Ejemplo n.º 1
0
    def get(cls, filename, size=12, mode='sdf'):
        """
        Get a font from the cache, the local data directory or the distant server
        (in that order).
        """

        filename = data.get(filename)
        dirname = os.path.dirname(filename)
        basename = os.path.basename(filename)

        if mode == 'sdf':
            key = '%s' % (basename)
            if FontManager._atlas_sdf is None:
                FontManager._atlas_sdf = np.zeros((1024, 1024),
                                                  np.float32).view(Atlas)
            atlas = FontManager._atlas_sdf
            cache = FontManager._cache_sdf

            if key not in cache.keys():
                cache[key] = SDFFont(filename, atlas)
            return cache[key]

        else:  # mode == 'agg':
            key = '%s-%d' % (basename, size)
            if FontManager._atlas_agg is None:
                FontManager._atlas_agg = np.zeros((1024, 1024, 3),
                                                  np.ubyte).view(Atlas)

            atlas = FontManager._atlas_agg
            cache = FontManager._cache_agg
            if key not in cache.keys():
                cache[key] = AggFont(filename, size, atlas)
            return cache[key]
Ejemplo n.º 2
0
    def get(cls, filename, size=12, mode='sdf'):
        """
        Get a font from the cache, the local data directory or the distant server
        (in that order).
        """

        filename = data.get(filename)
        dirname  = os.path.dirname(filename)
        basename = os.path.basename(filename)

        if mode == 'sdf':
            key = '%s' % (basename)
            if FontManager._atlas_sdf is None:
                FontManager._atlas_sdf = np.zeros((1024,1024),np.float32).view(Atlas)
            atlas = FontManager._atlas_sdf
            cache = FontManager._cache_sdf

            if key not in cache.keys():
                cache[key] = SDFFont(filename, atlas)
            return cache[key]

        else: # mode == 'agg':
            key = '%s-%d' % (basename,size)
            if FontManager._atlas_agg is None:
                FontManager._atlas_agg = np.zeros((1024,1024,3),np.ubyte).view(Atlas)

            atlas = FontManager._atlas_agg
            cache = FontManager._cache_agg
            if key not in cache.keys():
                cache[key] = AggFont(filename, size, atlas)
            return cache[key]
Ejemplo n.º 3
0
def on_draw(dt):

    gl.glViewport(0, 0, GridWidth, GridHeight)
    gl.glDisable(gl.GL_BLEND)

    Advect(Velocity.Ping, Velocity.Ping, Obstacles, Velocity.Pong,
           VelocityDissipation)
    Velocity.swap()

    Advect(Velocity.Ping, Temperature.Ping, Obstacles, Temperature.Pong,
           TemperatureDissipation)
    Temperature.swap()

    Advect(Velocity.Ping, Density.Ping, Obstacles, Density.Pong,
           DensityDissipation)
    Density.swap()

    ApplyBuoyancy(Velocity.Ping, Temperature.Ping, Density.Ping, Velocity.Pong)
    Velocity.swap()

    ApplyImpulse(Temperature.Ping, ImpulsePosition, ImpulseTemperature)
    ApplyImpulse(Density.Ping, ImpulsePosition, ImpulseDensity)
    ComputeDivergence(Velocity.Ping, Obstacles, Divergence)
    ClearSurface(Pressure.Ping, 0.0)

    for i in range(NumJacobiIterations):
        Jacobi(Pressure.Ping, Divergence, Obstacles, Pressure.Pong)
        Pressure.swap()

    SubtractGradient(Velocity.Ping, Pressure.Ping, Obstacles, Velocity.Pong)
    Velocity.swap()

    gl.glViewport(0, 0, window.width, window.height)
    gl.glClearColor(0, 0, 0, 1)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glEnable(gl.GL_BLEND)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

    prog_visualize['u_data'] = Density.Ping.texture
    prog_visualize['u_shape'] = Density.Ping.texture.shape[
        1], Density.Ping.texture.shape[0]
    prog_visualize['u_kernel'] = data.get("spatial-filters.npy")
    prog_visualize["Sampler"] = Density.Ping.texture
    prog_visualize["FillColor"] = 0.95, 0.925, 1.00
    prog_visualize["Scale"] = 1.0 / window.width, 1.0 / window.height
    prog_visualize.draw(gl.GL_TRIANGLE_STRIP)
Ejemplo n.º 4
0
    def __init__(self, transform=None, viewport=None, **kwargs):
        dtype = [('position', (np.float32, 2), '!local', (0, 0)),
                 ('texcoord', (np.float32, 2), '!local', (0, 0)),
                 ('origin', (np.float32, 3), 'shared', (0, 0, 0)),
                 ('direction', (np.float32, 3), 'shared', (1, 0, 0)),
                 ('scale', (np.float32, 1), 'shared', 0.005),
                 ('color', (np.float32, 4), 'shared', (0, 0, 0, 1))]

        if "vertex" in kwargs.keys():
            vertex = library.get(kwargs["vertex"])
            del kwargs["vertex"]
        else:
            vertex = library.get('collections/sdf-glyph.vert')

        if "fragment" in kwargs.keys():
            fragment = library.get(kwargs["fragment"])
            del kwargs["fragment"]
        else:
            fragment = library.get('collections/sdf-glyph.frag')

        Collection.__init__(self,
                            dtype=dtype,
                            itype=np.uint32,
                            mode=gl.GL_TRIANGLES,
                            vertex=vertex,
                            fragment=fragment)
        program = self._programs[0]
        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()

        manager = FontManager()
        atlas = manager.atlas_sdf
        self['u_kernel'] = data.get("spatial-filters.npy")
        self['atlas_data'] = atlas
        self['atlas_data'].interpolation = gl.GL_LINEAR
        self['atlas_shape'] = atlas.shape[1], atlas.shape[0]
