Пример #1
0
    def get_projection_matrix(self):
        """ Return current projection matrix
        """
        # Determine the field of view of orthographic projection so that the
        # sphere of radius rview centered at the origin inscribes the field
        # of view.
        width, height = self.physical_size
        aspect = float(width) / height
        if aspect > 1:
            top = self.rview
            right = self.rview * aspect
        else:
            top = self.rview / aspect
            right = self.rview
        assert min(top, right) == self.rview
        left = -right
        bottom = -top
        near = self.zview
        far = -self.zview

        left -= 1e-6
        right += 1e-6
        bottom -= 1e-6
        top += 1e-6
        near -= 1e-6
        far += 1e-6

        return transforms.ortho(left, right, bottom, top, near, far)
Пример #2
0
 def toggle_projection(self, event=None):
     """Toggle between perspective and orthonormal projection modes."""
     self.perspective = not self.perspective
     if self.perspective:
         self.volume_renderer.set_vol_projection(perspective(60, 1., 100, 0))
     else:
         self.volume_renderer.set_vol_projection(ortho(-1, 1, -1, 1, -1000, 1000))
Пример #3
0
 def resize(self, width, height):
     gloo.set_viewport(0, 0, width, height)
     data_width = self._data_lim[0][1] - self._data_lim[0][0]
     data_height = self._data_lim[1][1] - self._data_lim[1][0]
     data_aspect = data_width / float(data_height)
     frame_aspect = width / float(height)
     if frame_aspect >= data_aspect:
         padding = (frame_aspect * data_height - data_width) / 2.
         frame_lim = [
             [self._data_lim[0][0] - padding,
              self._data_lim[0][1] + padding],
             [self._data_lim[1][0],
              self._data_lim[1][1]]]
     else:
         padding = (data_width / frame_aspect - data_height) / 2.
         frame_lim = [
             [self._data_lim[0][0],
              self._data_lim[0][1]],
             [self._data_lim[1][0] - padding,
              self._data_lim[1][1] + padding]]
     args_ortho = frame_lim[0][::(1 if self._dir_x_right else -1)]
     args_ortho += frame_lim[1][::(1 if self._dir_y_top else -1)]
     args_ortho += -1000, 1000
     self.projection = ortho(*args_ortho)
     self.program['projection'] = self.projection
Пример #4
0
    def apply_magnification(self):
        #
        canvas_w, canvas_h = self.physical_size
        gloo.set_viewport(0, 0, canvas_w, canvas_h)

        #
        ratio = self._magnification
        w, h = self._width, self._height

        self._program['u_projection'] = ortho(
            self._coordinate[0],
            canvas_w * ratio + self._coordinate[0],
            self._coordinate[1],
            canvas_h * ratio + self._coordinate[1],
            -1, 1
        )

        x, y = int((canvas_w * ratio - w) / 2), int((canvas_h * ratio - h) / 2)  # centering x & y

        #
        self._data['a_position'] = np.array(
            [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]
        )

        #
        self._program.bind(gloo.VertexBuffer(self._data))
Пример #5
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=((W * 5), (H * 5)))

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture2D(I, interpolation='linear')

        self.program['u_texture'] = self.texture
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection

        gloo.set_clear_color('white')

        self._timer = app.Timer('auto', connect=self.update, start=True)

        self.sim_is_initialized = False
        self.sim = None

        self.show()
Пример #6
0
 def on_mouse_wheel(self, event):
     #print(event.delta[1])
     oldscale=self.scale
     if event.delta[1]>0:
         self.scale /=event.delta[1]+1
     else:
         self.scale *= -event.delta[1]+1
     factor=self.scale/oldscale
     self.event=event
     self.projection = ortho(-self.scale/2, self.scale/2, -self.scale/2, self.scale/2, -1, 100) #perspective(1.0, width / float(height), 1.0, 10000000.0)
     self.program['u_projection'] = self.projection
     self.view = np.eye(4, dtype=np.float32)
     x,y=self.getEventCoordinates(event)
     print(factor)
     if factor<1:
         x-(x-self.pos[0])/factor
         y-(y-self.pos[1])/factor
     else:
         x=self.pos[0]-(x-self.pos[0])/factor
         y=self.pos[1]-(y-self.pos[1])/factor
     self.pos[0]=x
     self.pos[1]=y
     translate(self.view, -x, -y, -1)
     self.program['u_view'] = self.view
     self.getEventCoordinates(self.event)
     self.update()        
Пример #7
0
def test_transforms():
    """Test basic transforms"""
    xfm = np.random.randn(4, 4).astype(np.float32)

    # Do a series of rotations that should end up into the same orientation
    # again, to ensure the order of computation is all correct
    # i.e. if rotated would return the transposed matrix this would not work
    # out (the translation part would be incorrect)
    new_xfm = xfm.dot(rotate(180, (1, 0, 0)).dot(rotate(-90, (0, 1, 0))))
    new_xfm = new_xfm.dot(rotate(90, (0, 0, 1)).dot(rotate(90, (0, 1, 0))))
    new_xfm = new_xfm.dot(rotate(90, (1, 0, 0)))
    assert_allclose(xfm, new_xfm)

    new_xfm = translate((1, -1, 1)).dot(translate((-1, 1, -1))).dot(xfm)
    assert_allclose(xfm, new_xfm)

    new_xfm = scale((1, 2, 3)).dot(scale((1, 1. / 2., 1. / 3.))).dot(xfm)
    assert_allclose(xfm, new_xfm)

    # These could be more complex...
    xfm = ortho(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = frustum(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = perspective(1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))
Пример #8
0
    def __init__(self):
        app.Canvas.__init__(self)
        self.size = 800, 600 + 2 * 32
        self.title = "Markers demo [press space to change marker]"

        self.vbo = VertexBuffer(data)
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = ortho(0, self.size[0], 0, self.size[1], -1, 1)
        self.programs = [
            Program(markers.vert, markers.frag + markers.tailed_arrow),
            Program(markers.vert, markers.frag + markers.disc),
            Program(markers.vert, markers.frag + markers.diamond),
            Program(markers.vert, markers.frag + markers.square),
            Program(markers.vert, markers.frag + markers.cross),
            Program(markers.vert, markers.frag + markers.arrow),
            Program(markers.vert, markers.frag + markers.vbar),
            Program(markers.vert, markers.frag + markers.hbar),
            Program(markers.vert, markers.frag + markers.clobber),
            Program(markers.vert, markers.frag + markers.ring)
        ]

        for program in self.programs:
            program.set_vars(self.vbo,
                             u_antialias=u_antialias,
                             u_size=1,
                             u_model=self.model,
                             u_view=self.view,
                             u_projection=self.projection)
        self.index = 0
        self.program = self.programs[self.index]
Пример #9
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive')
        self.size = W * 5, H * 5

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture3D(I,
                                      interpolation='nearest',
                                      wrapping='clamp_to_edge')
        self.program['u_texture'] = self.texture
        self.program['i'] = 0.0
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection

        self.i = 0

        gloo.set_clear_color('white')

        self._timer = app.Timer('auto', connect=self.on_timer, start=True)
Пример #10
0
def test_transforms():
    """Test basic transforms"""
    xfm = np.random.randn(4, 4).astype(np.float32)

    for rot in [xrotate, yrotate, zrotate]:
        new_xfm = rot(rot(xfm, 90), -90)
        assert_allclose(xfm, new_xfm)

    new_xfm = rotate(rotate(xfm, 90, 1, 0, 0), 90, -1, 0, 0)
    assert_allclose(xfm, new_xfm)

    new_xfm = translate(translate(xfm, 1, -1), 1, -1, 1)
    assert_allclose(xfm, new_xfm)

    new_xfm = scale(scale(xfm, 1, 2, 3), 1, 1. / 2., 1. / 3.)
    assert_allclose(xfm, new_xfm)

    # These could be more complex...
    xfm = ortho(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = frustum(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = perspective(1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))
Пример #11
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     self.projection = ortho(0, width, 0, height, -100, 100)
     self.u_size = width / 512.0
     self.program['u_projection'] = self.projection
     self.program['u_size'] = self.u_size
Пример #12
0
def test_transforms():
    """Test basic transforms"""
    xfm = np.random.randn(4, 4).astype(np.float32)

    # Do a series of rotations that should end up into the same orientation
    # again, to ensure the order of computation is all correct
    # i.e. if rotated would return the transposed matrix this would not work
    # out (the translation part would be incorrect)
    new_xfm = xfm.dot(rotate(180, (1, 0, 0)).dot(rotate(-90, (0, 1, 0))))
    new_xfm = new_xfm.dot(rotate(90, (0, 0, 1)).dot(rotate(90, (0, 1, 0))))
    new_xfm = new_xfm.dot(rotate(90, (1, 0, 0)))
    assert_allclose(xfm, new_xfm)

    new_xfm = translate((1, -1, 1)).dot(translate((-1, 1, -1))).dot(xfm)
    assert_allclose(xfm, new_xfm)

    new_xfm = scale((1, 2, 3)).dot(scale((1, 1. / 2., 1. / 3.))).dot(xfm)
    assert_allclose(xfm, new_xfm)

    # These could be more complex...
    xfm = ortho(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = frustum(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = perspective(1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))
Пример #13
0
    def set_data(self, data):
        self.data = data

        self.xmin, self.xmax = np.nanmin(data.x_coords), np.nanmax(data.x_coords)
        self.ymin, self.ymax = np.nanmin(data.y_coords), np.nanmax(data.y_coords)
        self.zmin, self.zmax = np.nanmin(data.values), np.nanmax(data.values)

        self.cm_dx = (self.xmax-self.xmin)*0.1

        self.view = translate((0, 0, 0))
        self.projection = ortho(self.xmin, self.xmax + self.cm_dx, self.ymin, self.ymax, -1, 1)

        self.program['u_view'] = self.view
        self.program['u_projection'] = self.projection
        self.program['u_colormap'] = gloo.Texture1D(self.colormap.get_colors(), interpolation='linear')
        
        self.program_cm['u_view'] = self.view
        self.program_cm['u_projection'] = self.projection

        self.program_line['u_view'] = self.view
        self.program_line['u_projection'] = self.projection

        t0 = time.clock()
        vertices = self.generate_vertices(data)
        #print 'generate_vertices: ', time.clock()-t0
        self.vbo = gloo.VertexBuffer(vertices)
        self.program.bind(self.vbo)

        self.update()
Пример #14
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     self.projection = ortho(0, width, 0, height, -100, 100)
     self.u_size = width / 512.0
     self.program['u_projection'] = self.projection
     self.program['u_size'] = self.u_size
Пример #15
0
    def __init__(self):
        app.Canvas.__init__(self)

        # This size is used for comparison with agg (via matplotlib)
        self.size = 512, 512 + 2 * 32
        self.title = "Markers demo [press space to change marker]"

        self.vbo = VertexBuffer(data)
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = ortho(0, self.size[0], 0, self.size[1], -1, 1)
        self.programs = [
            Program(markers.vert, markers.frag + markers.tailed_arrow),
            Program(markers.vert, markers.frag + markers.disc),
            Program(markers.vert, markers.frag + markers.diamond),
            Program(markers.vert, markers.frag + markers.square),
            Program(markers.vert, markers.frag + markers.cross),
            Program(markers.vert, markers.frag + markers.arrow),
            Program(markers.vert, markers.frag + markers.vbar),
            Program(markers.vert, markers.frag + markers.hbar),
            Program(markers.vert, markers.frag + markers.clobber),
            Program(markers.vert, markers.frag + markers.ring)]

        for program in self.programs:
            program.set_vars(self.vbo,
                             u_antialias=u_antialias,
                             u_size=1,
                             u_model=self.model,
                             u_view=self.view,
                             u_projection=self.projection)
        self.index = 0
        self.program = self.programs[self.index]
Пример #16
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive')

        # This size is used for comparison with agg (via matplotlib)
        self.size = 512, 512 + 2 * 32
        self.title = "Markers demo [press space to change marker]"

        self.vbo = VertexBuffer(data)
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = ortho(0, self.size[0], 0, self.size[1], -1, 1)
        self.programs = [
            Program(markers.vert, markers.frag + markers.tailed_arrow),
            Program(markers.vert, markers.frag + markers.disc),
            Program(markers.vert, markers.frag + markers.diamond),
            Program(markers.vert, markers.frag + markers.square),
            Program(markers.vert, markers.frag + markers.cross),
            Program(markers.vert, markers.frag + markers.arrow),
            Program(markers.vert, markers.frag + markers.vbar),
            Program(markers.vert, markers.frag + markers.hbar),
            Program(markers.vert, markers.frag + markers.clobber),
            Program(markers.vert, markers.frag + markers.ring)
        ]

        for program in self.programs:
            program.bind(self.vbo)
            program["u_antialias"] = u_antialias,
            program["u_size"] = 1
            program["u_model"] = self.model
            program["u_view"] = self.view
            program["u_projection"] = self.projection
        self.index = 0
        self.program = self.programs[self.index]
Пример #17
0
 def activate_zoom(self):
     width, heigh = self.size
     gloo.set_viewport(0, 0, *self.physical_size)
     data_width = self._data_lim[0][1] - self._data_lim[0][0]
     data_height = self._data_lim[1][1] - self._data_lim[1][0]
     data_aspect = data_width / float(data_height)
     frame_aspect = width / float(height)
     if frame_aspect >= data_aspect:
         padding = (frame_aspect * data_height - data_width) / 2.
         frame_lim = [
             [self._data_lim[0][0] - padding,
              self._data_lim[0][1] + padding],
             [self._data_lim[1][0],
              self._data_lim[1][1]]]
     else:
         padding = (data_width / frame_aspect - data_height) / 2.
         frame_lim = [
             [self._data_lim[0][0],
              self._data_lim[0][1]],
             [self._data_lim[1][0] - padding,
              self._data_lim[1][1] + padding]]
     args_ortho = frame_lim[0][::(1 if self._dir_x_right else -1)]
     args_ortho += frame_lim[1][::(1 if self._dir_y_top else -1)]
     args_ortho += -1000, 1000
     self.projection = ortho(*args_ortho)
     self.program['projection'] = self.projection
Пример #18
0
 def on_resize(self, event):
     width, height = event.size
     gloo.set_viewport(0, 0, width, height)
     self.projection = ortho(0, width, 0, height, -100, 100)
     self.u_size = width / 512.0
     self.program["u_projection"] = self.projection
     self.program["u_size"] = self.u_size
Пример #19
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive')
        self.size = W * 5, H * 5

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture3D(I, interpolation='nearest',
                                      wrapping='clamp_to_edge')
        self.program['u_texture'] = self.texture
        self.program['i'] = 0.0
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection

        self.i = 0

        gloo.set_clear_color('white')

        self._timer = app.Timer('auto', connect=self.on_timer, start=True)
Пример #20
0
 def on_resize(self, event):
     width, height = event.size
     self.width=width
     self.height=height
     gloo.set_viewport(0, 0, width, height)
     self.projection = ortho(-self.scale/2, self.scale/2, -self.scale/2, self.scale/2, -1, 100) #perspective(1.0, width / float(height), 1.0, 10000000.0)
     self.program['u_projection'] = self.projection
Пример #21
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=((W * 5), (H * 5)))

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture2D(I,
                                      interpolation='linear',
                                      internalformat='r32f')

        self.program['u_texture'] = self.texture
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection

        gloo.set_clear_color('white')

        self._timer = app.Timer('auto', connect=self.update, start=True)

        self.show()
Пример #22
0
    def __init__(self, emulate3d=True):
        app.Canvas.__init__(self, keys='interactive', size=((W*5), (H*5)))

        if emulate3d:
            tex_cls = gloo.TextureEmulated3D
        else:
            tex_cls = gloo.Texture3D
        self.texture = tex_cls(img_array, interpolation='nearest',
                               wrapping='clamp_to_edge')

        self.program = ModularProgram(VERT_SHADER, FRAG_SHADER)
        self.program.frag['sampler_type'] = self.texture.glsl_sampler_type
        self.program.frag['sample'] = self.texture.glsl_sample
        self.program['u_texture'] = self.texture
        self.program['i'] = 0.0
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection

        self.i = 0

        gloo.set_clear_color('white')

        self._timer = app.Timer('auto', connect=self.on_timer, start=True)

        self.show()
def test_transforms():
    """Test basic transforms"""
    xfm = np.random.randn(4, 4).astype(np.float32)

    for rot in [xrotate, yrotate, zrotate]:
        new_xfm = rot(rot(xfm, 90), -90)
        assert_allclose(xfm, new_xfm)

    new_xfm = rotate(rotate(xfm, 90, 1, 0, 0), 90, -1, 0, 0)
    assert_allclose(xfm, new_xfm)

    new_xfm = translate(translate(xfm, 1, -1), 1, -1, 1)
    assert_allclose(xfm, new_xfm)

    new_xfm = scale(scale(xfm, 1, 2, 3), 1, 1. / 2., 1. / 3.)
    assert_allclose(xfm, new_xfm)

    # These could be more complex...
    xfm = ortho(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = frustum(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = perspective(1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))
Пример #24
0
def create_transform_ortho(aspect=1.0, view="isometric", fake_ortho=True):
    model = np.eye(4, dtype=np.float32)

    if view == "isometric":
        if fake_ortho:
            # 0.816479 = 0.5 * sqrt(3) * x = 0.5 * sqrt(2)
            # scale of y-axis to make sides and top of same height: (1.0, 0.81649, 1.0)
            # scale to get block completely into viewport (-1;1): (1.0 / math.sqrt(2), ..., ...)
            model = np.dot(model, transforms.scale((1.0 / math.sqrt(2), 0.816479 / math.sqrt(2), 1.0 / math.sqrt(2))))
        else:
            # this scale factor is just for nicely viewing the block image manually
            model = np.dot(model, transforms.scale((0.5, 0.5, 0.5)))

        # and do that nice tilt
        model = np.dot(model, np.dot(transforms.rotate(45, (0, 1, 0)), transforms.rotate(30, (1, 0, 0))))
    elif view == "topdown":
        model = np.dot(model, transforms.rotate(90, (1, 0, 0)))
    elif view == "side":
        # same thing with scaling factor as with isometric view
        #f = 1.0 / math.sqrt(2)
        f = 0.5 / math.cos(math.radians(45))
        model = np.dot(model, transforms.scale((f / math.cos(math.radians(45)), f, f)))
        model = np.dot(model, transforms.rotate(45, (1, 0, 0)))
    elif view == "default":
        pass
    else:
        assert False, "Invalid view '%s'!" % view

    view = transforms.translate((0, 0, -5))
    projection = transforms.ortho(-aspect, aspect, -1, 1, 2.0, 50.0)
    return model, view, projection
Пример #25
0
 def toggle_projection(self, event=None):
     """Toggle between perspective and orthonormal projection modes."""
     self.perspective = not self.perspective
     if self.perspective:
         self.volume_renderer.set_vol_projection(perspective(60, 1., 100, 0))
         self.volume_renderer.uniform_changes['projection'] = 'perspective'
     else:
         self.volume_renderer.set_vol_projection(ortho(-1, 1, -1, 1, -1000, 1000))
         self.volume_renderer.uniform_changes['projection'] = 'orthographic'
Пример #26
0
	def apply_zoom(self):
		width, height = self.physical_size
		gloo.set_viewport(0, 0, width, height)
		a, b, c = .5, .5, 2
		if width>height:
			a *= width/height
		else:
			b *= height/width
		self.projection = ortho(-a, a, -b, b, -c, c)
		self.program['u_projection'] = self.projection
Пример #27
0
    def __init__(self, fragment_shader, vol_texture, num_channels, entry_texture, gain=1.0):
        gloo.Program.__init__(self, self.vert_shader, fragment_shader)

        self['u_data_texture'] = vol_texture
        self['u_projection'] = ortho(-.5, .5, -.5, .5, -100, 100)
        self.bind(self.port_verts)
        self['u_model'] = self.port_model
        self['u_view'] = np.eye(4, dtype=np.float32)
        self['u_entry_texture'] = entry_texture
        self['u_gain'] = gain
        self['u_numchannels'] = num_channels
def generate_image(img_def):
    c = context.FakeCanvas()

    img = _load_img(img_def['background']['path'])
    h, w, _ = img.shape

    render_fbo = gloo.FrameBuffer(gloo.Texture2D(img), gloo.RenderBuffer(
        (h, w)))

    program = gloo.Program(_vert_std, _frag_tex)
    program['a_pos'] = _unit_square()
    program['a_tex_coord'] = _unit_square()
    gloo.set_state(blend=True,
                   blend_func=('one', 'one_minus_src_alpha'),
                   depth_test=True,
                   depth_func='always')

    with render_fbo:
        gloo.set_viewport(0, 0, w, h)
        gloo.set_clear_depth(0)
        gloo.clear(depth=True, color=False)

        instances = img_def['instances']
        # The unsigned byte depth buffer extraction sets a limit of 255 instances.
        # Can be extracted as short if necessary.
        assert (len(instances) <= 255)
        for i, inst in enumerate(instances):
            img = _load_img(inst['path'])
            ih, iw, _ = img.shape
            x, y, s, r = (inst[k] for k in ['x', 'y', 's', 'r'])

            program['u_tex'] = gloo.Texture2D(img, interpolation='linear')
            program['u_mvp'] = \
                transforms.translate((-0.5, -0.5, 0)) @ \
                transforms.scale((s * iw, s * ih, 1)) @ \
                transforms.rotate(r, (0, 0, 1)) @ \
                transforms.translate((x, y, -i-1)) @ \
                transforms.ortho(0, w, 0, h, 0, 255)

            program.draw()

        rgb = render_fbo.read(alpha=False)
        depth = gl.glReadPixels(0, 0, w, h, gl.GL_DEPTH_COMPONENT,
                                gl.GL_UNSIGNED_BYTE)
        if not isinstance(depth, np.ndarray):
            depth = np.frombuffer(depth, np.uint8)
        depth = np.flip(depth.reshape(h, w), axis=0)
        masks = np.empty((h, w, len(instances)), np.bool)
        for i in range(len(instances)):
            masks[:, :, i] = depth == i + 1

    return rgb, depth, masks
Пример #29
0
def intrinsic_to_opengl_projection(intrinsic_mat, left, right, top, bottom,
                                   near, far):
    """
    Converts intrinsic matrix to OpenGL format.
    :param intrinsic_mat: Intrinsic matrix in row-major order.
    :return: OpenGL perspective mat (including NDC matrix) in column-major
             format.
    """
    perspective_mat = np.vstack((np.hstack(
        (intrinsic_mat[0, :], 0)), np.hstack(
            (intrinsic_mat[1, :], 0)), [0, 0, near + far, near * far],
                                 np.hstack((intrinsic_mat[2, :], 0))))
    ndc_mat = ortho(left, right, bottom, top, near, far).T

    return ndc_mat.dot(perspective_mat)
Пример #30
0
    def on_mouse_wheel(self, event):
        self.zoom+= .1 if event.delta[1] > 0  else -0.1
        if self.zoom <= 0:
            self.zoom += .1
        self.projection = ortho(-1.5/self.zoom, 1.5/self.zoom, -1.75/self.zoom, 1.75/self.zoom, 0.1, 100)
        self.mvp = reduce(np.dot, [self.model,self.view,self.projection])
        if self.isSelect>-1:
            self.handleLabel(self.isSelect)

        #recalculate intersection area
        p1 = self.unProject(0, 10, 10)
        p2 = self.unProject(self.radius, 10, 10)
        self.radius_unproject = p2[0] - p1[0]

        self.update_projections()
        self.update()
Пример #31
0
    def __init__(self,
                 fragment_shader,
                 vol_texture,
                 num_channels,
                 entry_texture,
                 gain=1.0):
        gloo.Program.__init__(self, self.vert_shader, fragment_shader)

        self['u_data_texture'] = vol_texture
        self['u_projection'] = ortho(-.5, .5, -.5, .5, -100, 100)
        self.bind(self.port_verts)
        self['u_model'] = self.port_model
        self['u_view'] = np.eye(4, dtype=np.float32)
        self['u_entry_texture'] = entry_texture
        self['u_gain'] = gain
        self['u_numchannels'] = num_channels
Пример #32
0
    def __init__(self, size):
        gloo.set_viewport(0, 0, *size)

        self._size = size
        width, height = size
        self._projection_matrix = ortho(0, width, 0, height, -1, 1)
        self._state = GraphicsState()
        self._state.ctm = identity_transform.copy()
        self._state_stack = [self._state]

        self._line_renderer = LINE_RENDERER
        self._marker_renderer = MARKER_RENDERER
        self._rect_renderer = RECT_RENDERER
        self._text_renderer = TEXT_RENDERER

        self._text_pos = (0, 0)
Пример #33
0
def intrinsic_to_opengl_projection(intrinsic_mat, left, right, top, bottom,
                                   near, far):
    """
    Converts intrinsic matrix to OpenGL format.
    :param intrinsic_mat: Intrinsic matrix in row-major order.
    :return: OpenGL perspective mat (including NDC matrix) in column-major
             format.
    """
    perspective_mat = np.vstack((
        np.hstack((intrinsic_mat[0, :], 0)),
        np.hstack((intrinsic_mat[1, :], 0)),
        [0, 0, near + far, near * far],
        np.hstack((intrinsic_mat[2, :], 0))
    ))
    ndc_mat = ortho(left, right, bottom, top, near, far).T

    return ndc_mat.dot(perspective_mat)
Пример #34
0
    def on_resize(self, event):
        width, height = event.size
        gl.glViewport(0, 0, width, height)
        self.projection = ortho( 0, width, 0, height, -100, 100 )
        self.program['u_projection'] = self.projection

        # Compute thje new size of the quad 
        r = width/float(height)
        R = W/float(H)
        if r < R:
            w,h = width, width/R
            x,y = 0, int((height-h)/2)
        else:
            w,h = height*R, height
            x,y = int((width-w)/2), 0
        data['a_position'] = np.array([[x, y], [x+w, y], [x, y+h], [x+w, y+h]])
        self.program.set_vars(oogl.VertexBuffer(data))
Пример #35
0
    def on_resize(self, event):
        width, height = self.size
        gloo.set_viewport(0, 0, *event.physical_size)
        self.projection = ortho(0, width, 0, height, 0, 1)
        self.program['u_projection'] = self.projection

        # Compute the new size of the quad
        r = width / float(height)
        R = W / float(H)
        if r < R:
            w, h = width, width / R
            x, y = 0, int((height - h) / 2)
        else:
            w, h = height * R, height
            x, y = int((width - w) / 2), 0
        data['a_position'] = np.array(
            [[x, y], [x + w, y], [x, y + h], [x + w, y + h]])
        self.program.bind(gloo.VertexBuffer(data))
Пример #36
0
    def __init__(self):
        app.Canvas.__init__(self, close_keys='escape')
        self.size = W * 5, H * 5

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture2D(I)
        self.texture.interpolation = gl.GL_LINEAR

        self.program['u_texture'] = self.texture
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection
Пример #37
0
    def __init__(self):
        app.Canvas.__init__(self)
        self.size = W*5,H*5

        self.program = oogl.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = oogl.Texture2D(I)
        self.texture.set_filter(gl.GL_NEAREST, gl.GL_NEAREST)
        
        self.program['u_texture'] = self.texture
        self.program.set_vars(oogl.VertexBuffer(data))

        self.view = np.eye(4,dtype=np.float32)
        self.model = np.eye(4,dtype=np.float32)
        self.projection = np.eye(4,dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection
Пример #38
0
    def set_data(self, data):
        self.data = data
        self.data_changed = True

        vertices = self.generate_vertices(data)

        self.xmin = np.nanmin(vertices['a_position'][:, 0])
        self.xmax = np.nanmax(vertices['a_position'][:, 0])
        self.ymin = np.nanmin(vertices['a_position'][:, 1])
        self.ymax = np.nanmax(vertices['a_position'][:, 1])

        if self.xmin == self.xmax or self.ymin == self.ymax:
            logger.error(('Cannot plot because min and max values of'
                          ' vertices are identical'))

            return

        # Determines the width of the colorbar
        self.cm_dx = (self.xmax - self.xmin) * 0.1

        self.view = translate((0, 0, 0))

        # Orthogonal projection matrix
        self.projection = ortho(self.xmin, self.xmax + self.cm_dx, self.ymin,
                                self.ymax, -1, 1)

        self.data_program['u_view'] = self.view
        self.data_program['u_projection'] = self.projection

        cmap_texture = gloo.Texture1D(self.colormap.get_colors(),
                                      interpolation='linear')
        self.data_program['u_colormap'] = cmap_texture

        self.colorbar_program['u_view'] = self.view
        self.colorbar_program['u_projection'] = self.projection

        self.linecut_program['u_view'] = self.view
        self.linecut_program['u_projection'] = self.projection

        self.vbo = gloo.VertexBuffer(vertices)
        self.data_program.bind(self.vbo)

        self.update()
Пример #39
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive')
        self.size = W * 5, H * 5

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture2D(I, interpolation='linear')

        self.program['u_texture'] = self.texture
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, -1, 1)
        self.program['u_projection'] = self.projection
        
        self._timer = app.Timer('auto', connect=self.update, start=True)
Пример #40
0
    def get_projection(self, viewbox):

        w, h = viewbox.resolution

        fov = self._fov
        aspect = 1.0
        fx = fy = 1.0  # todo: hard-coded

        # Calculate distance to center in order to have correct FoV and fy.
        if fov == 0:
            M = transforms.ortho(-0.5 * fx, 0.5 * fx, -0.5 * fy, 0.5 * fy,
                                 -10000, 10000)
            self._d = 0
        else:
            d = fy / (2 * math.tan(math.radians(fov) / 2))
            val = math.sqrt(10000)  # math.sqrt(getDepthValue())
            znear, zfar = d / val, d * val
            M = transforms.perspective(fov, aspect, znear, zfar)

        # Translation and rotation is done by our 'transformation' parameter

        return M
Пример #41
0
 def get_projection(self, viewbox):
     
     w, h = viewbox.resolution
     
     fov = self._fov
     aspect = 1.0
     fx = fy = 1.0 # todo: hard-coded
     
     # Calculate distance to center in order to have correct FoV and fy.
     if fov == 0:
         M = transforms.ortho(-0.5*fx, 0.5*fx, -0.5*fy, 0.5*fy, -10000, 10000)
         self._d = 0
     else:
         d = fy / (2 * math.tan(math.radians(fov)/2))
         val = math.sqrt(10000)  # math.sqrt(getDepthValue())
         znear, zfar = d/val, d*val
         M = transforms.perspective(fov, aspect, znear, zfar)
     
     # Translation and rotation is done by our 'transformation' parameter
     
     return M
 
     
Пример #42
0
    def set_data(self, data):
        self.data = data
        self.data_changed = True

        vertices = self.generate_vertices(data)

        self.xmin = np.nanmin(vertices['a_position'][:,0])
        self.xmax = np.nanmax(vertices['a_position'][:,0])
        self.ymin = np.nanmin(vertices['a_position'][:,1])
        self.ymax = np.nanmax(vertices['a_position'][:,1])

        if self.xmin == self.xmax or self.ymin == self.ymax:
            print('ERROR: Cannot plot because min and max values are the same')
            return

        self.cm_dx = (self.xmax - self.xmin) * 0.1

        self.view = translate((0, 0, 0))

        self.projection = ortho(self.xmin, self.xmax + self.cm_dx,
                                self.ymin, self.ymax, -1, 1)

        self.data_program['u_view'] = self.view
        self.data_program['u_projection'] = self.projection
        self.data_program['u_colormap'] = gloo.Texture1D(self.colormap.get_colors(),
                                                         interpolation='linear')

        self.colormap_program['u_view'] = self.view
        self.colormap_program['u_projection'] = self.projection

        self.linecut_program['u_view'] = self.view
        self.linecut_program['u_projection'] = self.projection

        self.vbo = gloo.VertexBuffer(vertices)
        self.data_program.bind(self.vbo)

        self.update()
Пример #43
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=((360), (360)))

        self.data = np.zeros((W, H)).astype(np.float32)

        # gradient 90deg
        for i in range(0,90):
            self.data[i, :] = i / 90.

        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.texture = gloo.Texture2D(self.data, interpolation='linear')
        self.program['u_texture'] = self.texture
        self.program.bind(gloo.VertexBuffer(data))

        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.projection = ortho(0, W, 0, H, 0, 1)
        self.program['u_projection'] = self.projection

        self.scale = self.program["scale"] = 1.
        self.center = self.program["center"] = [0, 0]
        self.bounds = [-1, 1]
        self.min_scale = 0.00005
        self.max_scale = 4
        self.aspect = 1.

        gloo.set_clear_color('black')

        self._timer = app.Timer('auto', connect=self.update, start=True)
        self.measure_fps()

        self.show()
Пример #44
0
 def activate_zoom(self):
     gloo.set_viewport(0, 0, *self.physical_size)
     projection = ortho(0, self.size[0], 0, self.size[1], -1, +1)
     self.program['u_projection'] = projection
Пример #45
0
 def on_resize(self, event):
     gloo.set_viewport(0, 0, *event.size)
     projection = ortho(0, event.size[0], 0, event.size[1], -1, +1)
     self.program['u_projection'] = projection
Пример #46
0
    def __init__(self, n, parent,**kwargs):
        app.Canvas.__init__(self, size=(400, 400),**kwargs)
        #self.native.setLayout(QtGui.QLayout())

        #bind shaders to programs
        self.points = gloo.Program(vertex, fragment)
        self.lines = gloo.Program(vertex2,fragment2)

        # Set attributes
        positions = self.vogel_sphere(n)
        index = np.zeros((n, 2), dtype=np.uint32)
        index[:, 0] = n
        index[:, 1] = np.arange(n, dtype=np.uint32)

        #upload data to shaders
        shader_pos = positions[:,:3]
        print 'initial positions', shader_pos[:n,:]
        self.points['position'] = gloo.VertexBuffer(shader_pos[:n,:])
        self.lines['position'] = gloo.VertexBuffer(shader_pos)

        self.points['radius'] = 5
        self.points['fg_color'] = 0.984, 0.980, 0.635, .5
        colors = np.random.uniform(0.75, 1.00, (n, 4)).astype(dtype=np.float32)
        colors[:, 3] = 1
        self.points['bg_color'] = colors
        self.points['linewidth'] = 1.0

        #set up matrices
        self.view=translate((0, 0, -5.0))
        self.model = np.eye(4, dtype=np.float32)
        #self.projection = ortho(-.5, .5, -.75, .75, 0.1, 100)
        self.projection = ortho(-1.5, 1.5, -1.75, 1.75, 0.1, 100)
        self.mvp = np.dot(self.view, self.projection)

        #bind matrices
        self.update_projections()
        self.update_models()
        self.update_views()

        #bind variables
        self.index = gloo.IndexBuffer(index)
        self.positions = positions[:n,:]
        self.world = np.ndarray((n,4))
        self.world[:,:] = self.positions[:,:]
        self.tree = Geometry.kdtree(self.positions.tolist())
        self.colors = colors
        self.theta = 0
        self.phi = 0
        self.oldx, self.oldy = 0,0
        self.radius = self.points['radius']+self.points['linewidth']
        self.parent = parent

        ##dealing with hovering/selecting intricacies
        self.prev_data = np.ndarray((1,5))
        self.prev_data[0,0] = 0
        self.prev_data[0,1:] = colors[0,:]
        self.isPrev = False
        self.isSelect = -1
        self.isPressed = False
        self.isDragged = False
        self.isHover = False
        self.num = n
        self.zoom = 1

        #calculate unprojected radius for ray casting
        self.viewport = (0,0,328,400) #setup fake viewport
        p1 = self.unProject(0,10,10)
        p2 = self.unProject(self.radius,10,10)
        self.radius_unproject = p2[0]-p1[0]

        #bind mouse callbacks
        self.events.mouse_press.connect(self.on_mouse_press)
        self.events.mouse_release.connect(self.on_mouse_release)
        self.events.mouse_move.connect(self.on_mouse_move)

        #init gl
        gloo.set_clear_color((1, 1, 1, 1))
        gloo.set_state(depth_test=True)

        #self._timer = app.Timer('auto', connect=self.update_transforms)
        #self._timer.start()

        # Label
        self.label = QtGui.QLabel("Point Name", self.native)
        #self.label.setGeometry(100, 100, 75, 20)
        self.label.setStyleSheet("background-color: white;")
        self.label.hide()
Пример #47
0
 def activate_zoom(self):
     gloo.set_viewport(0, 0, *self.physical_size)
     projection = ortho(0, self.size[0], 0,
                        self.size[1], -1, +1)
     self.program['u_projection'] = projection
Пример #48
0
def reshape(width, height):
    gloo.set_viewport(0, 0, width, height)
    projection = ortho(0, width, 0, height, -1, +1)
    program['u_projection'] = projection
Пример #49
0
 def on_resize(self, event):
     gloo.set_viewport(0, 0, *event.size)
     projection = ortho(0, event.size[0], 0, event.size[1], -1, +1)
     self.program['u_projection'] = projection