Esempio n. 1
0
    def _update_mapper(self):
        """
        Map vtkPolyData to the actor.
        """
        polydata = vtk.vtkPolyData()

        offsets = self._get_odf_offsets(self.mask)
        if len(offsets) == 0:
            self.mapper.SetInputData(polydata)
            return None

        sph_dirs = self._get_sphere_directions()
        sf = self._get_sf(self.mask)

        all_vertices = self._get_all_vertices(offsets, sph_dirs, sf)
        all_faces = self._get_all_faces(len(offsets), len(sph_dirs))
        all_colors = self._generate_color_for_vertices(sf)

        # TODO: There is a lot of deep copy here.
        # Optimize (see viz_network.py example).
        set_polydata_triangles(polydata, all_faces)
        set_polydata_vertices(polydata, all_vertices)
        set_polydata_colors(polydata, all_colors)

        self.mapper.SetInputData(polydata)
Esempio n. 2
0
def cube():
    my_polydata = vtk.vtkPolyData()

    my_vertices = np.array([[0.0, 0.0, 0.0],
                            [0.0, 0.0, 1.0],
                            [0.0, 1.0, 0.0],
                            [0.0, 1.0, 1.0],
                            [1.0, 0.0, 0.0],
                            [1.0, 0.0, 1.0],
                            [1.0, 1.0, 0.0],
                            [1.0, 1.0, 1.0]])

    my_vertices -= 0.5

    my_triangles = np.array([[0, 6, 4],
                            [0, 2, 6],
                            [0, 3, 2],
                            [0, 1, 3],
                            [2, 7, 6],
                            [2, 3, 7],
                            [4, 6, 7],
                            [4, 7, 5],
                            [0, 4, 5],
                            [0, 5, 1],
                            [1, 5, 7],
                            [1, 7, 3]], dtype='i8')

    set_polydata_vertices(my_polydata, my_vertices)
    set_polydata_triangles(my_polydata, my_triangles)
    return get_actor_from_polydata(my_polydata)
Esempio n. 3
0
def test_polydata_polygon(interactive=False):
    # Create a cube
    my_triangles = np.array([[0, 6, 4],
                             [0, 2, 6],
                             [0, 3, 2],
                             [0, 1, 3],
                             [2, 7, 6],
                             [2, 3, 7],
                             [4, 6, 7],
                             [4, 7, 5],
                             [0, 4, 5],
                             [0, 5, 1],
                             [1, 5, 7],
                             [1, 7, 3]], dtype='i8')
    my_vertices = np.array([[0.0, 0.0, 0.0],
                            [0.0, 0.0, 1.0],
                            [0.0, 1.0, 0.0],
                            [0.0, 1.0, 1.0],
                            [1.0, 0.0, 0.0],
                            [1.0, 0.0, 1.0],
                            [1.0, 1.0, 0.0],
                            [1.0, 1.0, 1.0]])
    colors = my_vertices * 255
    my_polydata = vtk.vtkPolyData()

    utils.set_polydata_vertices(my_polydata, my_vertices)
    utils.set_polydata_triangles(my_polydata, my_triangles)

    npt.assert_equal(len(my_vertices), my_polydata.GetNumberOfPoints())
    npt.assert_equal(len(my_triangles), my_polydata.GetNumberOfCells())
    npt.assert_equal(utils.get_polydata_normals(my_polydata), None)

    res_triangles = utils.get_polydata_triangles(my_polydata)
    res_vertices = utils.get_polydata_vertices(my_polydata)

    npt.assert_array_equal(my_vertices, res_vertices)
    npt.assert_array_equal(my_triangles, res_triangles)

    utils.set_polydata_colors(my_polydata, colors)
    npt.assert_equal(utils.get_polydata_colors(my_polydata), colors)

    utils.update_polydata_normals(my_polydata)
    normals = utils.get_polydata_normals(my_polydata)
    npt.assert_equal(len(normals), len(my_vertices))

    mapper = utils.get_polymapper_from_polydata(my_polydata)
    actor1 = utils.get_actor_from_polymapper(mapper)
    actor2 = utils.get_actor_from_polydata(my_polydata)

    scene = window.Scene()
    for actor in [actor1, actor2]:
        scene.add(actor)
        if interactive:
            window.show(scene)
        arr = window.snapshot(scene)

        report = window.analyze_snapshot(arr)
        npt.assert_equal(report.objects, 1)
Esempio n. 4
0
def _sphere(scale=1):

    vertices, faces = prim_sphere('symmetric362')

    from fury.utils import set_polydata_vertices, set_polydata_triangles, vtk
    polydata = vtk.vtkPolyData()

    set_polydata_vertices(polydata, scale * vertices)
    set_polydata_triangles(polydata, faces)
    from fury.utils import set_polydata_normals, normals_from_v_f

    normals = normals_from_v_f(scale * vertices, faces)
    set_polydata_normals(polydata, normals)
    return polydata, scale * vertices, normals