Ejemplo n.º 5
0
    def __init__(self, transform=None, viewport=None, **kwargs):
        dtype = [('position',  (np.float32, 2), '!local', (0,0)),
                 ('texcoord',  (np.float32, 2), '!local', (0,0)),
                 ('origin',    (np.float32, 3), 'shared', (0,0,0)),
                 ('direction', (np.float32, 3), 'shared', (1,0,0)),
                 ('scale',     (np.float32, 1), 'shared', 0.005),
                 ('color',     (np.float32, 4), 'shared', (0,0,0,1))]

        if "vertex" in kwargs.keys():
            vertex = library.get(kwargs["vertex"])
            del kwargs["vertex"]
        else:
            vertex = library.get('collections/sdf-glyph.vert')

        if "fragment" in kwargs.keys():
            fragment = library.get(kwargs["fragment"])
            del kwargs["fragment"]
        else:
            fragment = library.get('collections/sdf-glyph.frag')

        Collection.__init__(self, dtype=dtype, itype=np.uint32,
                            mode = gl.GL_TRIANGLES,
                            vertex=vertex, fragment=fragment)
        program = self._programs[0]
        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()


        manager = FontManager()
        atlas = manager.atlas_sdf
        self['u_kernel'] = data.get("spatial-filters.npy")
        self['atlas_data'] = atlas
        self['atlas_data'].interpolation = gl.GL_LINEAR
        self['atlas_shape'] = atlas.shape[1], atlas.shape[0]
Ejemplo n.º 6
0
def teapot(size=1.0):
    """
    Z-axis aligned Utah teapot

    Parameters
    ----------

    size : float
        Relative size of the teapot.
    """

    vertices, indices = data.get("teapot.obj")
    xmin = vertices["position"][:,0].min()
    xmax = vertices["position"][:,0].max()
    ymin = vertices["position"][:,1].min()
    ymax = vertices["position"][:,1].max()
    zmin = vertices["position"][:,2].min()
    zmax = vertices["position"][:,2].max()

    # Centering
    vertices["position"][:,0] -= xmin + (xmax-xmin)/2
    vertices["position"][:,1] -= ymin + (ymax-ymin)/2
    vertices["position"][:,2] -= zmin + (zmax-zmin)/2

    # Rotation to align on Z-axis
    X = vertices["position"][:,0].copy()
    Y = vertices["position"][:,1].copy()
    Z = vertices["position"][:,2].copy()
    NX = vertices["normal"][:,0].copy()
    NY = vertices["normal"][:,1].copy()
    NZ = vertices["normal"][:,2].copy()
    vertices["position"][:,0] = X
    vertices["position"][:,1] = Z
    vertices["position"][:,2] = Y
    vertices["normal"][:,0] = NX
    vertices["normal"][:,1] = NZ
    vertices["normal"][:,2] = NY

    # Scaling according to height
    vertices["position"] *= 2.0*size/(zmax-zmin)

    return vertices, indices
Ejemplo n.º 7
0
def teapot(size=1.0):
    """
    Z-axis aligned Utah teapot

    Parameters
    ----------

    size : float
        Relative size of the teapot.
    """

    vertices, indices = data.get("teapot.obj")
    xmin = vertices["position"][:, 0].min()
    xmax = vertices["position"][:, 0].max()
    ymin = vertices["position"][:, 1].min()
    ymax = vertices["position"][:, 1].max()
    zmin = vertices["position"][:, 2].min()
    zmax = vertices["position"][:, 2].max()

    # Centering
    vertices["position"][:, 0] -= xmin + (xmax - xmin) / 2
    vertices["position"][:, 1] -= ymin + (ymax - ymin) / 2
    vertices["position"][:, 2] -= zmin + (zmax - zmin) / 2

    # Rotation to align on Z-axis
    X = vertices["position"][:, 0].copy()
    Y = vertices["position"][:, 1].copy()
    Z = vertices["position"][:, 2].copy()
    NX = vertices["normal"][:, 0].copy()
    NY = vertices["normal"][:, 1].copy()
    NZ = vertices["normal"][:, 2].copy()
    vertices["position"][:, 0] = X
    vertices["position"][:, 1] = Z
    vertices["position"][:, 2] = Y
    vertices["normal"][:, 0] = NX
    vertices["normal"][:, 1] = NZ
    vertices["normal"][:, 2] = NY

    # Scaling according to height
    vertices["position"] *= 2.0 * size / (zmax - zmin)

    return vertices, indices
