Example #1
0
 def __init__(self, width=500, height=500):
     self.mesh_shader = load_shader('visualization/shader/mesh')
     trackball = Trackball(Position("position"))
     self.mesh_shader['transform'] = trackball
     trackball.theta, trackball.phi, trackball.zoom = 80, -135, 5
     self.img_shader = load_shader('visualization/shader/image')
     self.img_shader['position'] = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
     self.window = self.set_window(width, height)
     self.click = None
     self.click_callback = None
     self.key_dict = {}
     self.vertices = None
Example #2
0
def mostrar(V, T, N, F_V, F_T, F_N):
    # Building the vertices
    V = np.array(V)
    F_V = np.array(F_V)
    vtype = [('position', np.float32, 3)]

    if len(N):
        N = np.array(N)
        F_N = np.array(F_N)
        vtype.append(('normal', np.float32, 3))

    vertices = np.empty(len(F_V), vtype)
    vertices["position"] = V[F_V, :3]
    if len(N) and len(F_N):
        vertices["normal"] = N[F_N]
    vertices = vertices.view(gloo.VertexBuffer)

    # Centering and scaling to fit the unit box
    xmin, xmax = vertices["position"][:,
                                      0].min(), vertices["position"][:,
                                                                     0].max()
    ymin, ymax = vertices["position"][:,
                                      1].min(), vertices["position"][:,
                                                                     1].max()
    zmin, zmax = vertices["position"][:,
                                      2].min(), vertices["position"][:,
                                                                     2].max()
    vertices["position"][:, 0] -= (xmax + xmin) / 2.0
    vertices["position"][:, 1] -= (ymax + ymin) / 2.0
    vertices["position"][:, 2] -= (zmax + zmin) / 2.0
    scale = max(max(xmax - xmin, ymax - ymin), zmax - zmin) / 2.0
    vertices["position"] /= scale

    obj.bind(vertices)
    trackball = Trackball(Position("position"))
    obj['transform'] = trackball
    trackball.theta, trackball.phi, trackball.zoom = 90, 0, 18
    window.attach(obj['transform'])
    app.run()
def init_all_cubes(data):
    global window, CUBES, vertex, fragment

    vertices, faces, outline = custom_cube_2(-1, -1, 1, 1, 1)

    cube = gloo.Program(vertex, fragment)
    cube.bind(vertices)
    cube['transform'] = Trackball(Position("position"))
    cube['view'] = view
    window.attach(cube['transform'])
    CUBES.append(cube)
    VIO.append((vertices, faces, outline))

    for x, y, height, width, length in data:
        vertices, faces, outline = custom_cube(x, y, height, width, length)

        cube = gloo.Program(vertex, fragment)
        cube.bind(vertices)
        cube['transform'] = Trackball(Position("position"))
        cube['view'] = view
        window.attach(cube['transform'])
        CUBES.append(cube)
        VIO.append((vertices, faces, outline))
Example #4
0
def main():
    window = app.Window(width=800, height=800, color=(1, 1, 1, 1))

    protein = gloo.Program(vertex, fragment)
    protein['light_position'] = 0., 0., 2.
    protein["transform"] = Trackball(Position())
    protein.bind(data.get("protein.npy").view(gloo.VertexBuffer))
    protein['color'] *= .25
    protein['color'] += .75

    @window.event
    def on_draw(dt):
        window.clear()
        protein.draw(gl.GL_POINTS)

    @window.event
    def on_init():
        gl.glEnable(gl.GL_DEPTH_TEST)

    window.attach(protein["transform"])
    app.run()
Example #5
0
program['u_antialias'] = 1.0

# Polar domains
program['u_major_grid_step'] = np.array([ 1.00, np.pi/6])
program['u_minor_grid_step'] = np.array([ 0.25, np.pi/60])
program['u_limits1'] = -5.1, +5.1, -5.1, +5.1
program['u_limits2'] = 1.0, 5.0, 0*np.pi, 2*np.pi

# Cartesian domains
# program['u_major_grid_step'] = np.array([ 1.00, 1.00])
# program['u_minor_grid_step'] = np.array([ 0.10, 0.10])
# program['u_limits1'] = -5.1, +5.1, -5.1, +5.1
# program['u_limits2'] = -5.0, +5.0, -5.0, +5.0

# Hammer domains
# program['u_major_grid_step'] = np.array([ 1.00, 0.50]) * np.pi/ 6.0
# program['u_minor_grid_step'] = np.array([ 1.00, 0.50]) * np.pi/30.0
# program['u_limits1'] = -3.0, +3.0, -1.5, +1.5
# program['u_limits2'] = -np.pi, +np.pi, -np.pi/3, +np.pi/3