Esempio n. 5
0
def square(scale=1):
    polydata = vtk.vtkPolyData()

    vertices = np.array([[0.0, 0.0, 0.0],
                         [0.0, 1.0, 0.0],
                         [1.0, 1.0, 0.0],
                         [1.0, 0.0, 0.0]])

    vertices -= np.array([0.5, 0.5, 0])

    vertices = scale * vertices

    triangles = np.array([[0, 1, 2], [2, 3, 0]], dtype='i8')

    set_polydata_vertices(polydata, vertices)
    set_polydata_triangles(polydata, triangles)

    return get_actor_from_polydata(polydata)
Esempio n. 6
0
                       [2.0, 3.0, 0.0], #6
                       [1.5, 2.0, 0.0], #7
                       [0.25, 2.0, 0.0], #8
                       [1.25, 1.25, 0.0]]) #9

my_triangles = np.array([[1, 9, 0], #good
                         [1, 2, 3],
                         [3, 4, 5], #good
                         [5, 6, 7],
                         [7, 8, 9], #good
                         [1, 9, 3], #good
                         [3, 7, 9], #good
                         [3, 5, 7]], dtype='i8') #good

utils.set_polydata_vertices(my_polydata, my_vertices)
utils.set_polydata_triangles(my_polydata, my_triangles)

file_name = "my_star2D.vtk"
save_polydata(my_polydata, file_name)
print("Surface saved in " + file_name)

star_polydata = load_polydata(file_name)

star_vertices = utils.get_polydata_vertices(star_polydata)
colors = star_vertices * 255
utils.set_polydata_colors(star_polydata, colors)

print("new surface colors")
print(utils.get_polydata_colors(star_polydata))

# get vtkActor
Esempio n. 7
0
def custom_glyph(centers, directions=None, colors=(1, 0, 0),
                 normals=(1, 0, 0), sq_params=None,
                 geom='square', scale=1, **kwargs):
    """Return a custom glyph actor
    """
    if geom.lower() == 'square':
        unit_verts, unit_triangles = square()
        origin_z = 0
    elif geom.lower() == 'box':
        unit_verts, unit_triangles = box()
        origin_z = 0.5
    elif geom.lower() == 'octahedron':
        unit_verts, unit_triangles = octahedron()
        origin_z = 0.5
    elif geom.lower() == 'icosahedron':
        unit_verts, unit_triangles = icosahedron()
        origin_z = 0.5
    elif geom.lower() == 'superquadric':
        unit_verts, unit_triangles = superquadric(sq_params)
        origin_z = 0.5
    else:
        unit_verts, unit_triangles = None
        origin_z = 0

    # update vertices
    big_vertices = np.tile(unit_verts, (centers.shape[0], 1))
    big_centers = np.repeat(centers, unit_verts.shape[0], axis=0)
    # center it
    big_vertices -= np.array([0.5, 0.5, origin_z])
    # apply centers position
    big_vertices += big_centers
    # scale them
    if isinstance(scale, (list, tuple, np.ndarray)):
        scale = np.repeat(scale, unit_verts.shape[0], axis=0)
        scale = scale.reshape((big_vertices.shape[0], 1))
    big_vertices *= scale

    # update triangles
    big_triangles = np.tile(unit_triangles, (centers.shape[0], 1))
    z = np.repeat(np.arange(0, centers.shape[0] *
                            unit_verts.shape[0], step=unit_verts.shape[0]),
                            unit_triangles.shape[0],
                            axis=0).reshape((big_triangles.shape[0], 1))
    big_triangles = np.add(z, big_triangles, casting="unsafe")

    # update colors
    if isinstance(colors, (tuple, list)):
        colors = np.array([colors] * centers.shape[0])
    big_colors = np.repeat(colors*255, unit_verts.shape[0], axis=0)

    # update normals
    if isinstance(normals, (tuple, list)):
        normals = np.array([normals] * centers.shape[0])
    big_normals = np.repeat(normals, unit_verts.shape[0], axis=0)

    # if isinstance(normals, (tuple, list)):
    #     directions = np.array([directions] * centers.shape[0])
    # big_dirs = np.repeat(normals, unit_verts.shape[0], axis=0)
    r, p, t = cart2sphere(0, 0, 1)
    m = euler_matrix(r, p, t, 'rxzy')
    print(big_vertices)
    big_vertices -= big_centers
    big_vertices = np.dot(m[:3, :3], big_vertices.T).T + big_centers

    # Create a Polydata
    pd = vtk.vtkPolyData()
    set_polydata_vertices(pd, big_vertices)
    set_polydata_triangles(pd, big_triangles)
    set_polydata_colors(pd, big_colors)
    set_polydata_normals(pd, big_normals)
    update_polydata_normals(pd)

    current_actor = get_actor_from_polydata(pd)
    if geom.lower() == 'square':
        current_actor.GetProperty().BackfaceCullingOff()
    return current_actor
Esempio n. 8
0
# Create a cube with vertices and triangles as numpy arrays

my_vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0],
                        [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0],
                        [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]])
# the data type for vtk is needed to mention here, numpy.int64
my_triangles = np.array(
    [[0, 6, 4], [0, 2, 6], [0, 3, 2], [0, 1, 3], [2, 7, 6], [2, 3, 7],
     [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 3]],
    dtype='i8')