Ejemplo n.º 8
0
def on_draw(dt):

    gl.glViewport(0, 0, GridWidth, GridHeight)
    gl.glDisable(gl.GL_BLEND)

    Advect(Velocity.Ping, Velocity.Ping, Obstacles, Velocity.Pong, VelocityDissipation)
    Velocity.swap()

    Advect(Velocity.Ping, Temperature.Ping, Obstacles, Temperature.Pong, TemperatureDissipation)
    Temperature.swap()

    Advect(Velocity.Ping, Density.Ping, Obstacles, Density.Pong, DensityDissipation)
    Density.swap()

    ApplyBuoyancy(Velocity.Ping, Temperature.Ping, Density.Ping, Velocity.Pong)
    Velocity.swap()

    ApplyImpulse(Temperature.Ping, ImpulsePosition, ImpulseTemperature)
    ApplyImpulse(Density.Ping, ImpulsePosition, ImpulseDensity)
    ComputeDivergence(Velocity.Ping, Obstacles, Divergence)
    ClearSurface(Pressure.Ping, 0.0)

    for i in range(NumJacobiIterations):
        Jacobi(Pressure.Ping, Divergence, Obstacles, Pressure.Pong)
        Pressure.swap()

    SubtractGradient(Velocity.Ping, Pressure.Ping, Obstacles, Velocity.Pong)
    Velocity.swap()

    gl.glViewport(0,0,window.width,window.height)
    gl.glClearColor(0, 0, 0, 1)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glEnable(gl.GL_BLEND)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

    prog_visualize['u_data']   = Density.Ping.texture
    prog_visualize['u_shape']  = Density.Ping.texture.shape[1], Density.Ping.texture.shape[0]
    prog_visualize['u_kernel'] = data.get("spatial-filters.npy")
    prog_visualize["Sampler"] = Density.Ping.texture
    prog_visualize["FillColor"] = 0.95, 0.925, 1.00
    prog_visualize["Scale"] =  1.0/window.width, 1.0/window.height
    prog_visualize.draw(gl.GL_TRIANGLE_STRIP)
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
def on_draw(dt):

    surface_ref.set_array(Density.ping_array)
    kernel_function(np.int32(400), np.int32(400), block=(16,16,1), grid=((400+1)//16+1,(400+1)//16+1))

    gl.glViewport(0,0,window.width,window.height)
    gl.glClearColor(0, 0, 0, 1)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glEnable(gl.GL_BLEND)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

    global t
    t += dt
    prog_visualize['u_data']   = Density.Ping.texture
    prog_visualize['t'] = t
    prog_visualize['u_shape']  = Density.Ping.texture.shape[1], Density.Ping.texture.shape[0]
    prog_visualize['u_kernel'] = data.get("spatial-filters.npy")
    prog_visualize["Sampler"] = Density.Ping.texture
    prog_visualize["FillColor"] = 0.95, 0.925, 1.00
    prog_visualize["Scale"] =  1.0/window.width, 1.0/window.height
    prog_visualize.draw(gl.GL_TRIANGLE_STRIP)
    Density.swap()
Ejemplo n.º 11
0
    uniform sampler2D texture;
    varying vec2 v_texcoord;
    void main()
    {
        gl_FragColor = texture2D(texture, v_texcoord);
    }
"""

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

@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()

program = gloo.Program(vertex, fragment, count=4)
program['position'] = [(-1,-1), (-1,1), (1,-1), (1,1)]
program['texcoord'] = [( 0, 1), ( 0, 0), ( 1, 1), ( 1, 0)]
program['texture'] = data.get("lena.png")

transform = PanZoom(Position("position"), aspect=1)
program['transform'] = transform
window.attach(transform)

app.run()
Ejemplo n.º 12
0
              [0, 0, -1]])

faces_p = [
    0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5
]
faces_n = [
    0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
]

program = gloo.Program(vertex, fragment)
program['a_position'] = [p[i] for i in faces_p]
program['a_normal'] = [n[i] for i in faces_n]

texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32).view(gloo.TextureCube)
texture.interpolation = gl.GL_LINEAR
texture[1] = data.get(abspath("Left_t4.png")) / 255.
texture[0] = data.get(abspath("Right_t4.png")) / 255.
texture[4] = data.get(abspath("Front_t4.png")) / 255.
texture[5] = data.get(abspath("Back_t4.png")) / 255.
texture[2] = data.get(abspath("Top_t4.png")) / 255.
texture[3] = data.get(abspath("Bottom_t4.png")) / 255.

model = np.eye(4, dtype=np.float32)
view = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -5)
glm.scale(model, 0.5, 1, 0.1)

program['texture'] = texture
program['u_model'] = model
program['u_view'] = view
program["u_light_position"] = 0, 2, -2
Ejemplo n.º 13
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import re
import triangle
import numpy as np

from glumpy import app, gl, data
from glumpy.graphics.svg import Document
from glumpy.graphics.collections import PathCollection, PolygonCollection
from glumpy.transforms import Position, OrthographicProjection, PanZoom, Viewport

tiger = Document(data.get("tiger.svg"))
window = app.Window(int(tiger.viewport.width),
                    int(tiger.viewport.height),
                    color=(1, 1, 1, 1))


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


@window.event
def on_init():
    gl.glEnable(gl.GL_DEPTH_TEST)
Ejemplo n.º 14
0
    fovy = np.minimum(np.maximum(fovy * (1 + dy / 100), 10.0), 179.0)
    program['projection'] = glm.perspective(
        fovy, window.width / float(window.height), 1.0, 100.0)


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


program = gloo.Program(vertex, fragment)
program.bind(V)
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -3)
program['texture'] = data.get("checkerboard")
program['model'] = model
program['view'] = view
program['grid'] = Grid("pos", "index")
program['grid']["rows"] = rows
program['grid']["cols"] = cols
program['clip'] = Clip("v_index")
program['clip']["rows"] = rows
program['clip']["cols"] = cols

fovy = 30
phi, theta = 30, 20
app.run()
Ejemplo n.º 15
0
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):

    (basename, ext) = file_utils.extract_basename(fname)
    print('Loading model {0}/{1}: {2}'.format(fid, len(filenames), basename))

    path_to_pc = join(opt.path_to_data, 'scene3d')
    img = io.imread(join(path_to_pc, '{0}.jpg'.format(basename)),
                    dtype=np.float32)

    vertices, indices = objload(join(path_to_pc, '{0}.obj'.format(basename)))
    vertices['texcoord'][:, 1] = 1.0 - vertices['texcoord'][:, 1]
Ejemplo n.º 16
0
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

vertex = """
#include "math/constants.glsl"
varying float v_size;
varying vec4  v_fg_color;
varying vec4  v_bg_color;
varying vec2  v_orientation;
varying float v_antialias;
varying float v_linewidth;
void main (void)
{
    fetch_uniforms();
    v_linewidth   = linewidth;
Ejemplo n.º 17
0
     vec2 uv = <projection.inverse(v_texcoord)>;
     gl_FragColor = texture2D(texture, <scale(uv)>.xy);
} """

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


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


program = gloo.Program(vertex, fragment, count=4)
program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
program['texture'] = data.get("earth.jpg")
program['texture'].interpolation = gl.GL_LINEAR

# Polar projection
# ----------------
# program['projection'] = PolarProjection(
#     # This translates texture coordinates to cartesian coordinates
#     LinearScale('.x', name = 'x', domain=(-1, 1), range=(-1,1), call="forward", clamp=True),
#     LinearScale('.y', name = 'y', domain=(-1, 1), range=(-1,1), call="forward", clamp=True))
# program['scale'] = Position(
#     # This translates cartesian coordinates (polar domains) to texture coordinates
#     # LogScale('.x', name = 'x', domain=(-1,0), range=(0,1), clamp=True),
#     LinearScale('.x', name = 'x', domain=(0.2, 1.0),     range=(0,1), clamp=True),
#     LinearScale('.y', name = 'y', domain=(0.0, 2*np.pi), range=(0,1), clamp=True))

# Hammer projection
Ejemplo n.º 18
0
    void main()
    {
        gl_Position = vec4(position, 0.0, 1.0);
        v_texcoord = texcoord;
    }
"""

fragment = """
    uniform sampler2D texture;
    varying vec2 v_texcoord;
    void main()
    {
        gl_FragColor = texture2D(texture, v_texcoord);
    }
"""

window = app.Window(width=512, height=512, aspect=1)


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


program = gloo.Program(vertex, fragment, count=4)
program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
program['texcoord'] = [(0, 1), (0, 0), (1, 1), (1, 0)]
program['texture'] = data.get("lena.png")
app.run()
Ejemplo n.º 19
0
      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
Ejemplo n.º 20
0

@window.event
def on_draw(dt):
    window.clear()
    program.draw(gl.GL_TRIANGLES, I)


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


program = gloo.Program(vertex, fragment)
V, I = primitives.plane(2.0, n=64)
program.bind(V)

lena = data.get("lena.png") / 256.0

program["data"] = lena[::-1, :, 0]
program["data"].interpolation = gl.GL_NEAREST
program["data_shape"] = lena.shape[1], lena.shape[0]
program["u_kernel"] = data.get("spatial-filters.npy")
program["u_kernel"].interpolation = gl.GL_LINEAR

transform = PanZoom(aspect=1)
program["transform"] = transform
window.attach(transform)
app.run()
Ejemplo n.º 21
0
    {
        vec3 view_direction = normalize(-v_position);
        vec3 half_direction = normalize(light_direction + view_direction);
        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)
Ejemplo n.º 22
0
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
from glumpy import app, gl, gloo, glm, data, text

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


@window.event
def on_draw(dt):
    window.clear()
    label.draw(x=256, y=256, color=(1, 1, 1, 1))


font = text.TextureFont(data.get("OpenSans-Regular.ttf"), 64)
label = text.Label("Hello World !", font, anchor_x='center', anchor_y='center')
app.run()
Ejemplo n.º 23
0
    r, g, b = xyz_to_rgb(SMPTEsystem, x, y, z)
    r = min((max(r, 0), 1))
    g = min((max(g, 0), 1))
    b = min((max(b, 0), 1))
    colors[i] = norm_rgb(r, g, b)


program = gloo.Program(vertex, fragment, count=len(galaxy))

view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -5)
program["u_model"] = model
program["u_view"] = view
program["u_colormap"] = colors
program["u_texture"] = data.get("particle.png")
program["u_texture"].interpolation = gl.GL_LINEAR

program["a_temperature"] = (galaxy["temperature"] - t0) / (t1 - t0)
program["a_brightness"] = galaxy["brightness"]
program["a_size"] = galaxy["size"]
program["a_type"] = galaxy["type"]

gl.glClearColor(0.0, 0.0, 0.03, 1.0)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)

