Exemplo 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)
Exemplo n.º 2
0
def generate_points():
    centers = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

    colors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) * 255

    vtk_vertices = Points()
    # Create the topology of the point (a vertex)
    vtk_faces = CellArray()
    # Add points
    for i in range(len(centers)):
        p = centers[i]
        id = vtk_vertices.InsertNextPoint(p)
        vtk_faces.InsertNextCell(1)
        vtk_faces.InsertCellPoint(id)
    # Create a polydata object
    polydata = PolyData()
    # Set the vertices and faces we created as the geometry and topology of the
    # polydata
    polydata.SetPoints(vtk_vertices)
    polydata.SetVerts(vtk_faces)

    set_polydata_colors(polydata, colors)

    mapper = PolyDataMapper()
    mapper.SetInputData(polydata)
    mapper.SetVBOShiftScaleMethod(False)

    point_actor = Actor()
    point_actor.SetMapper(mapper)

    return point_actor
Exemplo 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)
Exemplo n.º 4
0
                         [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
star_actor = utils.get_actor_from_polydata(star_polydata)
star_actor.GetProperty().BackfaceCullingOff()
# Create a scene
scene = window.Scene()
scene.add(star_actor)
scene.set_camera(position=(0, 0, 7), focal_point=(0, 0, 0))
scene.zoom(3)

# display
# window.show(scene, size=(1000, 1000), reset_camera=False) this allows the picture to be moved around
Exemplo n.º 5
0
                         [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_colors = my_vertices * 255  # transform from [0, 1] to [0, 255]

# use a FURY util to apply the above values to the polydata
utils.set_polydata_vertices(my_polydata, my_vertices)
utils.set_polydata_triangles(my_polydata, my_triangles)
utils.set_polydata_colors(my_polydata, my_colors)

# in VTK, shaders are applied at the mapper level
# get mapper from polydata
cube_actor = utils.get_actor_from_polydata(my_polydata)
mapper = cube_actor.GetMapper()

# add the cube to a scene and show it
scene = window.Scene()
scene.add(cube_actor)

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

window.show(scene, size=(500, 500))

# let's use a frag shader to change how the cube is rendered
Exemplo n.º 6
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
Exemplo n.º 7
0
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

cube_vertices = ut_vtk.get_polydata_vertices(cube_polydata)
colors = cube_vertices * 255
ut_vtk.set_polydata_colors(cube_polydata, colors)

print("new surface colors")
print(ut_vtk.get_polydata_colors(cube_polydata))

###############################################################################
# Visualize surfaces

# get vtkActor
cube_actor = ut_vtk.get_actor_from_polydata(cube_polydata)

# renderer and scene
renderer = window.Renderer()
renderer.add(cube_actor)
renderer.set_camera(position=(10, 5, 7), focal_point=(0.5, 0.5, 0.5))
renderer.zoom(3)
Exemplo n.º 8
0
                         [3, 15, 16],
                         [3, 4, 16], #end of shape
                         ], dtype='i8')

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

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

rhombicube_polydata = load_polydata(file_name)

rhombicube_vertices = utils.get_polydata_vertices(rhombicube_polydata)
colors = rhombicube_vertices * 255
utils.set_polydata_colors(rhombicube_polydata, colors)

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

# get vtkActor
rhombicube_actor = utils.get_actor_from_polydata(rhombicube_polydata)
rhombicube_actor.GetProperty().BackfaceCullingOff() #gets rid of the winding order issue (look at later and other algorithms that get rid of winding order)

# Create a scene
scene = window.Scene()
scene.add(rhombicube_actor)
scene.set_camera(position=(0, 0, 7), focal_point=(0, 0, 0))
scene.zoom(0)

# display
Exemplo n.º 9
0
file_name = "my_cube.vtk"
save_polydata(my_polydata, file_name)
print("Surface saved in " + file_name)

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

cube_polydata = load_polydata(file_name)

###############################################################################
# add color based on vertices position

cube_vertices = utils.get_polydata_vertices(cube_polydata)
colors = cube_vertices * 255
utils.set_polydata_colors(cube_polydata, colors)

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

###############################################################################
# Visualize surfaces

# get vtkActor
cube_actor = utils.get_actor_from_polydata(cube_polydata)

# Create a scene
scene = window.Scene()
scene.add(cube_actor)
scene.set_camera(position=(10, 5, 7), focal_point=(0.5, 0.5, 0.5))
scene.zoom(3)
Exemplo n.º 10
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()
Exemplo n.º 11
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()
Exemplo n.º 12
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)