###############################################################################
# Set vertices and triangles in the ``vtkPolyData``

ut_vtk.set_polydata_vertices(my_polydata, my_vertices)
ut_vtk.set_polydata_triangles(my_polydata, my_triangles)

###############################################################################
# Save the ``vtkPolyData``

file_name = "my_cube.vtk"
io_vtk.save_polydata(my_polydata, file_name)
print("Surface saved in " + file_name)

###############################################################################
# Load the ``vtkPolyData``

cube_polydata = io_vtk.load_polydata(file_name)

###############################################################################
# add color based on vertices position
Esempio n. 9
0
File: actor.py Progetto: sitek/fury
def sphere(centers,
           colors,
           radii=1.,
           theta=16,
           phi=16,
           vertices=None,
           faces=None):
    """Visualize one or many spheres with different colors and radii

    Parameters
    ----------
    centers : ndarray, shape (N, 3)
    colors : ndarray (N,3) or (N, 4) or tuple (3,) or tuple (4,)
        RGB or RGBA (for opacity) R, G, B and A should be at the range [0, 1]
    radii : float or ndarray, shape (N,)
    theta : int
    phi : int
    vertices : ndarray, shape (N, 3)
    faces : ndarray, shape (M, 3)
        If faces is None then a sphere is created based on theta and phi angles
        If not then a sphere is created with the provided vertices and faces.

    Returns
    -------
    vtkActor

    Examples
    --------
    >>> from fury import window, actor
    >>> scene = window.Scene()
    >>> centers = np.random.rand(5, 3)
    >>> sphere_actor = actor.sphere(centers, window.colors.coral)
    >>> scene.add(sphere_actor)
    >>> # window.show(scene)

    """

    if np.array(colors).ndim == 1:
        colors = np.tile(colors, (len(centers), 1))

    if isinstance(radii, (float, int)):
        radii = radii * np.ones(len(centers), dtype='f8')

    pts = numpy_to_vtk_points(np.ascontiguousarray(centers))
    cols = numpy_to_vtk_colors(255 * np.ascontiguousarray(colors))
    cols.SetName('colors')

    radii_fa = numpy_support.numpy_to_vtk(np.ascontiguousarray(
        radii.astype('f8')),
                                          deep=0)
    radii_fa.SetName('rad')

    polydata_centers = vtk.vtkPolyData()
    polydata_sphere = vtk.vtkPolyData()

    if faces is None:
        src = vtk.vtkSphereSource()
        src.SetRadius(1)
        src.SetThetaResolution(theta)
        src.SetPhiResolution(phi)

    else:

        set_polydata_vertices(polydata_sphere, vertices)
        set_polydata_triangles(polydata_sphere, faces)

    polydata_centers.SetPoints(pts)
    polydata_centers.GetPointData().AddArray(radii_fa)
    polydata_centers.GetPointData().SetActiveScalars('rad')
    polydata_centers.GetPointData().AddArray(cols)

    glyph = vtk.vtkGlyph3D()

    if faces is None:
        glyph.SetSourceConnection(src.GetOutputPort())
    else:
        glyph.SetSourceData(polydata_sphere)

    glyph.SetInputData(polydata_centers)
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(glyph.GetOutput())
    mapper.SetScalarModeToUsePointFieldData()

    mapper.SelectColorArray('colors')

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Esempio n. 10
0
    def build_brain_demo(self, showm):
        # path = "/Users/koudoro/Software/temp/"
        path = "/pvw/data/"
        # lh_path = os.path.join(path, "100307_white_lh.vtk")
        # rh_path = os.path.join(path, "100307_white_rh.vtk")
        # lh_pd = load_polydata(lh_path)
        # rh_pd = load_polydata(rh_path)
        left_fname = os.path.join(path, 'pial_left.gii')
        right_fname = os.path.join(path, 'pial_right.gii')

        left_gii = nib.load(left_fname)
        right_gii = nib.load(right_fname)

        left_pointset = left_gii.darrays[
            0].data  # NIFTI_INTENT_POINTSET   1008
        left_triangles = left_gii.darrays[
            1].data  # NIFTI_INTENT_TRIANGLE   1009
        right_pointset = right_gii.darrays[0].data
        right_triangles = right_gii.darrays[1].data

        left_poly = vtk.vtkPolyData()
        right_poly = vtk.vtkPolyData()

        utils.set_polydata_vertices(left_poly, left_pointset)
        utils.set_polydata_triangles(left_poly, left_triangles)
        utils.set_polydata_vertices(right_poly, right_pointset)
        utils.set_polydata_triangles(right_poly, right_triangles)

        lh_actor = utils.get_actor_from_polydata(left_poly)
        rh_actor = utils.get_actor_from_polydata(right_poly)

        text_block = ui.TextBlock2D(text='',
                                    font_size=15,
                                    bold=True,
                                    color=(1, 1, 1))

        panel = ui.Panel2D(size=(250, 30),
                           position=(120, 30),
                           color=(.8, .8, .8),
                           opacity=0.1)
        panel.add_element(text_block, (0.1, 0.1))

        picker = vtk.vtkCellPicker()
        # picker = window.vtk.vtkPointPicker()
        # print(picker.GetTolerance())
        picker.SetTolerance(0.01)

        dummy_sphere = actor.sphere(centers=np.array([[0, 0, 0]]),
                                    radii=1,
                                    colors=np.array([[1, 1, 0, 1.]]))

        prev_translation = (0, 0, 0)

        def highlight(obj, event):
            if not hasattr(obj, 'selected'):
                obj.selected = False

            selected = obj.selected
            color = obj.default_color if selected else (1.0, 1.0, 1.0)
            if event == "RightButtonPressEvent":
                obj.GetProperty().SetColor(color)
                obj.selected = not obj.selected

        def left_click_callback(obj, event):
            local_showm = left_click_callback.showm
            local_picker = left_click_callback.picker
            local_dummy_sphere = left_click_callback.dummy_sphere
            local_prev_translation = left_click_callback.prev_translation
            local_text_block = left_click_callback.text_block
            x, y, z = obj.GetCenter()
            event_pos = local_showm.iren.GetEventPosition()

            local_picker.Pick(event_pos[0], event_pos[1], 0, local_showm.scene)

            # cell_index = picker.GetCellId()
            point_index = local_picker.GetPointId()
            #text = 'Face ID ' + str(cell_index) + '\n' + 'Point ID ' + str(point_index)
            pos = np.round(local_picker.GetMapperPosition(), 3)
            text = str(point_index) + ' ' + str(pos)

            pi, pj, pk = local_prev_translation
            local_dummy_sphere.SetPosition(-pi, -pj, -pk)

            i, j, k = local_picker.GetMapperPosition()

            local_dummy_sphere.SetPosition(i, j, k)
            local_text_block.message = text
            # local_showm.render()
            local_showm.prev_translation = pos

        left_click_callback.showm = showm
        left_click_callback.picker = picker
        left_click_callback.prev_translation = prev_translation
        left_click_callback.text_block = text_block
        left_click_callback.dummy_sphere = dummy_sphere

        lh_actor.AddObserver('LeftButtonPressEvent', left_click_callback, 1)
        rh_actor.AddObserver('LeftButtonPressEvent', left_click_callback, 1)

        rh_actor.selected = False
        lh_actor.selected = False
        rh_actor.default_color = (1.0, 0.5, 0.0)
        lh_actor.default_color = (1.0, 0.0, 0.5)
        rh_actor.AddObserver('RightButtonPressEvent', highlight, 1)
        rh_actor.AddObserver('RightButtonReleaseEvent', highlight, 1)
        lh_actor.AddObserver('RightButtonPressEvent', highlight, 1)
        lh_actor.AddObserver('RightButtonReleaseEvent', highlight, 1)

        return ('Brain Demo', [panel, lh_actor, rh_actor, dummy_sphere])