app.run(framerate=60)
Ejemplo n.º 24
0
"""

window = app.Window(width=2*512, height=2*512, color=(1,1,1,1))

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

@window.event
def on_resize(width, height):
    program["iResolution"] = width, height

program = gloo.Program(vertex, "./regular-grid.frag")
program["texcoord"] = (-0.5,-0.5), (-0.5, +0.5), (+0.5,-0.5), (+0.5,+0.5)
program["u_texture"] = data.get("lena.png")
program['u_major_grid_width'] = 1.5
program['u_minor_grid_width'] = 1.0
program['u_major_grid_color'] = 0, 0, 0, 1.0
program['u_minor_grid_color'] = 0, 0, 0, 0.5
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])
Ejemplo n.º 25
0
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)
paths["color"] = 0,0,0,0.5
paths["linewidth"] = 1.0

theta = np.linspace(0, 2*np.pi, 64, endpoint=True)
for phi in np.linspace(0, np.pi, 12, endpoint=False):
    paths.append(spheric_to_cartesian(phi, theta, radius*1.01), closed=True)

phi = np.linspace(0, 2*np.pi, 64, endpoint=True)
for theta in np.linspace(0, np.pi, 19, endpoint=True)[1:-1]:
    paths.append(spheric_to_cartesian(phi, theta, radius*1.01), closed=True)
Ejemplo n.º 26
0
    attribute vec2 texcoord;
    varying vec2 v_texcoord;
    void main()
    {
        gl_Position = vec4(position, 0.0, 1.0);
        v_texcoord = texcoord;
    }
"""