program['transform'] = shaders.get("transforms/polar.glsl")
# program['transform'] = shaders.get("transforms/identity.glsl")
# program['transform'] = shaders.get("transforms/hammer.glsl")
program['trackball'] = Trackball(Position2D("texcoord"))
program['trackball'].theta = 0
program['trackball'].phi = 0
program['trackball'].zoom = 7.5
window.attach(program['trackball'])

app.run()
Example #6
0
# program['u_minor_grid_step'] = np.array([ 0.25, np.pi/60])
# program['u_limits1'] = -5.1, +5.1, -5.1, +5.1
# program['u_limits2'] = 1.0, 5.0, 0*np.pi, 2*np.pi

# Cartesian domains
program['u_major_grid_step'] = np.array([1.00, 1.00])
program['u_minor_grid_step'] = np.array([0.10, 0.10])
program['u_limits1'] = -5.1, +5.1, -5.1, +5.1
program['u_limits2'] = -5.0, +5.0, -5.0, +5.0

# Hammer domains
# program['u_major_grid_step'] = np.array([ 1.00, 0.50]) * np.pi/ 6.0
# program['u_minor_grid_step'] = np.array([ 1.00, 0.50]) * np.pi/30.0
# program['u_limits1'] = -3.0, +3.0, -1.5, +1.5
# program['u_limits2'] = -np.pi, +np.pi, -np.pi/3, +np.pi/3

# program['transform'] = shaders.get("transforms/polar.glsl")
# program['transform'] = shaders.get("transforms/hammer.glsl")
program['transform_forward'] = gloo.Snippet(
    library.get("transforms/identity_forward.glsl"))
program['transform_inverse'] = gloo.Snippet(
    library.get("transforms/identity_inverse.glsl"))
program['trackball'] = Trackball(Position("texcoord"))
program['trackball'].theta = 0
program['trackball'].phi = 0
program['trackball'].zoom = 7.5

window.attach(program['trackball'])

app.run()
    cube.draw(gl.GL_TRIANGLES, faces)

    # Outlined cube
    gl.glDisable(gl.GL_POLYGON_OFFSET_FILL)
    gl.glEnable(gl.GL_BLEND)
    gl.glDepthMask(gl.GL_FALSE)
    cube['u_color'] = 0, 0, 0, 1
    cube.draw(gl.GL_LINES, outline)
    gl.glDepthMask(gl.GL_TRUE)


# Build cube data
V, I, O = colorcube()
vertices = V.view(gloo.VertexBuffer)
faces = I.view(gloo.IndexBuffer)
outline = O.view(gloo.IndexBuffer)

cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
cube['transform'] = Trackball(Position("position"))
window.attach(cube['transform'])

# OpenGL initalization
gl.glEnable(gl.GL_DEPTH_TEST)
gl.glPolygonOffset(1, 1)
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

# Run
app.run()
Example #8
0
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 - y**2)


x = np.linspace(-2.0, 2.0, 32).astype(np.float32)
y = np.linspace(-2.0, 2.0, 32).astype(np.float32)
X, Y = np.meshgrid(x, y)
Z = func3(X, Y)

surface['data'] = (Z - Z.min()) / (Z.max() - Z.min())
surface['data'].interpolation = gl.GL_NEAREST
surface['data_shape'] = Z.shape[1], Z.shape[0]
surface['u_kernel'] = data.get("spatial-filters.npy")
surface['u_kernel'].interpolation = gl.GL_LINEAR
surface['texture'] = data.checkerboard(32, 24)

transform = Trackball("vec4(position.xy, z, 1.0)")
surface['transform'] = transform
window.attach(transform)

T = (Z - Z.min()) / (Z.max() - Z.min())

surface['height'] = 0.75
surface["light_position[0]"] = 3, 0, 0 + 5
surface["light_position[1]"] = 0, 3, 0 + 5
surface["light_position[2]"] = -3, -3, +5
surface["light_color[0]"] = 1, 0, 0
surface["light_color[1]"] = 0, 1, 0
surface["light_color[2]"] = 0, 0, 1
phi, theta = -45, 0
time = 0
Example #9
0
File: oit.py Project: jk34/glumpy
framebuffer = gloo.FrameBuffer(color=[accumulation,revealage])

# Three quads
quads = gloo.Program(vert_quads, frag_quads, count=12)
quads["position"] = [ (-1,-1,-1), (-1,+1,-1), (+1,-1,-1), (+1,+1,-1),
                      (-1,-1, 0), (-1,+1, 0), (+1,-1, 0), (+1,+1, 0),
                      (-1,-1,+1), (-1,+1,+1), (+1,-1,+1), (+1,+1,+1) ]