Esempio n. 11
0
def test_fireballs_on_canvas():
    scene = window.Scene()
    showm = window.ShowManager(scene)

    # colors = 255 * np.array([
    #     [.85, .07, .21], [.56, .14, .85], [.16, .65, .20], [.95, .73, .06],
    #     [.95, .55, .05], [.62, .42, .75], [.26, .58, .85], [.24, .82, .95],
    #     [.95, .78, .25], [.85, .58, .35], [1., 1., 1.]
    # ])
    colors = np.random.rand(1000000, 3) * 255
    n_points = colors.shape[0]
    np.random.seed(42)
    centers = 500 * np.random.rand(n_points, 3) - 250

    radius = .5 * np.ones(n_points)

    polydata = vtk.vtkPolyData()

    verts = np.array([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0],
                      [1.0, 0.0, 0.0]])
    verts -= np.array([0.5, 0.5, 0])

    big_verts = np.tile(verts, (centers.shape[0], 1))
    big_cents = np.repeat(centers, verts.shape[0], axis=0)

    big_verts += big_cents

    big_scales = np.repeat(radius, verts.shape[0], axis=0)

    big_verts *= big_scales[:, np.newaxis]

    tris = np.array([[0, 1, 2], [2, 3, 0]], dtype='i8')

    big_tris = np.tile(tris, (centers.shape[0], 1))
    shifts = np.repeat(
        np.arange(0, centers.shape[0] * verts.shape[0], verts.shape[0]),
        tris.shape[0])

    big_tris += shifts[:, np.newaxis]

    big_cols = np.repeat(colors, verts.shape[0], axis=0)

    big_centers = np.repeat(centers, verts.shape[0], axis=0)

    big_centers *= big_scales[:, np.newaxis]

    set_polydata_vertices(polydata, big_verts)
    set_polydata_triangles(polydata, big_tris)
    set_polydata_colors(polydata, big_cols)

    vtk_centers = numpy_support.numpy_to_vtk(big_centers, deep=True)
    vtk_centers.SetNumberOfComponents(3)
    vtk_centers.SetName("center")
    polydata.GetPointData().AddArray(vtk_centers)

    canvas_actor = get_actor_from_polydata(polydata)
    canvas_actor.GetProperty().BackfaceCullingOff()

    scene.add(canvas_actor)

    mapper = canvas_actor.GetMapper()

    mapper.MapDataArrayToVertexAttribute(
        "center", "center", vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, -1)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Vertex, "//VTK::ValuePass::Dec", True, """
        //VTK::ValuePass::Dec
        in vec3 center;
        out vec3 centeredVertexMC;
        """, False)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Vertex, "//VTK::ValuePass::Impl", True, """
        //VTK::ValuePass::Impl
        centeredVertexMC = vertexMC.xyz - center;
        float scalingFactor = 1. / abs(centeredVertexMC.x);
        centeredVertexMC *= scalingFactor;

        vec3 CameraRight_worldspace = vec3(MCVCMatrix[0][0], MCVCMatrix[1][0], MCVCMatrix[2][0]);
        vec3 CameraUp_worldspace = vec3(MCVCMatrix[0][1], MCVCMatrix[1][1], MCVCMatrix[2][1]);

        vec3 vertexPosition_worldspace = center + CameraRight_worldspace * .5 * centeredVertexMC.x + CameraUp_worldspace * .5 * centeredVertexMC.y;
        gl_Position = MCDCMatrix * vec4(vertexPosition_worldspace, 1.);
        """, False)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Fragment, "//VTK::ValuePass::Dec", True, """
        //VTK::ValuePass::Dec
        in vec3 centeredVertexMC;
        uniform float time;

        float snoise(vec3 uv, float res) {
            const vec3 s = vec3(1e0, 1e2, 1e3);
            uv *= res;
            vec3 uv0 = floor(mod(uv, res)) * s;
            vec3 uv1 = floor(mod(uv + vec3(1.), res)) * s;
            vec3 f = fract(uv);
            f = f * f * (3. - 2. * f);
            vec4 v = vec4(uv0.x + uv0.y + uv0.z, uv1.x + uv0.y + uv0.z,
                uv0.x + uv1.y + uv0.z, uv1.x + uv1.y + uv0.z);
            vec4 r = fract(sin(v * 1e-1) * 1e3);
            float r0 = mix(mix(r.x, r.y, f.x), mix(r.z, r.w, f.x), f.y);
            r = fract(sin((v + uv1.z - uv0.z) * 1e-1) * 1e3);
            float r1 = mix(mix(r.x, r.y, f.x), mix(r.z, r.w, f.x), f.y);
            return mix(r0, r1, f.z) * 2. - 1.;
        }
        """, False)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Fragment, "//VTK::Light::Impl", True, """
        // Renaming variables passed from the Vertex Shader
        vec3 color = vertexColorVSOutput.rgb;
        vec3 point = centeredVertexMC;
        float len = length(point);
        float fColor = 2. - 2. * len;
        vec3 coord = vec3(atan(point.x, point.y) / 6.2832 + .5, len * .4, .5);
        for(int i = 1; i <= 7; i++) {
            float power = pow(2., float(i));
            fColor += (1.5 / power) * snoise(coord +
                vec3(0., -time * .005, time * .001), power * 16.);
        }
        if(fColor < 0) discard;
        //color = vec3(fColor);
        color *= fColor;
        fragOutput0 = vec4(color, 1.);
        """, False)

    global timer
    timer = 0

    def timer_callback(obj, event):
        global timer
        timer += 1.
        showm.render()

    @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

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

    showm.initialize()
    showm.add_timer_callback(True, 100, timer_callback)
    showm.start()