fragment = """
    uniform sampler2D texture;
    varying vec2 v_texcoord;
    void main()
    {
        gl_FragColor = texture2D(texture, v_texcoord);
    }
"""

window = app.Window(width=512, height=512, aspect=1)

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

quad = gloo.Program(vertex, fragment, count=4)
quad['position'] = [(-1,-1), (-1,+1), (+1,-1), (+1,+1)]
quad['texcoord'] = [( 0, 1), ( 0, 0), ( 1, 1), ( 1, 0)]
quad['texture'] = data.get("lena.png")
app.run()
Ejemplo n.º 27
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()
Ejemplo n.º 28
0
dx, dy = 1 / 4.0, 1 / 2.0
for j in range(4):
    for i in range(4):
        index = 1 + j * 4 + i
        x, y = i / 4.0, -1 + j / 2.0
        vertices["position"][index] = (x, y + dy), (x, y), (x + dx,
                                                            y + dy), (x + dx,
                                                                      y)
vertices['texcoord'] = (0, 0), (0, +1), (+1, 0), (+1, +1)
vertices['interpol'] = np.arange(17).reshape(17, 1)
program.bind(vertices)
indices = np.zeros((17, 6), np.uint32).view(gloo.IndexBuffer)
indices[:] = [0, 1, 2, 1, 2, 3]
indices += 4 * np.arange(17).reshape(17, 1)

lena = data.get("lena.png")
program['u_data'] = lena
program['u_shape'] = lena.shape[1], lena.shape[0]
program['u_kernel'] = data.get("spatial-filters.npy")
program['u_data'].interpolation = gl.GL_NEAREST
program['u_data'].wrapping = gl.GL_CLAMP

x, y = 512, 512
dx, dy = 0.05, 0.05
x = min(max(x / 1024.0, dx), 1.0 - dx)
y = min(max(y / 1024.0, dy), 1.0 - dy)
vertices['texcoord'][1:] = (x - dx, y - dy), (x - dy,
                                              y + dy), (x + dx,
                                                        y - dy), (x + dx,
                                                                  y + dy)
Ejemplo n.º 29
0
    r,g,b = xyz_to_rgb(SMPTEsystem, x, y, z)
    r = min((max(r,0),1))
    g = min((max(g,0),1))
    b = min((max(b,0),1))
    colors[i] = norm_rgb(r, g, b)


program = gloo.Program(vertex, fragment, count=len(galaxy))

view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -5)
program['u_model'] = model
program['u_view'] = view
program['u_colormap'] = colors
program['u_texture'] = data.get("particle.png")
program['u_texture'].interpolation = gl.GL_LINEAR

program['a_temperature'] = (galaxy['temperature'] - t0) / (t1-t0)
program['a_brightness'] = galaxy['brightness']
program['a_size'] = galaxy['size']
program['a_type'] = galaxy['type']

gl.glClearColor(0.0, 0.0, 0.03, 1.0)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)

app.run(framerate=60)
Ejemplo n.º 30
0
    paths.draw()


Albers = ConicEqualArea(scale=2 * 1285,
                        parallels=(29.5, 45.5),
                        rotate=(96, 0),
                        translate=(0, 0),
                        center=(0.38, -0.41))
transform = PanZoom(OrthographicProjection(Albers(Position()), aspect=1))
paths = PathCollection("agg+",
                       transform=transform,
                       linewidth='shared',
                       color="shared")
polys = PolygonCollection("raw", transform=transform, color="shared")

with open(data.get("us.json"), 'r') as file:
    topology = json.load(file)

scale = topology['transform']['scale']
translate = topology['transform']['translate']
arcs = topology["arcs"]

linewidth = 2.5
color = 0.0, 0.0, 0.0, 1.0
land = topology["objects"]["land"]
for coords in geometry(land, arcs, scale, translate)["coordinates"]:
    for path in coords:
        V = np.zeros((len(path), 3))
        V[:, :2] = np.array(path)
        paths.append(V, closed=True, color=color, linewidth=linewidth)
Ejemplo n.º 31
0
    {
        vec3 view_direction = normalize(-v_position);
        vec3 half_direction = normalize(light_direction + view_direction);
        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)
    
Ejemplo n.º 32
0
window = app.Window(2 * 960, 2 * 600, color=(1, 1, 1, 1))


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


Albers = ConicEqualArea(scale=2 * 1285, parallels=(29.5, 45.5), rotate=(96, 0), translate=(0, 0), center=(0.38, -0.41))
transform = PanZoom(OrthographicProjection(Albers(Position()), aspect=1))
paths = PathCollection("agg+", transform=transform, linewidth="shared", color="shared")
polys = PolygonCollection("raw", transform=transform, color="shared")

with open(data.get("us.json"), "r") as file:
    topology = json.load(file)

scale = topology["transform"]["scale"]
translate = topology["transform"]["translate"]
arcs = topology["arcs"]

linewidth = 2.5
color = 0.0, 0.0, 0.0, 1.0
land = topology["objects"]["land"]
for coords in geometry(land, arcs, scale, translate)["coordinates"]:
    for path in coords:
        V = np.zeros((len(path), 3))
        V[:, :2] = np.array(path)
        paths.append(V, closed=True, color=color, linewidth=linewidth)