quads["position"] *= 10

quads["color"] = C1,C1,C1,C1, C2,C2,C2,C2, C3,C3,C3,C3
indices = np.zeros((3,6),dtype=np.uint32)
indices[0] = 0 + np.array([0,1,2,1,2,3]) 
indices[1] = 4 + np.array([0,1,2,1,2,3]) 
indices[2] = 8 + np.array([0,1,2,1,2,3]) 
indices = indices.view(gloo.IndexBuffer)

# Post composition
post = gloo.Program(vert_post, frag_post)
post['tex_accumulation'] = accumulation
post['tex_revealage']    = revealage
post['position']  = [(-1,-1), (-1,1), (1,-1), (1,1)]

trackball = Trackball(Position("position"), znear=0.1, zfar=100.0, distance=50)
quads['transform'] = trackball
trackball.theta = 40
trackball.phi = 45
trackball.zoom = 40
window.attach(quads['transform'])

app.run()
Example #10
0
        float specular_angle = max(dot(half_direction, normal), 0.0);
        specular = pow(specular_angle, shininess);
    }
    vec3 color_linear = ambient_color +
                        lambertian * diffuse_color +
                        specular * specular_color;
    vec3 color_gamma = pow(color_linear, vec3(1.0/gamma));
    gl_FragColor = vec4(color_gamma, 1.0);
}
"""

log.info("Loading brain mesh")
vertices, indices = data.get("brain.obj")
brain = gloo.Program(vertex, fragment)
brain.bind(vertices)
trackball = Trackball(Position("position"))
brain['transform'] = trackball
trackball.theta, trackball.phi, trackball.zoom = 80, -135, 15

window = app.Window(width=1024, height=768)


def update():
    model = brain['transform']['model'].reshape(4, 4)
    view = brain['transform']['view'].reshape(4, 4)
    brain['m_view'] = view
    brain['m_model'] = model
    brain['m_normal'] = np.array(np.matrix(np.dot(view, model)).I.T)


@window.event
Example #11
0

@window.event
def on_resize(width, height):
    cube['u_projection'] = glm.perspective(45.0, width / float(height), 2.0,
                                           100.0)


@window.event
def on_init():
    #gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glPolygonOffset(1, 1)
    gl.glEnable(gl.GL_LINE_SMOOTH)


vertices, indices = cube()
cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
cube['transform'] = Trackball(Position("position"),
                              znear=0.1,
                              zfar=100.0,
                              distance=10,
                              aspect=1)
cube['u_texture'] = np.array(imread('data.png', mode='RGBA')) / 255.0
cube['u_model'] = np.eye(4, dtype=np.float32)
cube['u_view'] = glm.translation(0, 0, -5)
window.attach(cube['transform'])
phi, theta = 40, 30

app.run()
Example #12
0
    cube.draw(gl.GL_TRIANGLES, faces)

    # Outlined cube
    gl.glDisable(gl.GL_POLYGON_OFFSET_FILL)
    gl.glEnable(gl.GL_BLEND)
    gl.glDepthMask(gl.GL_FALSE)
    cube["u_color"] = 0, 0, 0, 1
    cube.draw(gl.GL_LINES, outline)
    gl.glDepthMask(gl.GL_TRUE)


# Build cube data
V, I, O = colorcube()
vertices = V.view(gloo.VertexBuffer)
faces = I.view(gloo.IndexBuffer)
outline = O.view(gloo.IndexBuffer)

cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
cube["transform"] = Trackball(Position("position"))
window.attach(cube["transform"])

# OpenGL initalization
gl.glEnable(gl.GL_DEPTH_TEST)
gl.glPolygonOffset(1, 1)
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

# Run
app.run()
Example #13
0
# print(dt.min(), dt.max(), dt.mean())
idx = np.where(dt > 0.5)
blue = np.linspace(0.7, 0.0, len(t))
green = np.linspace(0.7, 0.0, len(t))
red = np.ones_like(t) * 1.0
alpha = np.ones_like(t) * 0.5
red[idx] = 0.0
green[idx] = 0.0
blue[idx] = 1.0
alpha[idx] = 1.0
radius = np.ones_like(t)
radius[0] = 10

points = gloo.Program(vertex, fragment, count=len(x))
points['a_position'] = np.dstack((x, y, z))[0]
points['transform'] = Trackball(Position('a_position'))
points['a_color'] = np.dstack((red, green, blue, alpha))[0]
points['a_radius'] = radius
window.attach(points['transform'])
pidx = 0

pointsCol = PointCollection('agg', color='local', size='local')
window.attach(pointsCol['transform'])
# window.attach(pointsCol['viewport'])

if os.path.isfile('active_site.pt'):
    print('... plot with active_site.pt')
    data = np.genfromtxt('active_site.pt',
                         dtype=[('x', 'f8'), ('y', 'f8'), ('z', 'f8')])
    apoint = gloo.Program(vertex, fragment, count=len(data))
    apoint['a_position'] = np.dstack((data['x'], data['y'], data['z']))[0]
Example #14
0
    def plot(self, cmap=None, color_function=None):
        """ Method used to plot a surface. """
        print("Plotting object of dimension: {}".format(
            self.decomposition.dimension))

        data = self.decomposition
        tuples = data.surface.surface_sampler_data
        points = extract_points(data)

        triangle = []
        for i in range(len(tuples)):
            for tri in tuples[i]:
                x_coordinate = int(tri[0])
                y_coordinate = int(tri[1])
                z_coordinate = int(tri[2])

                point = [x_coordinate, y_coordinate, z_coordinate]
                triangle.append(point)

        triangle = np.asarray(triangle)

        # ----------------------------------------------------------------------------- #
        #                    Vertex and fragment are OpenGL code
        # ----------------------------------------------------------------------------- #

        vertex = """
        attribute vec4 a_color;         // Vertex Color
        uniform mat4   u_model;         // Model matrix
        uniform mat4   u_view;          // View matrix
        uniform mat4   u_projection;    // Projection matrix
        attribute vec3 position;        // Vertex position
        varying vec4   v_color;         // Interpolated fragment color (out)
        void main()
        {
            v_color = a_color;
            gl_Position = <transform>;
        }
        """

        fragment = """
        varying vec4  v_color;          // Interpolated fragment color (in)
        void main()
        {
            gl_FragColor = v_color;
        }
        """

        window = app.Window(width=2048,
                            height=2048,
                            color=(0.30, 0.30, 0.35, 1.00))

        verts = np.zeros(len(points), [("position", np.float32, 3),
                                       ("a_color", np.float32, 4)])
        verts["position"] = points
        verts["a_color"] = make_colors(verts["position"], cmap, color_function)

        verts = verts.view(gloo.VertexBuffer)
        indeces = np.array(triangle).astype(np.uint32)
        indeces = indeces.view(gloo.IndexBuffer)

        surface = gloo.Program(vertex, fragment)
        surface.bind(verts)
        surface['u_model'] = np.eye(4, dtype=np.float32)
        surface['u_view'] = glm.translation(0, 0, -5)
        surface['transform'] = Trackball(Position("position"), znear=0)
        window.attach(surface['transform'])

        @window.event
        def on_draw(draw_triangles):
            window.clear()

            surface.draw(gl.GL_TRIANGLES, indeces)
            #  surface.draw(gl.GL_LINES, indeces)

        @window.event
        def on_init():
            gl.glEnable(gl.GL_DEPTH_TEST)
            gl.glPolygonOffset(1, 1)
            gl.glEnable(gl.GL_LINE_SMOOTH)
            gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        app.run()
Example #15
0
    # Outlined cube
    gl.glDisable(gl.GL_POLYGON_OFFSET_FILL)
    gl.glEnable(gl.GL_BLEND)
    gl.glDepthMask(gl.GL_FALSE)
    cube['u_color'] = 0, 0, 0, 1
    cube.draw(gl.GL_LINES, outline)
    gl.glDepthMask(gl.GL_TRUE)


# Build cube data
V, I, O = colorcube()
vertices = V.view(gloo.VertexBuffer)
faces = I.view(gloo.IndexBuffer)
outline = O.view(gloo.IndexBuffer)

cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
transform = Trackball(Position("position"))
cube['transform'] = transform
window.attach(transform)

# OpenGL initalization
gl.glEnable(gl.GL_DEPTH_TEST)
gl.glPolygonOffset(1, 1)
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.glLineWidth(0.75)

# Run
app.run()
Example #16
0
glm.translate(view, 0, 0, -45)

program['position'] = np.dstack((x, y, z))[0]
program['radius'] = np.ones(n) * 5
program['fg_color'] = 0.8, 0.8, 0.8, 1
# colors = np.random.uniform(0.75, 1.00, (n, 4))
colors = np.ones((n, 4))
colors[:, 0] = np.linspace(0.00, 0.80, n)
colors[:, 1] = 0
colors[:, 2] = 0
colors[:, 3] = 1
program['bg_color'] = colors
program['linewidth'] = 1.0
program['antialias'] = 1.0
program['view'] = view
program['transform'] = Trackball(Position("position"))
window.attach(program['transform'])

if os.path.isfile('active_site.pt'):
    print("... plot with active_site.pt")
    data = np.genfromtxt("active_site.pt",
                         dtype=[('x', 'f8'), ('y', 'f8'), ('z', 'f8')])
    ndata = len(data['x'])
    pro2 = gloo.Program(vertex, fragment, count=ndata)
    pro2['position'] = np.dstack((data['x'], data['y'], data['z']))[0]
    pro2['radius'] = np.ones_like(data['x']) * 3
    pro2['fg_color'] = 0, 0, 0, 1
    colors = np.zeros((ndata, 4))
    colors[:, 0:1] = 0.5
    colors[:, 2] = 1.0
    colors[:, 3] = 0.8
Example #17
0
@window.event
def on_draw(dt):
    window.clear()
    teapot.draw(gl.GL_TRIANGLES, indices)

@window.event
def on_mouse_drag(x, y, dx, dy, button):
    update()
    
@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)
    update()

vertices, indices = primitives.teapot()
teapot = gloo.Program(vertex, fragment)
teapot.bind(vertices)
trackball = Trackball(Position("position"))
teapot['transform'] = trackball
trackball.theta, trackball.phi, trackball.zoom = 40, 135, 25

teapot["light_position[0]"] = 3, 0, 0+5
teapot["light_position[1]"] = 0, 3, 0+5
teapot["light_position[2]"] = -3, -3, +5
teapot["light_color[0]"]    = 1, 0, 0
teapot["light_color[1]"]    = 0, 1, 0
teapot["light_color[2]"]    = 0, 0, 1

window.attach(teapot['transform'])
app.run()
Example #18
0
@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)

vertices = np.array([[+1,+1,+1], [-1,+1,+1], [-1,-1,+1], [+1,-1,+1],
                     [+1,-1,-1], [+1,+1,-1], [-1,+1,-1], [-1,-1,-1]])
texcoords = np.array([[+1,+1,+1], [-1,+1,+1], [-1,-1,+1], [+1,-1,+1],
                     [+1,-1,-1], [+1,+1,-1], [-1,+1,-1], [-1,-1,-1]])
faces = np.array([vertices[i] for i in [0,1,2,3, 0,3,4,5, 0,5,6,1,
                                        6,7,2,1, 7,4,3,2, 4,7,6,5]])
indices = np.resize(np.array([0,1,2,0,2,3], dtype=np.uint32), 36)
indices += np.repeat(4 * np.arange(6, dtype=np.uint32), 6)
indices = indices.view(gloo.IndexBuffer)
texture = np.zeros((6,1024,1024,3),dtype=np.float32).view(gloo.TextureCube)
texture.interpolation = gl.GL_LINEAR
program = gloo.Program(vertex, fragment, count=24)
program['position'] = faces*10
program['texcoord'] = faces
program['texture'] = texture
program['transform'] = Trackball(Position(), distance=0)

texture[2] = data.get("sky-left.png")/255.
texture[3] = data.get("sky-right.png")/255.
texture[0] = data.get("sky-front.png")/255.
texture[1] = data.get("sky-back.png")/255.
texture[4] = data.get("sky-up.png")/255.
texture[5] = data.get("sky-down.png")/255.
window.attach(program["transform"])
app.run()
Example #19
0
    pos = <transform.trackball_projection> * pos;
    gl_FragDepth = 0.5*(pos.z / pos.w)+0.5;
    vec3 normal = vec3(x,y,z);
    float diffuse = clamp(dot(normal, v_light_direction), 0.0, 1.0);

    vec4 color = vec4((0.5 + 0.5*diffuse)*v_color, 1.0);
    gl_FragColor = outline(distance, 1.0, 1.0, vec4(0,0,0,1), color);
    // gl_FragColor = color;
}
"""

window = app.Window(width=800, height=800, color=(1, 1, 1, 1))

protein = gloo.Program(vertex, fragment)
protein['light_position'] = 0., 0., 2.
protein["transform"] = Trackball(Position())
protein.bind(data.get("protein.npy").view(gloo.VertexBuffer))
protein['color'] *= .25
protein['color'] += .75


@window.event
def on_draw(dt):
    window.clear()
    protein.draw(gl.GL_POINTS)


@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl_FragColor = texture2D(color,v_texcoord);
}
"""

window = app.Window(width=1000, height=1000, color=(1, 1, 1, 1))

n = 5000
program = gloo.Program(vertex, fragment, count=n)
program['position'] = 0.75 * np.random.randn(n, 3)
program['size'] = np.random.uniform(20, 30, n)
program['fg_color'] = 0, 0, 0, 1
program['bg_color'] = np.random.uniform(0.75, 1.00, (n, 4))
program['bg_color'][:, 3] = 1
program['linewidth'] = 1.0
program['antialias'] = 1.0
program['transform'] = Trackball()
program["id"] = np.arange(n, dtype=np.float32)

quad = gloo.Program(quad_vertex, quad_fragment, count=4)
quad['position'] = [(-1, -1), (-1, 1), (1, -1), (1, 1)]

color = np.zeros((window.height, window.width, 4),
                 np.ubyte).view(gloo.Texture2D)
color.interpolation = gl.GL_LINEAR
pick = np.zeros((window.height, window.width, 4),
                np.ubyte).view(gloo.Texture2D)
pick.interpolation = gl.GL_LINEAR
framebuffer = gloo.FrameBuffer(color=[color, pick])
quad["color"] = color

index = 0
Example #21
0
               "One, two! One, two! And through and through\n"
               "  The vorpal blade went snicker-snack!\n"
               "He left it dead, and with its head\n"
               "  He went galumphing back.\n"
               "\"And, has thou slain the Jabberwock?\n"
               "  Come to my arms, my beamish boy!\n"
               "O frabjous day! Callooh! Callay!'\n"
               "  He chortled in his joy.\n"
               "\n"
               "`Twas brillig, and the slithy toves\n"
               "  Did gyre and gimble in the wabe;\n"
               "All mimsy were the borogoves,\n"
               "  And the mome raths outgrabe.\n")

window = app.Window(width=700, height=700, color=(1, 1, 1, 1))


@window.event
def on_draw(dt):
    window.clear()
    glyphs.draw()


glyphs = GlyphCollection(transform=Trackball(Position()))
glyphs.append(jabberwocky, FontManager.get("Roboto-Regular.ttf"))

window.attach(glyphs["transform"])
window.attach(glyphs["viewport"])

app.run()
parser.add_argument('--end', type=int, default=-1, help='Ending frame')
parser.add_argument('--fps', type=int, default=15, help='Ending frame')

opt, _ = parser.parse_known_args()

filenames = np.genfromtxt(join(opt.path_to_data, 'youtube.txt'), dtype=str)
if opt.end == -1:
    opt.end = len(filenames)
filenames = filenames[opt.start:opt.end]

fps = opt.fps
n_frames = len(filenames)

trackball = Trackball(Position("position"),
                      aspect=1,
                      theta=45,
                      phi=45,
                      distance=100,
                      zoom=135)

vertices_field, indices_field = plane()

field = gloo.Program(vertex_tex, fragment_tex)
field.bind(vertices_field)
field['position'] = vertices_field
field['u_texture'] = data.get(join(opt.path_to_data, 'texture.png'))
field['transform'] = trackball

all_programs = []

for fid, fname in enumerate(filenames):
Example #23
0
def glumpyVisualize(voronoiCrystal):
    from glumpy import app, gloo, gl, data
    from glumpy.transforms import Position, Trackball
    from glumpy.graphics.filter import Filter
    vertex = """
uniform vec3 light_position;
attribute vec3 position;
attribute vec3 color;
attribute float radius;
varying float v_size;
varying vec3 v_color;
varying float v_radius;
varying vec4 v_eye_position;
varying vec3 v_light_direction;
void main (void)
{
    v_color = color;
    v_radius = radius;
    v_eye_position = <transform.trackball_view> *
                     <transform.trackball_model> *
                     vec4(position,1.0);
    v_light_direction = normalize(light_position);
    gl_Position = <transform(position)>;
    // stackoverflow.com/questions/8608844/...
    //  ... resizing-point-sprites-based-on-distance-from-the-camera
    vec4 p = <transform.trackball_projection> *
             vec4(radius, radius, v_eye_position.z, v_eye_position.w);
    v_size = 512.0 * p.x / p.w;
    gl_PointSize = v_size + 5.0;
}
"""

    fragment = """
#include "antialias/outline.glsl"
varying float v_size;
varying vec3 v_color;
varying float v_radius;
varying vec4 v_eye_position;
varying vec3 v_light_direction;
void main()
{
    vec2 P = gl_PointCoord.xy - vec2(0.5,0.5);
    float point_size = v_size  + 5.0;
    float distance = length(P*point_size) - v_size/2;
    vec2 texcoord = gl_PointCoord* 2.0 - vec2(1.0);
    float x = texcoord.x;
    float y = texcoord.y;
    float d = 1.0 - x*x - y*y;
    if (d <= 0.0) discard;
    float z = sqrt(d);
    vec4 pos = v_eye_position;
    pos.z += v_radius*z;
    vec3 pos2 = pos.xyz;
    pos = <transform.trackball_projection> * pos;
    gl_FragDepth = 0.5*(pos.z / pos.w)+0.5;
    vec3 normal = vec3(x,y,z);
    float diffuse = clamp(dot(normal, v_light_direction), 0.0, 1.0);
    vec4 color = vec4((0.5 + 0.5*diffuse)*v_color, 1.0);
    gl_FragColor = outline(distance, 1.0, 1.0, vec4(0,0,0,1), color);
    // gl_FragColor = color;
}
	"""
    window = app.Window(width=800, height=800, color=(1, 1, 1, 1))
    particles = gloo.Program(vertex, fragment)
    particles['light_position'] = 0., 0., 2.
    particles["transform"] = Trackball(Position(), distance=500)
    particles.bind(
        getBindDataFromVoronoiCrystals(voronoiCrystal).view(gloo.VertexBuffer))

    @window.event
    def on_draw(dt):
        window.clear()
        particles.draw(gl.GL_POINTS)

    @window.event
    def on_init():
        gl.glEnable(gl.GL_DEPTH_TEST)

    window.attach(particles["transform"])
    app.run()
Example #24
0

'''Models'''
# V, I = primitives.sphere()
V, I = primitives.teapot()
# V, I = primitives.cube()
# V, I = primitives.cubesphere()
# V, I = primitives.tube()
# V, I = data.get('teapot.obj')
path = '../models/bunny.obj'
# V, I = data.load(path)

obj = gloo.Program(vertex_shader, fragment_shader)
obj.bind(V)

trackball = Trackball(Position("position"))
obj['transform'] = trackball
trackball.theta, trackball.phi, trackball.zoom = 45, 45, 25  #40, 135, 25
'''lights'''
# obj["lightPositions[0]"] =  np.array((10,  10, -10))
# obj["lightPositions[1]"] =  np.array((0,  5, +10))
# obj["lightPositions[2]"] =  np.array((-5, 0, +10))
# obj["lightPositions[3]"] =  np.array((0, -5, +10))
# obj['lightPositions'] = np.array((0,0,10))
obj['lightColors'] = np.array((1, 1, 1)) * 500

obj['camPos'] = np.array((0, 0, 5))
'''textures'''
obj['albedoMap'] = np.array(
    Image.open(
        "../textures/chipped-paint-metal/chipped-paint-metal-albedo.png"))
      // the falloff equation, starts at falloff and is kind of 1/x^2 falling
      bl += step(falloff,depthDifference)*normDiff*(1.0-smoothstep(falloff,strength,depthDifference));
   }

   // output the result
   float ao = 1.0 - base*bl/16;
   gl_FragColor.rgb = color * ao;
   gl_FragColor.a = 1.0;
}
"""

window = app.Window(width=800, height=800, color=(1,1,1,1))

protein = gloo.Program(vertex, fragment)
protein['light_position'] = 0., 0., 2.
protein["transform"] = Trackball(Position(), znear=2.0, zfar=100.0)
protein.bind(data.get("protein.npy").view(gloo.VertexBuffer))

ssao= gloo.Program(ssao_vertex, ssao_fragment, count=4)
ssao['position']= [(0,0), (0,1), (1,0), (1,1)]
ssao['base']    = 1.00
ssao['strength']= 0.20;
ssao['falloff'] = 0.000002;
ssao['radius']  = 0.01;

ssao['normals'] = np.zeros((800,800,4),np.float32).view(gloo.Texture2D)
ssao['normals'].interpolation = gl.GL_LINEAR
ssao['colors'] = np.zeros((800,800,4),np.float32).view(gloo.Texture2D)
ssao['colors'].interpolation = gl.GL_LINEAR
ssao['noise'] = np.random.uniform(0,1,(256,256,3))
ssao['noise'].interpolation = gl.GL_LINEAR
window = app.Window(width=1024, height=1024, color=(.75, .75, .75, 1))


@window.event
def on_draw(dt):
    window.clear()
    teapot.draw(gl.GL_TRIANGLES, indices)


@window.event
def on_init():
    gl.glEnable(gl.GL_BLEND)
    gl.glEnable(gl.GL_DEPTH_TEST)


vertices, indices = primitives.teapot()
vertices["position"] *= 10
teapot = gloo.Program(teapot_vert, teapot_frag)
teapot.bind(vertices)
teapot['texture'] = data.checkerboard()

trackball = Trackball(Position("position"), znear=0.1, zfar=100.0, distance=50)
teapot['transform'] = trackball
trackball.theta = 40
trackball.phi = 135
trackball.zoom = 40

window.attach(teapot['transform'])
app.run()
Example #27
0
        float specular_angle = max(dot(half_direction, normal), 0.0);
        specular = pow(specular_angle, shininess);
    }
    vec3 color_linear = ambient_color +
                        lambertian * diffuse_color +
                        specular * specular_color;
    vec3 color_gamma = pow(color_linear, vec3(1.0/gamma));
    gl_FragColor = vec4(color_gamma, 1.0);
}
"""

log.info("Loading brain mesh")
vertices,indices = data.get("brain.obj")
brain = gloo.Program(vertex, fragment)
brain.bind(vertices)
trackball = Trackball(Position("position"))
brain['transform'] = trackball
trackball.theta, trackball.phi, trackball.zoom = 80, -135, 15

window = app.Window(width=1024, height=768)

def update():
    model = brain['transform']['model'].reshape(4,4)
    view  = brain['transform']['view'].reshape(4,4)
    brain['m_view']  = view
    brain['m_model'] = model
    brain['m_normal'] = np.array(np.matrix(np.dot(view, model)).I.T)
    
@window.event
def on_draw(dt):
    window.clear()
Example #28
0
"""Based on lorenz.py in glumpy repo."""
from __future__ import division
from glumpy import app
from glumpy.transforms import Position, Trackball, Viewport
from grid import grid
from skeleton_vis import LimbCollection

window = app.Window(width=1000, height=800, color=(1, 1, 1, 1))
transform = Trackball(Position())
viewport = Viewport()

pose_scale = 2.5
ticks = grid(transform, viewport, scale=pose_scale)
limb_collections = []


@window.event
def on_draw(dt):
    window.clear()
    ticks.draw()
    for limb_collection in limb_collections:
        limb_collection.draw()


@window.event
def on_key_press(key, modifiers):
    if key == app.window.key.SPACE:
        reset()


def reset():
Example #29
0
    def __init__(self, render_objects, **kwargs):
        self.window = app.Window(**kwargs)
        self.render_objects = render_objects
        self.animating = True
        self.programs = []
        for obj in self.render_objects:
            self.programs.append(
                gloo.Program(obj.vertex_shader, obj.fragment_shader))
            self.programs[-1].bind(obj.vertices)

        self.set_light_position([0, 0, 2])
        self.set_light_intensity([1, 1, 1])
        self.view = glm.translation(0, 0, 1)  # camera position
        self.model = np.eye(4, dtype=np.float32)
        for obj, prog in zip(self.render_objects, self.programs):
            prog['u_model'] = np.eye(4, dtype=np.float32)
            prog['u_min_color'] = np.min(obj.vertex_buffer['color'])
            prog['u_max_color'] = np.max(obj.vertex_buffer['color'])
            prog['u_view'] = self.view
            prog['u_colors'] = [[0, 0, 1], [1, 1, 1], [1, 0, 0]]

            prog['transform'] = Trackball(Position("position"), theta=0, phi=0)
            self.window.attach(prog['transform'])


#            glyphs = GlyphCollection(transform=Trackball(Position()))
#            glyphs.append(jab, FontManager.get("Roboto-Regular.ttf"))
#self.window.attach(glyphs["transform"])
#self.window.attach(glyphs["viewport"])

        @self.window.event
        def on_draw(dt):
            self.window.clear()
            gl.glEnable(gl.GL_DEPTH_TEST)
            for obj, prog in zip(self.render_objects, self.programs):
                prog.draw(gl.GL_TRIANGLES, obj.indices)
            # Rotate cube
            self.update_camera()

        @self.window.timer(1 / 5.0)
        def timer(dt):
            self.window.set_title("FPS: {:3.1f}".format(
                self.window.fps).encode())

        @self.window.event
        def on_init():
            gl.glEnable(gl.GL_DEPTH_TEST)
            gl.glDisable(gl.GL_BLEND)

        @self.window.event
        def on_key_press(symbol, modifiers):
            LOG.debug('Key pressed (symbol=%s, modifiers=%s)', symbol,
                      modifiers)

        @self.window.event
        def on_character(character):
            if character == 'q':
                self.window.close()
                app.quit()
                sys.exit(0)
            if character == 'r':
                # random colormap
                for prog in self.programs:
                    prog['u_colors'] = np.random.rand(3, 3)
            if character == 'p':
                available = list(
                    self.render_objects[0].available_properties.keys())
                self.change_surface_property(random.choice(available))

            LOG.debug('Character entered (character: %s)' % character)
            LOG.debug('Character == q {}'.format(character == 'q'))

        @self.window.event
        def on_key_release(symbol, modifiers):
            LOG.debug('Key released (symbol=%s, modifiers=%s)', symbol,
                      modifiers)