Esempio n. 12
0
def test_spheres_on_canvas():

    scene = window.Scene()
    showm = window.ShowManager(scene, reset_camera=False)

    # colors = 255 * np.array([
    #     [.85, .07, .21], [.56, .14, .85], [.16, .65, .20], [.95, .73, .06],
    #     [.95, .55, .05], [.62, .42, .75], [.26, .58, .85], [.24, .82, .95],
    #     [.95, .78, .25], [.85, .58, .35], [1., 1., 1.]
    # ])
    n_points = 2000000
    colors = np.array([[255, 0, 0], [0, 255, 0],
                       [0, 0, 255]])  #255 * np.random.rand(n_points, 3)
    # n_points = colors.shape[0]
    np.random.seed(42)
    centers = np.array(
        [[2, 0, 0], [0, 2, 0], [0, 0, 0]]
    )  # 500 * np.random.rand(n_points, 3) - 250 # np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    radius = [2, 2, 2]  # np.random.rand(n_points) #  [1, 1, 2]

    polydata = vtk.vtkPolyData()

    verts, faces = fp.prim_square()

    big_verts = np.tile(verts, (centers.shape[0], 1))
    big_cents = np.repeat(centers, verts.shape[0], axis=0)

    big_verts += big_cents

    # print(big_verts)

    big_scales = np.repeat(radius, verts.shape[0], axis=0)

    # print(big_scales)

    big_verts *= big_scales[:, np.newaxis]

    # print(big_verts)

    tris = np.array([[0, 1, 2], [2, 3, 0]], dtype='i8')

    big_tris = np.tile(tris, (centers.shape[0], 1))
    shifts = np.repeat(
        np.arange(0, centers.shape[0] * verts.shape[0], verts.shape[0]),
        tris.shape[0])

    big_tris += shifts[:, np.newaxis]

    # print(big_tris)

    big_cols = np.repeat(colors, verts.shape[0], axis=0)

    # print(big_cols)

    big_centers = np.repeat(centers, verts.shape[0], axis=0)

    # print(big_centers)

    big_centers *= big_scales[:, np.newaxis]

    # print(big_centers)

    set_polydata_vertices(polydata, big_verts)
    set_polydata_triangles(polydata, big_tris)
    set_polydata_colors(polydata, big_cols)

    vtk_centers = numpy_support.numpy_to_vtk(big_centers, deep=True)
    vtk_centers.SetNumberOfComponents(3)
    vtk_centers.SetName("center")
    polydata.GetPointData().AddArray(vtk_centers)

    canvas_actor = get_actor_from_polydata(polydata)
    canvas_actor.GetProperty().BackfaceCullingOff()

    scene.add(canvas_actor)

    mapper = canvas_actor.GetMapper()

    mapper.MapDataArrayToVertexAttribute(
        "center", "center", vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, -1)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Vertex, "//VTK::ValuePass::Dec", True, """
        //VTK::ValuePass::Dec
        in vec3 center;

        uniform mat4 Ext_mat;

        out vec3 centeredVertexMC;
        out vec3 cameraPosition;
        out vec3 viewUp;

        """, False)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Vertex, "//VTK::ValuePass::Impl", True, """
        //VTK::ValuePass::Impl
        centeredVertexMC = vertexMC.xyz - center;
        float scalingFactor = 1. / abs(centeredVertexMC.x);
        centeredVertexMC *= scalingFactor;

        vec3 CameraRight_worldspace = vec3(MCVCMatrix[0][0], MCVCMatrix[1][0], MCVCMatrix[2][0]);
        vec3 CameraUp_worldspace = vec3(MCVCMatrix[0][1], MCVCMatrix[1][1], MCVCMatrix[2][1]);

        vec3 vertexPosition_worldspace = center + CameraRight_worldspace * 1 * centeredVertexMC.x + CameraUp_worldspace * 1 * centeredVertexMC.y;
        gl_Position = MCDCMatrix * vec4(vertexPosition_worldspace, 1.);

        """, False)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Fragment, "//VTK::ValuePass::Dec", True, """
        //VTK::ValuePass::Dec
        in vec3 centeredVertexMC;
        in vec3 cameraPosition;
        in vec3 viewUp;

        uniform vec3 Ext_camPos;
        uniform vec3 Ext_viewUp;
        """, False)

    mapper.AddShaderReplacement(
        vtk.vtkShader.Fragment, "//VTK::Light::Impl", True, """
        // Renaming variables passed from the Vertex Shader
        vec3 color = vertexColorVSOutput.rgb;
        vec3 point = centeredVertexMC;
        fragOutput0 = vec4(color, 0.7);
        /*
        // Comparing camera position from vertex shader and python
        float dist = distance(cameraPosition, Ext_camPos);
        if(dist < .0001)
            fragOutput0 = vec4(1, 0, 0, 1);
        else
            fragOutput0 = vec4(0, 1, 0, 1);


        // Comparing view up from vertex shader and python
        float dist = distance(viewUp, Ext_viewUp);
        if(dist < .0001)
            fragOutput0 = vec4(1, 0, 0, 1);
        else
            fragOutput0 = vec4(0, 1, 0, 1);
        */
        float len = length(point);
        // VTK Fake Spheres
        float radius = 1.;
        if(len > radius)
          discard;
        vec3 normalizedPoint = normalize(vec3(point.xy, sqrt(1. - len)));
        vec3 direction = normalize(vec3(1., 1., 1.));
        float df = max(0, dot(direction, normalizedPoint));
        float sf = pow(df, 24);
        fragOutput0 = vec4(max(df * color, sf * vec3(1)), 1);
        """, False)

    @vtk.calldata_type(vtk.VTK_OBJECT)
    def vtk_shader_callback(caller, event, calldata=None):
        res = scene.size()
        camera = scene.GetActiveCamera()
        cam_pos = camera.GetPosition()
        foc_pnt = camera.GetFocalPoint()
        view_up = camera.GetViewUp()
        # cam_light_mat = camera.GetCameraLightTransformMatrix()
        # comp_proj_mat = camera.GetCompositeProjectionTransformMatrix()
        # exp_proj_mat = camera.GetExplicitProjectionTransformMatrix()
        # eye_mat = camera.GetEyeTransformMatrix()
        # model_mat = camera.GetModelTransformMatrix()
        # model_view_mat = camera.GetModelViewTransformMatrix()
        # proj_mat = camera.GetProjectionTransformMatrix(scene)
        view_mat = camera.GetViewTransformMatrix()
        mat = view_mat
        np.set_printoptions(precision=3, suppress=True)
        np_mat = np.zeros((4, 4))
        for i in range(4):
            for j in range(4):
                np_mat[i, j] = mat.GetElement(i, j)
        program = calldata
        if program is not None:
            # print("\nCamera position: {}".format(cam_pos))
            # print("Focal point: {}".format(foc_pnt))
            # print("View up: {}".format(view_up))
            # print(mat)
            # print(np_mat)
            # print(np.dot(-np_mat[:3, 3], np_mat[:3, :3]))
            # a = np.array(cam_pos) - np.array(foc_pnt)
            # print(a / np.linalg.norm(a))
            # print(cam_light_mat)
            # #print(comp_proj_mat)
            # print(exp_proj_mat)
            # print(eye_mat)
            # print(model_mat)
            # print(model_view_mat)
            # print(proj_mat)
            # print(view_mat)
            program.SetUniform2f("Ext_res", res)
            program.SetUniform3f("Ext_camPos", cam_pos)
            program.SetUniform3f("Ext_focPnt", foc_pnt)
            program.SetUniform3f("Ext_viewUp", view_up)
            program.SetUniformMatrix("Ext_mat", mat)

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

    global timer
    timer = 0

    def timer_callback(obj, event):
        global timer
        timer += 1.
        showm.render()
        scene.azimuth(2)
        # scene.elevation(5)
        # scene.roll(5)

    label = vtk.vtkOpenGLBillboardTextActor3D()
    label.SetInput("FURY Rocks!!!")
    label.SetPosition(1., 1., 1)
    label.GetTextProperty().SetFontSize(40)
    label.GetTextProperty().SetColor(.5, .5, .5)
    # TODO: Get Billboard's mapper
    # l_mapper = label.GetActors()

    # scene.add(label)
    scene.add(actor.axes())

    scene.background((1, 1, 1))

    # scene.set_camera(position=(1.5, 2.5, 15), focal_point=(1.5, 2.5, 1.5),
    #                  view_up=(0, 1, 0))
    scene.set_camera(position=(1.5, 2.5, 25),
                     focal_point=(0, 0, 0),
                     view_up=(0, 1, 0))
    showm.initialize()
    showm.add_timer_callback(True, 100, timer_callback)
    showm.start()