Ejemplo n.º 33
0
        gl_FragData[0] = vec4(colormap_autumn(1-rate),1.0);
    else
        gl_FragData[0] = v_color;
    gl_FragData[1] = vec4(v_id, 1.0);
}
"""
user_dtype = [ ('rate', (np.float32, 1), 'shared', 0.0),
               ('id',   (np.float32, 1), 'shared', 0.0) ]
paths = PathCollection("agg+", transform=transform, linewidth='shared', color="shared")
polys = PolygonCollection("raw", transform=transform, color="shared",
                          user_dtype=user_dtype, vertex=vertex, fragment=fragment)


# Opening the topojson file
# -------------------------
with open(data.get("us.json"), 'r') as file:
    geomap = json.load(file)
arcs = geomap["arcs"]
scale = geomap['transform']['scale']
translate = geomap['transform']['translate']

# Apply scale and transform to all coordinates (= arcs)
_arcs = []
for arc in arcs:
    _arc = []
    x, y = translate[0], translate[1]
    for position in arc:
        x = x + position[0]*scale[0] 
        y = y + position[1]*scale[1] 
        _arc.append((x,y))
    _arcs.append(_arc)
Ejemplo n.º 34
0
b_indices = np.array(I, dtype=np.uint32).view(gloo.IndexBuffer)


def func3(x, y):
    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
Ejemplo n.º 35
0
        "Gaussian", "Bessel", "Sinc", "Lanczos", "Blackman"]
    
    if key == app.window.key.RIGHT:
        program['u_interpolation'] = (program['u_interpolation'] + 1) % 17
    elif key == app.window.key.LEFT:
        program['u_interpolation'] = (program['u_interpolation'] - 1) % 17
    print "Interpolation :", names[int(program['u_interpolation'])]
    
program = gloo.Program(vertex, fragment, count=4)
program["position"] = (-1,-1), (-1,+1), (+1,-1), (+1,+1)
program['texcoord'] = ( 0, 0), ( 0,+1), (+1, 0), (+1,+1)

program['u_data'] =np.array( [ [0.0,0.0,0.0,0.0,0.0],
                               [0.0,0.5,0.5,0.5,0.0],
                               [0.0,0.5,1.0,0.5,0.0],
                               [0.0,0.5,0.5,0.5,0.0],
                               [0.0,0.0,0.0,0.0,0.0] ]).astype(np.float32)

program['u_data'].interpolation = gl.GL_NEAREST
program['u_data'].wrapping = gl.GL_CLAMP
program['u_shape'] = program['u_data'].shape[:2]

program['u_kernel'] = data.get("spatial-filters.npy")
program['u_kernel'].interpolation = gl.GL_NEAREST
program['u_kernel'].wrapping = gl.GL_CLAMP

program['u_interpolation'] = 0


app.run()
Ejemplo n.º 36
0
{
     vec2 uv = <projection.inverse(v_texcoord)>;
     gl_FragColor = texture2D(texture, <scale(uv)>.xy);
} """


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

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

program = gloo.Program(vertex, fragment, count=4)
program['position'] = [(-1,-1), (-1,+1), (+1,-1), (+1,+1)]
program['texture'] = data.get("earth.jpg")
program['texture'].interpolation = gl.GL_LINEAR


# Polar projection
# ----------------
# program['projection'] = PolarProjection(
#     # This translates texture coordinates to cartesian coordinates
#     LinearScale('.x', name = 'x', domain=(-1, 1), range=(-1,1), call="forward", clamp=True),
#     LinearScale('.y', name = 'y', domain=(-1, 1), range=(-1,1), call="forward", clamp=True))
# program['scale'] = Position(
#     # This translates cartesian coordinates (polar domains) to texture coordinates
#     # LogScale('.x', name = 'x', domain=(-1,0), range=(0,1), clamp=True),
#     LinearScale('.x', name = 'x', domain=(0.2, 1.0),     range=(0,1), clamp=True),
#     LinearScale('.y', name = 'y', domain=(0.0, 2*np.pi), range=(0,1), clamp=True))
Ejemplo n.º 37
0
def on_draw(dt):
    window.clear()
    program.draw(gl.GL_TRIANGLES, I)

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

def func3(x,y):
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
x = np.linspace(-2.0, 2.0, 256).astype(np.float32)
y = np.linspace(-2.0, 2.0, 256).astype(np.float32)
X,Y = np.meshgrid(x, y)
Z = func3(X,Y)

program = gloo.Program(vertex, fragment)
V,I = primitives.plane(2.0, n=64)
program.bind(V)

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

transform = PanZoom(aspect=1)
program['transform'] = transform
window.attach(transform)
app.run()
Ejemplo n.º 38
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
from glumpy import app, gl, gloo, glm, data, text

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

@window.event
def on_draw(dt):
    window.clear()
    label.draw(x=256, y=256, color=(1,1,1,1))

font = text.TextureFont(data.get("OpenSans-Regular.ttf"), 64)
label = text.Label("Hello World !", font,
                   anchor_x = 'center', anchor_y = 'center')
