Beispiel #1
0
# program['minor_step'] = 0.25, np.pi/60

# # This scales projected coordinates into texture coordinates
# program['scale2'] = Position(
#    LinearScale(name = 'x', domain=(0.0, 5.0),     range=(0,1), discard=False, clamp=False),
#    LinearScale(name = 'y', domain=(0.0, 2*np.pi), range=(0,1), discard=False, clamp=False))

# Transverse Mercator projection
# ------------------------------
# This scales texture coordinates into cartesian coordinates
program['scale1'] = Position(
    LinearScale(name='x',
                domain=(0, 1),
                range=(-1.5, 1.5),
                discard=False,
                clamp=False),
    LinearScale(name='y',
                domain=(1, 0),
                range=(-2.3, 2.3),
                discard=False,
                clamp=False))

# Actual projection
program['projection'] = TransverseMercatorProjection()

program['major_step'] = np.array([1.00, 0.50]) * np.pi / 6.0
program['minor_step'] = np.array([1.00, 0.50]) * np.pi / 30.0

# This scales projected coordinates into texture coordinates
program['scale2'] = Position(
    LinearScale(name='x',
Beispiel #2
0
    def __init__(self,
                 user_dtype=None,
                 transform=None,
                 viewport=None,
                 vertex=None,
                 fragment=None,
                 **kwargs):
        """
        Initialize the collection.

        Parameters
        ----------

        user_dtype: list
            The base dtype can be completed (appended) by the used_dtype. It
            only make sense if user also provide vertex and/or fragment shaders

        viewport: glumpy.Transforms
            The viewport to use to rende the collection

        transform: glumpy.Tranforms
            The default vertex shader apply the supplied transform to the
            vertices positions before computing the actual vertices positions
            for path thickness. Note that it is necessary to add the
            glumpy.transforms.Viewport transform at the end of the supplied transform.

        vertex: string
            Vertex shader code

        fragment: string
            Fragment  shader code

        caps : string
            'local', 'shared' or 'global'

        color : string
            'local', 'shared' or 'global'

        linewidth : string
            'local', 'shared' or 'global'

        antialias : string
            'local', 'shared' or 'global'
        """

        base_dtype = [('prev', (np.float32, 3), '!local', (0, 0, 0)),
                      ('curr', (np.float32, 3), '!local', (0, 0, 0)),
                      ('next', (np.float32, 3), '!local', (0, 0, 0)),
                      ('id', (np.float32, 1), '!local', 0),
                      ('color', (np.float32, 4), 'global', (0, 0, 0, 1)),
                      ('linewidth', (np.float32, 1), 'global', 1),
                      ('antialias', (np.float32, 1), 'global', 1)]
        dtype = base_dtype
        if user_dtype:
            dtype.extend(user_dtype)

        if vertex is None:
            vertex = library.get('collections/agg-fast-path.vert')
        if fragment is None:
            fragment = library.get('collections/agg-fast-path.frag')

        Collection.__init__(self,
                            dtype=dtype,
                            itype=None,
                            mode=gl.GL_TRIANGLE_STRIP,
                            vertex=vertex,
                            fragment=fragment,
                            **kwargs)

        # Set hooks if necessary
        program = self._programs[0]
        if "transform" in program.hooks:
            if transform is not None:
                program["transform"] = transform
            else:
                program["transform"] = Position() + Viewport()

        if "viewport" in program.hooks:
            if viewport is not None:
                program["viewport"] = viewport
            else:
                program["viewport"] = Viewport()
Beispiel #3
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)
    filename = sys.argv[1]

    ndata1 = addData(sys.argv[1], points1, color=(0.2, 0.2, 0.2, -1.0))
    tuniq1 = np.unique(ndata1['t'])
    ndata2 = addData(sys.argv[2], points2, color=(0.2, 0.8, 0.2, 0.7))
    tuniq2 = np.unique(ndata2['t'])
    maxtime = len(tuniq1)

    # prepare coordinate
    P0 = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
    P1 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    CP = [(0.9, 0.1, 0.1, 1), (0.1, 0.9, 0.1, 1), (0.1, 0.1, 0.9, 1)]
    coord.append(P0, P1, color=CP, linewidth=[1, 1, 1])
    coord['antialias'] = 1

    transform = Trackball(Position())
    points1["transform"] = transform
    points2["transform"] = transform
    coord['transform'] = transform

    window.attach(points1["transform"])
    window.attach(points1["viewport"])
    window.attach(points2["transform"])
    window.attach(points2["viewport"])
    window.attach(coord["transform"])
    window.attach(coord["viewport"])

    @window.event
    def on_draw(dt):
        global time, maxtime, toggleStop
        window.clear()
}
"""

fragment = """
const vec4 blue  = vec4(0.80,0.80,1.00,1.00);
const vec4 white = vec4(1.00,1.00,1.00,1.00);
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
    float v = texture2D(texture, v_texcoord).r;
    gl_FragColor = mix(white,blue,v);
}
"""

transform = Arcball(Position(), znear=1, zfar=10)
viewport = Viewport()

radius = 1.5
vertices, indices = sphere(radius, 64, 64)
earth = gloo.Program(vertex, fragment)
earth.bind(vertices)
earth['texture'] = data.get("earth-black.jpg")
earth['texture'].interpolation = gl.GL_LINEAR
earth['transform'] = transform

paths = PathCollection(mode="agg+",
                       color="global",
                       linewidth="global",
                       viewport=viewport,
                       transform=transform)
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import re
import numpy as np
from glumpy import app, gl, data, svg, collections
from glumpy.transforms import Position, OrthographicProjection, PanZoom, Viewport

window = app.Window(800, 800, color=(1, 1, 1, 1))
transform = PanZoom(OrthographicProjection(Position()))


@window.event
def on_draw(dt):
    window.clear()
    paths["antialias"] = -0.5
    collections.Collection.draw(paths)
    paths["antialias"] = +1.0
    collections.Collection.draw(paths)


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


paths = collections.PathCollection("agg", transform=transform)
# paths["miter_limit"] = 4.0
paths["linewidth"] = 50.0
paths["color"] = 0.0, 0.0, 0.0, 0.5
Beispiel #7
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)
Beispiel #8
0
               "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, title="hello", 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("c:/windows/fonts/arial.ttf"))

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

app.run()
Beispiel #9
0
    def __init__(self,
                 marker='heart',
                 user_dtype=None,
                 transform=None,
                 viewport=None,
                 vertex=None,
                 fragment=None,
                 **kwargs):
        """
        Initialize the collection.

        Parameters
        ----------

        user_dtype: list
            The base dtype can be completed (appended) by the user_dtype. It
            only make sense if user also provide vertex and/or fragment shaders

        transform: glumpy.Tranforms
            The default vertex shader apply the supplied transform to the
            vertices positions before computing the actual vertices positions
            for path thickness. Note that it is necessary to add the
            glumpy.transforms.Viewport transform at the end of the supplied transform.

        vertex: string
            Vertex shader code

        fragment: string
            Fragment  shader code

        size : string
            'local', 'shared' or 'global'

        orientation : string
            'local', 'shared' or 'global'

        fg_color : string
            'local', 'shared' or 'global'

        bg_color : string
            'local', 'shared' or 'global'

        linewidth : string
            'local', 'shared' or 'global'

        antialias : string
            'local', 'shared' or 'global'
        """

        base_dtype = [('position', (np.float32, 3), '!local', (0, 0, 0)),
                      ('size', (np.float32, 1), 'local', 1),
                      ('marker', (np.float32, 1), 'local', 1),
                      ('orientation', (np.float32, 1), 'local', 0.0),
                      ('fg_color', (np.float32, 4), 'local', (0, 0, 0, 1)),
                      ('bg_color', (np.float32, 4), 'local', (1, 1, 1, 1)),
                      ('linewidth', (np.float32, 1), 'global', 1.0),
                      ('antialias', (np.float32, 1), 'global', 1.0)]
        dtype = base_dtype
        if user_dtype:
            dtype.extend(user_dtype)

        if vertex is None:
            vertex = library.get('collections/marker.vert')
        if fragment is None:
            fragment = library.get('collections/marker.frag')

        Collection.__init__(self,
                            dtype=dtype,
                            itype=None,
                            mode=gl.GL_POINTS,
                            vertex=vertex,
                            fragment=fragment,
                            **kwargs)

        # Set hooks if necessary
        program = self._programs[0]
        if "transform" in program.hooks:
            if transform is not None:
                program["transform"] = transform
            else:
                program["transform"] = Position()

        if "viewport" in program.hooks:
            if viewport is not None:
                program["viewport"] = viewport
            else:
                program["viewport"] = Viewport()

        program["marker"] = marker
        program["paint"] = "outline"
Beispiel #10
0
    source = parents.pop(0)
    for i in range(branch):
        try:
            target = next(nodes)
            parents.append(target)
            A[source, target] = 1
        except StopIteration:
            break

# Current selected node
selected = -1

# Get edges
src, tgt = np.nonzero(A)

transform = OrthographicProjection(Position(), aspect=None)
viewport = Viewport()

markers = collections.MarkerCollection(marker='disc',
                                       transform=transform,
                                       viewport=viewport)
markers.append(N,
               size=15,
               linewidth=2,
               itemsize=1,
               fg_color=(1, 1, 1, 1),
               bg_color=(1, .5, .5, 1))
segments = collections.SegmentCollection('agg',
                                         transform=transform,
                                         viewport=viewport)
segments.append(N[src],
Beispiel #11
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
Beispiel #12
0
      // 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
Beispiel #13
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()
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glEnable(gl.GL_POLYGON_OFFSET_FILL)
    color_all_cubes()

    # 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)
    # cube2['u_color'] = 0, 0, 0, 1
    # cube2.draw(gl.GL_LINES, outline)
    # gl.glDepthMask(gl.GL_TRUE)


zoom = PanZoom(Position("position"), aspect=1, zoom=1)


@window.event
def on_key_press(key, modifiers):
    global phi, theta
    if key == app.window.key.UP:
        for cube in CUBES:
            glm.translate(view, 0, -0.01, 0)
            cube['view'] = view
    if key == app.window.key.DOWN:
        for cube in CUBES:
            glm.translate(view, 0, 0.01, 0)
            cube['view'] = view
    if key == app.window.key.LEFT:
        for cube in CUBES:
Beispiel #15
0
data['orientation'] = 0
radius, theta, dtheta = 250.0, 0.0, 5.5 / 180.0 * np.pi
for i in range(500):
    theta += dtheta
    x = 256 + radius * np.cos(theta)
    y = 256 + radius * np.sin(theta)
    r = 10.0 - i * 0.02
    radius -= 0.45
    data['orientation'][i] = theta - np.pi/2
    data['position'][i] = x, y
    data['size'][i] = 2 * r
    data['linewidth'][i] = 1

data['position'][-1]    = 512+256, 256
data['size'][-1]        = 512/np.sqrt(2)
data['linewidth'][-1]   = 3.0
data['fg_color'][-1]    = 0, 0, 0, 1
data['bg_color'][-1]    = .95, .95, .95, 1
data['orientation'][-1] = 0

program = gloo.Program("markers/marker.vert", "markers/marker.frag")
program.bind(data)
program['antialias'] = 1.00
program['marker']    = "square"
program['paint']     = "stroke"
transform = OrthographicProjection(Position("position"))
program['transform'] = transform
window.attach(transform)

app.run()
Beispiel #16
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]
Beispiel #17
0
    phi += 0.5  # degrees
    model = np.eye(4, dtype=np.float32)
    glm.rotate(model, theta, 0, 0, 1)
    glm.rotate(model, phi, 0, 1, 0)
    transform['model'] = model


# 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 = PVMProjection(Position("position"))
cube['transform'] = transform
window.attach(transform)

phi, theta = 0, 0

# 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()
Beispiel #18
0
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
from glumpy import app
from glumpy.log import log
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.transforms import Position, OrthographicProjection, Viewport

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


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


labels = GlyphCollection('agg', transform=OrthographicProjection(Position()))
text = "The quick brown fox jumps over the lazy dog"
x, y, z = 2, window.height, 0

log.info("Caching texture fonts")
for i in range(6, 54, 2):
    font = FontManager.get("OpenSans-Regular.ttf", size=i, mode='agg')
    y -= i * 1.1
    labels.append(text, font, origin=(x, y, z), anchor_x="left")

window.attach(labels["transform"])
window.attach(labels["viewport"])
app.run()
Beispiel #19
0
@window.event
def on_draw(dt):
    window.clear()
    program.draw(gl.GL_TRIANGLE_STRIP)


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


@window.event
def on_resize(width, height):
    program['viewport'] = 0, 0, width, height


program = gloo.Program(vertex, fragment, count=4)

n = 64
program['position'] = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
program['texcoord'] = [(0, 1), (0, 0), (1, 1), (1, 0)]
program['data'] = np.random.uniform(0, 1, (n, n))
program['data_shape'] = program['data'].shape[:2]
transform = PanZoom(Position("position"), aspect=1)

program['transform'] = transform
window.attach(transform)
app.run()
    window.clear()
    quads.draw(gl.GL_TRIANGLES, indices)


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


quads = gloo.Program(vertex, fragment, 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)

trackball = Trackball(Position("position"), znear=0.1, zfar=500, distance=50)
quads['transform'] = trackball
trackball.theta = 40
trackball.phi = 45
trackball.zoom = 40
window.attach(quads['transform'])
app.run()
Beispiel #21
0
{
    gl_Position = <transform>;
}
"""

fragment = """
void main()
{
    gl_FragColor = vec4(1,0,0,1);
}
"""

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


@window.event
def on_draw(dt):
    window.clear()
    quad.draw(gl.GL_TRIANGLE_STRIP)


@window.event
def on_resize(w, h):
    quad['position'] = [(w - 100, h - 100), (w - 100, h), (w, h - 100), (w, h)]


quad = gloo.Program(vertex, fragment, count=4)
quad["transform"] = OrthographicProjection(Position("position"))
window.attach(quad["transform"])
app.run()
Beispiel #22
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()
}
"""

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

# 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)

# create an instance of the TrackballPan object.
trackball = TrackballPan(Position("position"), znear=3, zfar=10, distance=5)
cube['transform'] = trackball

trackball.aspect = 1
# rotation around the X axis
trackball.phi = 0
# rotation around the Y axis
trackball.theta = 0
trackball.zoom = 50


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

    # Filled cube