Esempio n. 13
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebSpheres.authKey)

        # Create default pipeline (Only once for all the session)
        if not _WebSpheres.view:
            # FURY specific code
            scene = window.Scene()
            scene.background((1, 1, 1))

            n_points = 1000000
            translate = 100
            colors = 255 * np.random.rand(n_points, 3)
            centers = translate * np.random.rand(n_points, 3) - translate / 2
            radius = np.random.rand(n_points) / 10

            polydata = vtk.vtkPolyData()

            verts = np.array([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0],
                              [1.0, 1.0, 0.0], [1.0, 0.0, 0.0]])
            verts -= np.array([0.5, 0.5, 0])

            big_verts = np.tile(verts, (centers.shape[0], 1))
            big_cents = np.repeat(centers, verts.shape[0], axis=0)

            big_verts += big_cents

            # print(big_verts)

            big_scales = np.repeat(radius, verts.shape[0], axis=0)

            # print(big_scales)

            big_verts *= big_scales[:, np.newaxis]

            # print(big_verts)

            tris = np.array([[0, 1, 2], [2, 3, 0]], dtype='i8')

            big_tris = np.tile(tris, (centers.shape[0], 1))
            shifts = np.repeat(
                np.arange(0, centers.shape[0] * verts.shape[0],
                          verts.shape[0]), tris.shape[0])

            big_tris += shifts[:, np.newaxis]

            # print(big_tris)

            big_cols = np.repeat(colors, verts.shape[0], axis=0)

            # print(big_cols)

            big_centers = np.repeat(centers, verts.shape[0], axis=0)

            # print(big_centers)

            big_centers *= big_scales[:, np.newaxis]

            # print(big_centers)

            set_polydata_vertices(polydata, big_verts)
            set_polydata_triangles(polydata, big_tris)
            set_polydata_colors(polydata, big_cols)

            vtk_centers = numpy_to_vtk(big_centers, deep=True)
            vtk_centers.SetNumberOfComponents(3)
            vtk_centers.SetName("center")
            polydata.GetPointData().AddArray(vtk_centers)

            canvas_actor = get_actor_from_polydata(polydata)
            canvas_actor.GetProperty().BackfaceCullingOff()

            mapper = canvas_actor.GetMapper()

            mapper.MapDataArrayToVertexAttribute(
                "center", "center", vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,
                -1)

            vtk_major_version = vtk.vtkVersion.GetVTKMajorVersion()
            vtk_minor_version = vtk.vtkVersion.GetVTKMinorVersion()
            if vtk_major_version > 8 or (vtk_major_version == 8
                                         and vtk_minor_version >= 90):
                mapper = canvas_actor.GetShaderProperty()

            mapper.AddShaderReplacement(
                vtk.vtkShader.Vertex, "//VTK::ValuePass::Dec", True, """
                //VTK::ValuePass::Dec
                in vec3 center;

                out vec3 centeredVertexMC;
                """, False)

            mapper.AddShaderReplacement(
                vtk.vtkShader.Vertex, "//VTK::ValuePass::Impl", True, """
                //VTK::ValuePass::Impl
                centeredVertexMC = vertexMC.xyz - center;
                float scalingFactor = 1. / abs(centeredVertexMC.x);
                centeredVertexMC *= scalingFactor;

                vec3 cameraRight = vec3(MCVCMatrix[0][0], MCVCMatrix[1][0],
                                        MCVCMatrix[2][0]);
                vec3 cameraUp = vec3(MCVCMatrix[0][1], MCVCMatrix[1][1],
                                     MCVCMatrix[2][1]);
                vec2 squareVertices = vec2(.5, -.5);
                vec3 vertexPosition = center + cameraRight * squareVertices.x *
                                      vertexMC.x + cameraUp * squareVertices.y *
                                      vertexMC.y;
                gl_Position = MCDCMatrix * vec4(vertexPosition, 1.);
                gl_Position /= gl_Position.w;
                """, False)

            mapper.AddShaderReplacement(
                vtk.vtkShader.Fragment, "//VTK::ValuePass::Dec", True, """
                //VTK::ValuePass::Dec
                in vec3 centeredVertexMC;
                """, False)

            mapper.AddShaderReplacement(
                vtk.vtkShader.Fragment, "//VTK::Light::Impl", True, """
                // Renaming variables passed from the Vertex Shader
                vec3 color = vertexColorVSOutput.rgb;
                vec3 point = centeredVertexMC;
                float len = length(point);
                // VTK Fake Spheres
                float radius = 1.;
                if(len > radius)
                  discard;
                vec3 normalizedPoint = normalize(vec3(point.xy, sqrt(1. - len)));
                vec3 direction = normalize(vec3(1., -1., 1.));
                float df = max(0, dot(direction, normalizedPoint));
                float sf = pow(df, 24);
                fragOutput0 = vec4(max(df * color, sf * vec3(1)), 1);
                """, False)

            scene.add(canvas_actor)
            #scene.add(actor.axes())

            showm = window.ShowManager(scene)

            renderWindow = showm.window

            # VTK Web application specific
            _WebSpheres.view = renderWindow
            self.getApplication().GetObjectIdMap().\
                SetActiveObject('VIEW', renderWindow)