app.run()
Ejemplo n.º 39
0
}
"""
paths = PathCollection("agg+",
                       transform=transform,
                       linewidth='shared',
                       color="shared")
polys = PolygonCollection("raw",
                          transform=transform,
                          color="shared",
                          fragment=fragment,
                          user_dtype=[('rate', (np.float32, 1), 'shared', 0.0)
                                      ])

# Opening the topojson file
# -------------------------
with open(data.get("us.json"), 'r') as file:
    geomap = json.load(file)
arcs = geomap["arcs"]
scale = geomap['transform']['scale']
translate = geomap['transform']['translate']

# Apply scale and transform to all coordinates (= arcs)
_arcs = []
for arc in arcs:
    _arc = []
    x, y = translate[0], translate[1]
    for position in arc:
        x = x + position[0] * scale[0]
        y = y + position[1] * scale[1]
        _arc.append((x, y))
    _arcs.append(_arc)
Ejemplo n.º 40
0
    gl.glDisable(gl.GL_BLEND)
    gl.glEnable(gl.GL_DEPTH_TEST)
    cube.draw(gl.GL_TRIANGLES, indices)

    # Rotate cube
    theta += 0.5 # degrees
    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)
    cube['u_model'] = model

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


vertices, indices = cube()
cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
cube['u_texture'] = data.get("crate.png")
cube['u_model'] = np.eye(4, dtype=np.float32)
cube['u_view'] = glm.translation(0, 0, -5)
phi, theta = 40, 30

app.run()
Ejemplo n.º 41
0
Archivo: tiger.py Proyecto: jk34/glumpy
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import re
import triangle
import numpy as np

from glumpy import app, gl, data
from glumpy.graphics.svg import Document
from glumpy.graphics.collections import PathCollection, PolygonCollection
from glumpy.transforms import Position, OrthographicProjection, PanZoom, Viewport


tiger = Document(data.get("tiger.svg"))
window = app.Window(int(tiger.viewport.width), int(tiger.viewport.height), color=(1, 1, 1, 1))


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


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

Ejemplo n.º 42
0
for i in xrange(n-1): I.append(n*n-1-i)
for i in xrange(n-1): I.append(n*(n-1) - i*n)
b_indices = np.array(I, dtype=np.uint32).view(gloo.IndexBuffer)


def func3(x,y):
    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
Ejemplo n.º 43
0
                     ("texcoord", np.float32, 2),
                     ("interpol", np.float32, 1)]).view(gloo.VertexBuffer)
vertices["position"][0] = (-1,+1), (-1,-1), (0,+1), (0,-1)
dx, dy = 1/4.0, 1/2.0
for j in range(4):
    for i in range(4):
        index = 1+j*4+i
        x, y = i/4.0, -1 + j/2.0
        vertices["position"][index] = (x,y+dy), (x,y), (x+dx,y+dy), (x+dx,y)
vertices['texcoord'] = ( 0, 0), ( 0,+1), (+1, 0), (+1,+1)
vertices['interpol'] = np.arange(17).reshape(17,1)
program.bind(vertices)
indices = np.zeros((17,6),np.uint32).view(gloo.IndexBuffer)
indices[:] = [0,1,2,1,2,3]
indices += 4*np.arange(17).reshape(17,1)

lena = data.get("lena.png")
program['u_data'] = lena
program['u_shape'] = lena.shape[1], lena.shape[0]
program['u_kernel'] = data.get("spatial-filters.npy")
program['u_data'].interpolation = gl.GL_NEAREST
program['u_data'].wrapping = gl.GL_CLAMP

x,y = 512,512
dx, dy = 0.05, 0.05
x = min(max(x/1024.0, dx), 1.0-dx)
y = min(max(y/1024.0, dy), 1.0-dy)
vertices['texcoord'][1:] = (x-dx,y-dy), (x-dy,y+dy), (x+dx, y-dy), (x+dx,y+dy)

app.run()
Ejemplo n.º 44
0
    x, y, z = spectrum_to_xyz(bb_spectrum, temperature)
    r, g, b = xyz_to_rgb(SMPTEsystem, x, y, z)
    r = min((max(r, 0), 1))
    g = min((max(g, 0), 1))
    b = min((max(b, 0), 1))
    colors[i] = norm_rgb(r, g, b)

program = gloo.Program(vertex, fragment, count=len(galaxy))

view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -5)
program['u_model'] = model
program['u_view'] = view
program['u_colormap'] = colors
program['u_texture'] = data.get("particle.png")
program['u_texture'].interpolation = gl.GL_LINEAR

program['a_temperature'] = (galaxy['temperature'] - t0) / (t1 - t0)
program['a_brightness'] = galaxy['brightness']
program['a_size'] = galaxy['size']
program['a_type'] = galaxy['type']

gl.glClearColor(0.0, 0.0, 0.03, 1.0)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)

app.run(framerate=60)
Ejemplo n.º 45
0
            OLDMUR[pos_mur] = 1
        elif dif > 0:
            posi = dif
    return posi


def posmur(pos_mur, pos_aig=0):
    """
    retourne la liste correspondant aux coordonnées des triangles du mur
    """
    return [(pos_mur, -0.25), (pos_mur, -1), (pos_mur+sticky(pos_mur, pos_aig), -0), (+1, -1),\
     (+1, +1), (pos_mur+sticky(pos_mur, pos_aig), -0), (pos_mur, 1), (pos_mur, +0.25)]


MUR1 = gloo.Program(VERTEXS, FRAGMENTS, count=8)
MUR1['texture'] = data.get("eau.png")
MUR1['position'] = posmur(MUR[0])
MUR1['scale'] = 1

MUR2 = gloo.Program(VERTEX, FRAGMENT, count=8)
MUR2['color'] = [(1, 1, 0, 1)] * 8
MUR2['position'] = posmur(MUR[1])
MUR2['scale'] = 1

MUR3 = gloo.Program(VERTEX, FRAGMENT, count=8)
MUR3['color'] = [(0, 0, 1, 1)] * 8
MUR3['position'] = posmur(MUR[2])
MUR3['scale'] = 1

#####################################################################################################
# Create a window with a valid GL context
Ejemplo n.º 46
0
    fovy = np.minimum(np.maximum(fovy*(1+dy/100), 10.0), 179.0)
    program['projection'] = glm.perspective(fovy,
                                            window.width/float(window.height),
                                            1.0, 100.0)

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


program = gloo.Program(vertex, fragment)
program.bind(V)
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
projection = np.eye(4, dtype=np.float32)
glm.translate(view, 0, 0, -3)
program['texture'] = data.get("checkerboard")
program['model'] = model
program['view'] = view
program['grid'] = Grid("pos", "index")
program['grid']["rows"] = rows
program['grid']["cols"] = cols
program['clip'] = Clip("v_index")
program['clip']["rows"] = rows
program['clip']["cols"] = cols

fovy = 30
phi, theta = 30, 20
app.run()
Ejemplo n.º 47
0
    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)

window.attach(protein["transform"])
app.run()
Ejemplo n.º 48
0

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


@window.event
def on_resize(width, height):
    program["iResolution"] = width, height


program = gloo.Program(vertex, "./regular-grid.frag")
program["texcoord"] = (-0.5, -0.5), (-0.5, +0.5), (+0.5, -0.5), (+0.5, +0.5)
program["u_texture"] = data.get("lena.png")
program["u_texture"].interpolation = gl.GL_LINEAR
program['u_major_grid_width'] = 1.5
program['u_minor_grid_width'] = 1.0
program['u_major_grid_color'] = 0, 0, 0, 1.0
program['u_minor_grid_color'] = 0, 0, 0, 1.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])
Ejemplo n.º 49
0
vertex_pos = [[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1],
              [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]
face_norm = [[0, 0, 1], [1, 0, 0], [0, 1, 0], [-1, 0, 1], [0, -1, 0],
             [0, 0, -1]]

face_vertex_idx = [
    0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5
]
face_normal_idx = [
    0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
]

# Upload the texture data
texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32).view(gloo.TextureCube)
texture.interpolation = gl.GL_LINEAR
texture[2] = data.get(abspath("Gauden/Top.jpg")) / 255.
texture[3] = data.get(abspath("Gauden/Bottom.jpg")) / 255.
texture[0] = data.get(abspath("Gauden/Right.jpg")) / 255.
texture[1] = data.get(abspath("Gauden/Left.jpg")) / 255.
texture[4] = data.get(abspath("Gauden/Front3.jpg")) / 255.
texture[5] = data.get(abspath("Gauden/Back.jpg")) / 255.

# Bind the vertex object to the cube program
cube = gloo.Program(vertex, fragment)
cube["a_position"] = [vertex_pos[i] for i in face_vertex_idx]
cube['a_normal'] = [face_norm[i] for i in face_normal_idx]
cube['u_texture'] = texture

# Initiate all three matrix
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
Ejemplo n.º 50
0
#!/usr/bin/env python3

import numpy as np
import math
import cv2
import time
import threading
from PIL import Image
from glumpy import app, gl, glm, gloo, data
from rendering import stage, transform, video, var

window = app.Window()

blah = data.get("lena.png").view(gloo.Texture2D)

@window.event
def on_draw(dt):
    app.clock.tick()
    window.clear()

    gl.glEnable(gl.GL_BLEND);
    gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD);
    gl.glBlendFuncSeparate(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA, gl.GL_ONE, gl.GL_ONE_MINUS_SRC_ALPHA);

    w, h = window.get_size()
    #print("----------")
    pipeline.render_screen(None, (w, h))
    var.ReloadVar.reload_vars()

@window.event
def on_key_press(symbol, modifiers):
Ejemplo n.º 51
0
    # Rotate cube
    theta += 0.5  # degrees
    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)
    cube['u_model'] = model


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


vertices, indices = cube()
cube = gloo.Program(vertex, fragment)
cube.bind(vertices)
cube['u_texture'] = data.get("crate.png")
cube['u_model'] = np.eye(4, dtype=np.float32)
cube['u_view'] = glm.translation(0, 0, -5)
phi, theta = 40, 30

app.run()
Ejemplo n.º 52
0
vertex_pos = [[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1],
              [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]
face_norm = [[0, 0, 1], [1, 0, 0], [0, 1, 0], [-1, 0, 1], [0, -1, 0],
             [0, 0, -1]]

face_vertex_idx = [
    0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5
]
face_normal_idx = [
    0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
]

# Upload the texture data
texture = np.zeros((6, 1024, 1024, 4), dtype=np.float32).view(gloo.TextureCube)
texture.interpolation = gl.GL_LINEAR
texture[2] = data.get(abspath("Up2.png")) / 255.
texture[3] = data.get(abspath("Down2.png")) / 255.
texture[0] = data.get(abspath("Right2.png")) / 255.
texture[1] = data.get(abspath("Left2.png")) / 255.
texture[4] = data.get(abspath("Front2.png")) / 255.
texture[5] = data.get(abspath("Back2.png")) / 255.

# Bind the vertex object to the cube program
cube = gloo.Program(vertex, fragment)
cube["a_position"] = [vertex_pos[i] for i in face_vertex_idx]
cube['a_normal'] = [face_norm[i] for i in face_normal_idx]
cube['u_texture'] = texture

# Initiate all three matrix
view = np.eye(4, dtype=np.float32)
model = np.eye(4, dtype=np.float32)
Ejemplo n.º 53
0
window = app.Window(width=2*512, height=2*512, color=(1,1,1,1))

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

@window.event
def on_resize(width, height):
    program["iResolution"] = width, height

program = gloo.Program(vertex, "./regular-grid.frag")
program["texcoord"] = (-0.5,-0.5), (-0.5, +0.5), (+0.5,-0.5), (+0.5,+0.5)
# program["u_texture"] = data.get("lena.png")
program["u_texture"] = data.get("MonaLisa.png")
program["u_texture"].interpolation = gl.GL_LINEAR
program['u_major_grid_width'] = 1.5
program['u_minor_grid_width'] = 1.0
program['u_major_grid_color'] = 0, 0, 0, 1.0
program['u_minor_grid_color'] = 0, 0, 0, 1.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])