Esempio n. 14
0
def rectangle2(centers, colors, use_vertices=False, size=(2, 2)):
    """Visualize one or many spheres with different colors and radii

    Parameters
    ----------
    centers : ndarray, shape (N, 3)
    colors : ndarray (N,3) or (N, 4) or tuple (3,) or tuple (4,)
        RGB or RGBA (for opacity) R, G, B and A should be at the range [0, 1]
    """
    if np.array(colors).ndim == 1:
        colors = np.tile(colors, (len(centers), 1))

    pts = numpy_to_vtk_points(np.ascontiguousarray(centers))
    cols = numpy_to_vtk_colors(255 * np.ascontiguousarray(colors))
    cols.SetName('colors')

    polydata_centers = vtk.vtkPolyData()

    polydata_centers.SetPoints(pts)
    polydata_centers.GetPointData().AddArray(cols)

    print("NB pts: ", polydata_centers.GetNumberOfPoints())
    print("NB arrays: ", polydata_centers.GetPointData().GetNumberOfArrays())

    for i in range(polydata_centers.GetPointData().GetNumberOfArrays()):
        print("Array {0}: {1}".format(
            i, polydata_centers.GetPointData().GetArrayName(i)))

    for i in range(polydata_centers.GetCellData().GetNumberOfArrays()):
        print("Cell {0}: {1}".format(
            i, polydata_centers.GetCellData().GetArrayName(i)))

    print("Array pts: {}".format(
        polydata_centers.GetPoints().GetData().GetName()))

    glyph = vtk.vtkGlyph3D()
    if use_vertices:
        scale = 1
        my_polydata = vtk.vtkPolyData()
        my_vertices = np.array([[0.0, 0.0, 0.0],
                                [0.0, 1.0, 0.0],
                                [1.0, 1.0, 0.0],
                                [1.0, 0.0, 0.0]])

        my_vertices -= np.array([0.5, 0.5, 0])

        my_vertices = scale * my_vertices

        my_triangles = np.array([[0, 1, 2],
                                 [2, 3, 0]], dtype='i8')

        set_polydata_vertices(my_polydata, my_vertices)
        set_polydata_triangles(my_polydata, my_triangles)

        glyph.SetSourceData(my_polydata)
    else:
        src = vtk.vtkPlaneSource()
        src.SetXResolution(size[0])
        src.SetYResolution(size[1])
        glyph.SetSourceConnection(src.GetOutputPort())

    glyph.SetInputData(polydata_centers)
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(glyph.GetOutput())
    mapper.SetScalarModeToUsePointFieldData()

    mapper.SelectColorArray('colors')

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor