Exemplo n.º 1
0
 def make_screen_fbo(self, screen):
     fbo = Fbo(size=screen.size)
     with fbo:
         ClearColor(0, 1, 0, 1)
         ClearBuffers()
     fbo.add(screen.canvas)
     return fbo
Exemplo n.º 2
0
def insert_combined(state, texture_size, texture_name, texture_list):
    """
        TODO
        """
    tile_size = screen.get_tile_size(state)
    texture_size *= tile_size

    if len(texture_list) == 0:
        raise YapygTextureDbException(
            "insert_combined() called with empty list")
    elif len(texture_list) == 1:
        # Single texture, just load it and enter it with the
        # tile name as key to texture dict
        load(state, texture_name, texture_list[0])
    else:
        # Combine several textures into one
        texture = Texture.create(size=(texture_size, texture_size),
                                 colorfmt='rgba')
        for texture_filename in texture_list:
            other_texture = Image(source=texture_filename).texture
            fbo = Fbo(size=(texture_size, texture_size), texture=texture)
            with fbo:
                Color(1, 1, 1)
                Rectangle(pos=(0, 0),
                          size=other_texture.size,
                          texture=other_texture)
            fbo.draw()
        insert(state, texture_name, texture)
Exemplo n.º 3
0
def create_texture(state, text, font_name):
    """
        TODO
        """
    font_def = state[globals.IDX_STATE_TEXT][font_name]
    text_lines = text.split("\n")
    n_lines = len(text_lines)
    max_line_length = len(max(text_lines, key=len))
    texture_w = max_line_length * font_def[IDX_TEXT_WIDTH]
    texture_h = n_lines * font_def[IDX_TEXT_HEIGHT]
    texture = Texture.create(size=(texture_w, texture_h), colorfmt='rgba')
    fbo = Fbo(size=(texture_w, texture_h), texture=texture)
    for row in xrange(n_lines):
        cur_row = text_lines[row]
        for col in xrange(len(cur_row)):
            char = cur_row[col]
            char_texture = get_character_texture(state, font_name, char)
            x_pos = col * font_def[IDX_TEXT_WIDTH]
            y_pos = (n_lines - row - 1) * font_def[IDX_TEXT_HEIGHT]
            with fbo:
                Rectangle(pos=(x_pos, y_pos),
                          size=(font_def[IDX_TEXT_WIDTH],
                                font_def[IDX_TEXT_HEIGHT]),
                          texture=char_texture)
            fbo.draw()
    return texture
Exemplo n.º 4
0
def load_walls(state, base_name, background_file, tile_file, with_collisions=True):
        """
        TODO
        """
        tile_size = screen.get_tile_size(state)
        int_tile_size = int(tile_size)
        background_texture = Image(source=background_file).texture
        walls_texture = Image(source=tile_file).texture
        for tile_name, origin_xy, collision in tiles_origin_table:
                full_tile_name = base_name + tile_name
                wall_texture = walls_texture.get_region(
                        origin_xy[0] * int_tile_size,
                        origin_xy[1] * int_tile_size,
                        int_tile_size,
                        int_tile_size)

                tile_texture = Texture.create(size=(int_tile_size, int_tile_size), colorfmt='rgba')
                fbo = Fbo(size=(int_tile_size, int_tile_size), texture=tile_texture)
                with fbo:
                        Color(1, 1, 1)
                        Rectangle(pos=(0, 0), size=tile_texture.size, texture=background_texture)
                        Rectangle(pos=(0, 0), size=tile_texture.size, texture=wall_texture)
                fbo.draw()
                if not with_collisions:
                        collision = None
                tiles.add_tile_def(state, full_tile_name, tile_texture, collision)
Exemplo n.º 5
0
    def _prepare_preview_fbo(self, resolution):
        self.preview_fbo = Fbo(size=resolution)
        self.preview_fbo['resolution'] = [float(f) for f in resolution]
        self.preview_fbo.shader.fs = """
            #extension GL_OES_EGL_image_external : require
            #ifdef GL_ES
                precision highp float;
            #endif

            /* Outputs from the vertex shader */
            varying vec4 frag_color;
            varying vec2 tex_coord0;

            /* uniform texture samplers */
            uniform sampler2D texture0;
            uniform samplerExternalOES texture1;
            uniform vec2 resolution;

            void main()
            {
                gl_FragColor = texture2D(texture1, tex_coord0);
            }
        """
        with self.preview_fbo:
            Rectangle(size=resolution)
Exemplo n.º 6
0
class FboTest(Widget):
    def __init__(self, **kwargs):
        super(FboTest, self).__init__(**kwargs)
        self.positions = [
            (260.0, 260.0),
            (192.0, 192.0),
            (96.0, 192.0),
            (192.0, 96.0),
            (96.0, 96.0),
            (32.0, 192.0),
            (192.0, 32.0),
            (32.0, 32.0)
        ]

        self.fbo = Fbo(size=(256, 256))
        with self.fbo:
            Color(0.56789, 0, 0, 1)
            Rectangle(size=(256, 64))
            Color(0, 0.56789, 0, 1)
            Rectangle(size=(64, 256))
            Color(0.56789, 0, 0, .5)
            Rectangle(pos=(64, 64), size=(192, 64))
            Color(0, 0.56789, 0, .5)
            Rectangle(pos=(64, 64), size=(64, 192))
        self.fbo.draw()
    def __init__(self, **kwargs):
        # Make sure opengl context exists
        EventLoop.ensure_window()

        self.canvas = RenderContext(use_parent_projection=True,
                                    use_parent_modelview=True)

        with self.canvas:
            self.fbo = Fbo(size=self.size)

        with self.fbo.before:
            PushMatrix()
        with self.fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            self._background_color = Color(*self.background_color)
            self.fbo_rectangle = Rectangle(size=self.size)
        with self.fbo.after:
            PopMatrix()

        super(EffectWidget, self).__init__(**kwargs)

        Clock.schedule_interval(self._update_glsl, 0)

        fbind = self.fbind
        fbo_setup = self.refresh_fbo_setup
        fbind('size', fbo_setup)
        fbind('effects', fbo_setup)
        fbind('background_color', self._refresh_background_color)

        self.refresh_fbo_setup()
        self._refresh_background_color()  # In case thi was changed in kwargs
Exemplo n.º 8
0
    def __init__(self, fs, length1, length2 = 1):
        size = (length1, length2)

        # it doesn't look like we can use float textures on mobile kivy, but people sometimes interconvert floats with 32bit rgba in shaders.
        # we would then have 3 shaders or texture rows or such, for x coord, y coord, angle, etc

        #Logger.info('float: ' + str(gl.getExtension('OES_texture_float')))
        texture = Texture.create(
            size = size,
            #bufferfmt = 'float'
        )
        self._fbo = Fbo(
            size = size,
            texture = texture,
            vs = default_vs,
            fs = header_fs + fs, 
        )

        # these matrices are to transform
        # window coordinates into data
        # coordinates
        centermat = Matrix()
        centermat.translate(-.5,-.5,-.5)
        idxscale = 1.0 / 255.0;
        idxmat = Matrix()
        idxmat.scale(idxscale, idxscale, idxscale)
        self._fbo['frag_coord2idx'] = idxmat.multiply(centermat)
        ratiomat = Matrix()
        ratiomat.scale(1.0 / length1, 1.0 / length2, 1.0)
        self._fbo['frag_coord2ratio'] = ratiomat

        self._texture_bindings = {}

        self._fbo.add_reload_observer(self._populate_fbo)
        self._populate_fbo(self._fbo)
Exemplo n.º 9
0
 def make_screen_fbo(self, screen):
     fbo = Fbo(size=screen.size)
     with fbo:
         ClearColor(0, 0, 0, 1)
         ClearBuffers()
     fbo.add(screen.canvas)
     return fbo
Exemplo n.º 10
0
class FboTest(Widget):
    def __init__(self, **kwargs):
        super(FboTest, self).__init__(**kwargs)
        self.positions = [
            (260.0, 260.0),
            (192.0, 192.0),
            (96.0, 192.0),
            (192.0, 96.0),
            (96.0, 96.0),
            (32.0, 192.0),
            (192.0, 32.0),
            (32.0, 32.0)
        ]

        self.fbo = Fbo(size=(256, 256))
        with self.fbo:
            Color(0.56789, 0, 0, 1)
            Rectangle(size=(256, 64))
            Color(0, 0.56789, 0, 1)
            Rectangle(size=(64, 256))
            Color(0.56789, 0, 0, .5)
            Rectangle(pos=(64, 64), size=(192, 64))
            Color(0, 0.56789, 0, .5)
            Rectangle(pos=(64, 64), size=(64, 192))
        self.fbo.draw()
Exemplo n.º 11
0
	def __init__(self, code, **kwargs):
		Fbo.__init__(self, **kwargs)
		self.canvas = RenderContext()

		shader = self.canvas.shader
		shader.fs = header + code
		if not shader.success:
			print '! Shader compilation failed (GLSL)'
			assert False
Exemplo n.º 12
0
    def __init__(self, code, **kwargs):
        Fbo.__init__(self, **kwargs)
        self.canvas = RenderContext()

        shader = self.canvas.shader
        shader.fs = header + code
        if not shader.success:
            print '! Shader compilation failed (GLSL)'
            assert False
Exemplo n.º 13
0
def circle_fs(size=(64, 64)):

    fbo = Fbo(size=size)
    fbo.shader.fs = circle_test

    with fbo:
        Color(1, 1, 1)
        Rectangle(size=size)
    fbo.draw()
    return fbo.texture
Exemplo n.º 14
0
class Scaled(Widget):
    def __init__(self, **kwargs):
        super(Scaled, self).__init__(**kwargs)

        self.elements = []
        self.pointsize = 5  # this multiplies by two according to kivy docs

        with self.canvas:
            self._fbo = Fbo(size=self.size)
            self._rect = Rectangle(texture=self._fbo.texture)

        with self._fbo:
            Color(1, 1, 1)
            self._fborect = Rectangle(size=self._fbo.size)
            Color(0, 0, 1)
            self._points = Point(pointsize=self.pointsize)

        self._fbo.add_reload_observer(self._clear_fbo)
        self.bind(pos=self._update_rect, size=self._update_rect)

    def drawpoint(self, x, y):
        self.elements.append([x, y])
        self._points.add_point(x, y)

    def draw(self, matrix):
        self._points.points = []
        self._clear_fbo()

        for point in matrix:
            x = int(point[0] * (self.pointsize * 2) + self.pointsize)
            y = int(point[1] * (self.pointsize * 2) + self.pointsize)
            self.drawpoint(x, y)

    # RELOADING THE BUFFER AT ANY CHANGE
    def _clear_fbo(self, fbo=None):
        """ This will reload the framebufferer either by the call of the
        observer or by the deletion of a point"""
        if fbo is None:
            fbo = self._fbo

        fbo.bind()
        fbo.clear_buffer()
        fbo.add(Color(1, 1, 1))
        fbo.add(self._fborect)
        fbo.add(Color(0, 0, 1))
        fbo.add(self._points)
        fbo.release()

    def _update_rect(self, instance, value):
        self._fbo.size = instance.size
        self._fborect.size = instance.size
        self._rect.size = instance.size
        self._rect.pos = instance.pos
        self._rect.texture = self._fbo.texture
    def init_camera(self):
        self._release_camera()
        self._android_camera = Camera.open(self._index)
        params = self._android_camera.getParameters()
        width, height = self._resolution
        zoom = self._zoom  # edit by ableity
        focusmode = self._focusmode  # edit by lilei
        params.setPreviewSize(width, height)
        params.setFocusMode(focusmode)  #edit by lilei
        params.setZoom(zoom)  # edit by ableity
        self._android_camera.setParameters(params)
        # self._android_camera.setDisplayOrientation()
        self.fps = 30.

        pf = params.getPreviewFormat()
        assert (pf == ImageFormat.NV21)  # default format is NV21
        self._bufsize = int(
            ImageFormat.getBitsPerPixel(pf) / 8. * width * height)

        self._camera_texture = Texture(width=width,
                                       height=height,
                                       target=GL_TEXTURE_EXTERNAL_OES,
                                       colorfmt='rgba')
        self._surface_texture = SurfaceTexture(int(self._camera_texture.id))
        self._android_camera.setPreviewTexture(self._surface_texture)

        self._fbo = Fbo(size=self._resolution)
        self._fbo['resolution'] = (float(width), float(height))
        self._fbo.shader.fs = '''
            #extension GL_OES_EGL_image_external : require
            #ifdef GL_ES
                precision highp float;
            #endif

            /* Outputs from the vertex shader */
            varying vec4 frag_color;
            varying vec2 tex_coord0;

            /* uniform texture samplers */
            uniform sampler2D texture0;
            uniform samplerExternalOES texture1;
            uniform vec2 resolution;

            void main()
            {
                vec2 coord = vec2(tex_coord0.y * (
                    resolution.y / resolution.x), 1. -tex_coord0.x);
                gl_FragColor = texture2D(texture1, tex_coord0);
            }
        '''
        with self._fbo:
            self._texture_cb = Callback(
                lambda instr: self._camera_texture.bind)
            Rectangle(size=self._resolution)
    def test_fbo_pixels(self):
        from kivy.graphics import Fbo, ClearColor, ClearBuffers, Ellipse

        fbo = Fbo(size=(512, 512))
        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Ellipse(pos=(100, 100), size=(100, 100))
        fbo.draw()
        data = fbo.pixels
        fbo.texture.save('results.png')
Exemplo n.º 17
0
class Scaled(Widget):
    def __init__(self, **kwargs):
        super(Scaled, self).__init__(**kwargs)

        self.elements = []
        self.pointsize = 5  # this multiplies by two according to kivy docs

        with self.canvas:
            self._fbo = Fbo(size=self.size)
            self._rect = Rectangle(texture=self._fbo.texture)

        with self._fbo:
            Color(1, 1, 1)
            self._fborect = Rectangle(size=self._fbo.size)
            Color(0, 0, 1)
            self._points = Point(pointsize=self.pointsize)

        self._fbo.add_reload_observer(self._clear_fbo)
        self.bind(pos=self._update_rect, size=self._update_rect)

    def drawpoint(self, x, y):
        self.elements.append([x, y])
        self._points.add_point(x, y)

    def draw(self, matrix):
        self._points.points = []
        self._clear_fbo()

        for point in matrix:
            x = int(point[0] * (self.pointsize * 2) + self.pointsize)
            y = int(point[1] * (self.pointsize * 2) + self.pointsize)
            self.drawpoint(x, y)

    # RELOADING THE BUFFER AT ANY CHANGE
    def _clear_fbo(self, fbo=None):
        ''' This will reload the framebufferer either by the call of the
        observer or by the deletion of a point'''
        if fbo is None:
            fbo = self._fbo

        fbo.bind()
        fbo.clear_buffer()
        fbo.add(Color(1, 1, 1))
        fbo.add(self._fborect)
        fbo.add(Color(0, 0, 1))
        fbo.add(self._points)
        fbo.release()

    def _update_rect(self, instance, value):
        self._fbo.size = instance.size
        self._fborect.size = instance.size
        self._rect.size = instance.size
        self._rect.pos = instance.pos
        self._rect.texture = self._fbo.texture
Exemplo n.º 18
0
    def test_fbo_pixels(self):
        from kivy.graphics import Fbo, ClearColor, ClearBuffers, Ellipse

        fbo = Fbo(size=(512, 512))
        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Ellipse(pos=(100, 100), size=(100, 100))
        fbo.draw()
        data = fbo.pixels
        fbo.texture.save('results.png')
Exemplo n.º 19
0
 def make_screen_fbo(self, screen):
     fbo = Fbo(size=screen.size, with_stencilbuffer=True)
     with fbo:
         ClearColor(*self.clearcolor)
         ClearBuffers()
     fbo.add(screen.canvas)
     with fbo.before:
         PushMatrix()
         Translate(-screen.x, -screen.y, 0)
     with fbo.after:
         PopMatrix()
     return fbo
Exemplo n.º 20
0
 def make_screen_fbo(self, screen):
     fbo = Fbo(size=screen.size)
     with fbo:
         ClearColor(0, 0, 0, 1)
         ClearBuffers()
     fbo.add(screen.canvas)
     with fbo.before:
         PushMatrix()
         Translate(-screen.x, -screen.y, 0)
     with fbo.after:
         PopMatrix()
     return fbo
Exemplo n.º 21
0
    def setupVTK(self):
        Clock.schedule_interval(self.updateVTK, 1 / 1.)
        with self.canvas:
            self.fbo = Fbo(size=(512, 512),
                           clear_color=(.3, .3, .3, .8),
                           push_viewport=True,
                           with_depthbuffer=True)
            self.size = self.fbo.size
            Color(0, 0, 1)
            Rectangle(pos=self.pos, size=self.size, texture=self.fbo.texture)

            Callback(self.drawVTK, reset_context=True)
Exemplo n.º 22
0
 def make_screen_fbo(self, screen):
     fbo = Fbo(size=screen.size)
     with fbo:
         ClearColor(*self.clearcolor)
         ClearBuffers()
     fbo.add(screen.canvas)
     with fbo.before:
         PushMatrix()
         Translate(-screen.x, -screen.y, 0)
     with fbo.after:
         PopMatrix()
     return fbo
Exemplo n.º 23
0
class FboCapture(FloatLayout):

    texture = ObjectProperty(None)

    texture_thumb = ObjectProperty(None)

    thumb_size = ListProperty([50, 50])

    def __init__(self, **kwargs):
        self.canvas = Canvas()
        with self.canvas:
            self.fbo = Fbo(size=self.size)
        self.fbo_thumb = Fbo(size=self.thumb_size)
        with self.fbo:
            Color(0, 0, 0)
            self.fbo_rect = Rectangle(size=self.size)
        self.texture = self.fbo.texture
        with self.fbo_thumb:
            Color(1, 1, 1)
            self.fbo_thumb_rect = Rectangle(size=self.thumb_size)
        super(FboCapture, self).__init__(**kwargs)

    def on_size(self, instance, value):
        w, h = value
        ratio = float(w) / h
        if w > h:
            w = 160
            h = w / ratio
        else:
            h = 160
            w = h * ratio
        w = max(1, w)
        h = max(1, h)
        self.thumb_size = int(w), int(h)
        self.fbo.size = value
        self.fbo_rect.size = value
        self.texture = self.fbo.texture
        self.fbo_thumb_rect.texture = self.fbo.texture

    def on_thumb_size(self, instance, value):
        self.fbo_thumb.size = value
        self.fbo_thumb_rect.size = value
        self.texture_thumb = self.fbo_thumb.texture

    def add_widget(self, child):
        child.parent = self
        self.children.insert(0, child)
        self.fbo.add(child.canvas)

    def remove_widget(self, child):
        self.children.remove(child)
        self.fbo.remove(child.canvas)
Exemplo n.º 24
0
    def capture_image(self, filename):
        """
        Capture only the visible part of the camera, without the black border.
        Similar to export_to_png but with adjusted coordinates.
        :param filename: path to the target file name
        :return True
        """
        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            if canvas_parent_index > -1:
                self.parent.canvas.remove(self.canvas)

        nw, nh = self.norm_image_size
        fbo = Fbo(size=(nw, nh), with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            Scale(1, -1, 1)
            x = -self.x-(self.width-nw)/2
            y = -self.y-(self.height-nh)/2 - nh
            Translate(x, y, 0)

        fbo.add(self.canvas)
        fbo.draw()
        fbo.texture.save(filename, flipped=False)
        fbo.remove(self.canvas)

        if self.parent is not None and canvas_parent_index > -1:
            self.parent.canvas.insert(canvas_parent_index, self.canvas)

        return True
Exemplo n.º 25
0
def hue_transform(source, hue, size=(64, 64)):

    fbo = Fbo(size=size)
    fbo.shader.fs = hue_xfo

    # use the shader on the entire surface
    fbo['hueAdjust'] = float(hue)

    with fbo:
        Color(1, 1, 1)
        Rectangle(size=size, source=source)
    fbo.draw()

    return fbo.texture
Exemplo n.º 26
0
    def add_image(self, widget):
        filename = f"tmp_{self.img_counter}.png"
        output_size = (self.meta_data["width"], self.meta_data["height"])

        if self.meta_data["WH_ratio"] != widget.width // widget.height:
            raise Exception("W/H ratio does not match")

        img_scale = self.meta_data["width"] / widget.width

        if widget.parent is not None:
            canvas_parent_index = widget.parent.canvas.indexof(widget.canvas)
            if canvas_parent_index > -1:
                widget.parent.canvas.remove(widget.canvas)

        fbo = Fbo(size=output_size, with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            Scale(img_scale, -img_scale, img_scale)
            Translate(-widget.x, -widget.y - widget.height, 0)

        fbo.add(widget.canvas)
        fbo.draw()
        fbo.texture.save(self.tmp_imgs_path + filename, flipped=False)
        fbo.remove(widget.canvas)

        if widget.parent is not None and canvas_parent_index > -1:
            widget.parent.canvas.insert(canvas_parent_index, widget.canvas)

        self.img_counter += 1
Exemplo n.º 27
0
        def save_montage(background):
            fbo = Fbo(size=PAPER_SIZE)

            w, h = fbo.size
            length = int(0.9 *
                         w)  # Picture will be square of 90% of paper width
            length = min(length, int(h * 0.85 / NPHOTOS))

            with fbo:
                Rectangle(size=fbo.size, pos=(0, 0), texture=background)
                for i in range(NPHOTOS):
                    Rectangle(size=(length, length),
                              pos=(int(0.5 * (w - length)),
                                   int(h - (i + 1) * (0.25 *
                                                      (w - length) + length))),
                              texture=self.snaps[i])
            # Carry the actual draw
            fbo.draw()

            # Save the final composition
            stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            montage_file = osp.join(curdir, STORAGE_FOLDER,
                                    "picture_{}.jpg".format(stamp))
            fbo.bind()
            fbo.texture.save(montage_file, flipped=True)
            fbo.release()
            del fbo

            return montage_file
Exemplo n.º 28
0
    def capture_image(self, filename):
        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            if canvas_parent_index > -1:
                self.parent.canvas.remove(self.canvas)

        nw, nh = self.norm_image_size
        fbo = Fbo(size=(nw, nh), with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            Scale(1, -1, 1)
            x = -self.x - (self.width - nw) / 2
            y = -self.y - (self.height - nh) / 2 - nh
            Translate(x, y, 0)

        fbo.add(self.canvas)
        fbo.draw()
        fbo.texture.save(filename, flipped=False)
        fbo.remove(self.canvas)

        if self.parent is not None and canvas_parent_index > -1:
            self.parent.canvas.insert(canvas_parent_index, self.canvas)

        return True
Exemplo n.º 29
0
    def export_as_image(self, *args, **kwargs):

        # overwrite the function, because ClearColor is set to black per default
        from kivy.core.image import Image
        scale = kwargs.get('scale', 1)

        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            if canvas_parent_index > -1:
                self.parent.canvas.remove(self.canvas)

        fbo = Fbo(size=(self.width * scale, self.height * scale),
                  with_stencilbuffer=True)

        with fbo:
            ClearColor(1, 1, 1, 1)
            ClearBuffers()
            Scale(1, -1, 1)
            Scale(scale, scale, 1)
            Translate(-self.x, -self.y - self.height, 0)

        fbo.add(self.canvas)
        fbo.draw()
        img = Image(fbo.texture)
        fbo.remove(self.canvas)

        if self.parent is not None and canvas_parent_index > -1:
            self.parent.canvas.insert(canvas_parent_index, self.canvas)

        return img
def export_to_png(self, filename, *args):
    '''Saves an image of the widget and its children in png format at the
    specified filename. Works by removing the widget canvas from its
    parent, rendering to an :class:`~kivy.graphics.fbo.Fbo`, and calling
    :meth:`~kivy.graphics.texture.Texture.save`.
    '''

    if self.parent is not None:
        canvas_parent_index = self.parent.canvas.indexof(self.canvas)
        self.parent.canvas.remove(self.canvas)

    fbo = Fbo(size=self.size)

    with fbo:
        ClearColor(0, 0, 0, 1)
        ClearBuffers()
        Translate(-self.x, -self.y, 0)

    fbo.add(self.canvas)
    fbo.draw()
    fbo.texture.save(filename)
    fbo.remove(self.canvas)

    if self.parent is not None:
        self.parent.canvas.insert(canvas_parent_index, self.canvas)

    return True
Exemplo n.º 31
0
    def get_frame_data(self, *args):
        """Return the content of this display as buffer.

        @see: widget.export_to_png
        """
        del args
        if self._slide_manager_parent.parent is not None:
            canvas_parent_index = self._slide_manager_parent.parent.canvas.indexof(self._slide_manager_parent.canvas)
            if canvas_parent_index > -1:
                self._slide_manager_parent.parent.canvas.remove(self._slide_manager_parent.canvas)

        fbo = Fbo(size=self._slide_manager_parent.size, with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Scale(1, -1, 1)
            Translate(-self._slide_manager_parent.x, -self._slide_manager_parent.y - self._slide_manager_parent.height, 0)

        fbo.add(self._slide_manager_parent.canvas)
        fbo.draw()
        data = fbo.texture.pixels
        fbo.remove(self._slide_manager_parent.canvas)

        if self._slide_manager_parent.parent is not None and canvas_parent_index > -1:
            self._slide_manager_parent.parent.canvas.insert(canvas_parent_index, self._slide_manager_parent.canvas)

        return data
Exemplo n.º 32
0
    def bitmap(self):
        # self.export_to_png('test.png')

        # remove cross
        self.canvas.after.clear()

        image_scale = 36 / self.width

        fbo = Fbo(size=(36, 27), with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            Scale(image_scale, -image_scale, image_scale)
            Translate(-self.x, -self.y - self.height, 0)

        fbo.add(self.canvas)
        fbo.draw()
        # fbo.texture.save('test_small.png', flipped=False)
        bm = np.fromstring(fbo.pixels, dtype=np.uint8).reshape(fbo.size[1], fbo.size[0], 4)
        fbo.remove(self.canvas)

        # return cross
        self.add_cross()

        return np.int64(np.all(bm[:, :, :3] == 0, axis=2))
Exemplo n.º 33
0
Arquivo: main.py Projeto: matham/ceed
    def get_root_pixels(self):
        """Returns all the pixels values of the widget containing the shapes,
        as well as the size of that widget.

        This is how you can save an image of whatever is currently displayed on
        screen.
        """
        widget = self.root.ids.display_canvas

        canvas_parent_index = widget.parent.canvas.indexof(widget.canvas)
        if canvas_parent_index > -1:
            widget.parent.canvas.remove(widget.canvas)

        fbo = Fbo(size=widget.size, with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Scale(1, -1, 1)
            Translate(0, -widget.height, 0)

        fbo.add(widget.canvas)
        fbo.draw()
        pixels = fbo.pixels
        fbo.remove(widget.canvas)

        if canvas_parent_index > -1:
            widget.parent.canvas.insert(canvas_parent_index, widget.canvas)
        return pixels, widget.size
Exemplo n.º 34
0
def advanced_gradient(border_color=(1, 1, 0), center_color=(1, 0, 0), size=(64, 64),fs=radial_grd_fs):

    fbo = Fbo(size=size)
    fbo.shader.fs = fs

    # use the shader on the entire surface
    fbo['border_color'] = map(float, border_color)
    fbo['center_color'] = map(float, center_color)
    with fbo:
        Color(1, 1, 1)
        Rectangle(size=size)
    fbo.draw()

    return fbo.texture
    def get_widget_pos_pixel(self, widget, positions):
        from kivy.graphics import Fbo, ClearColor, ClearBuffers

        canvas_parent_index = -2
        if widget.parent is not None:
            canvas_parent_index = widget.parent.canvas.indexof(widget.canvas)
            if canvas_parent_index > -1:
                widget.parent.canvas.remove(widget.canvas)

        w, h = int(widget.width), int(widget.height)
        fbo = Fbo(size=(w, h), with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()

        fbo.add(widget.canvas)
        fbo.draw()
        pixels = fbo.pixels
        fbo.remove(widget.canvas)

        if widget.parent is not None and canvas_parent_index > -1:
            widget.parent.canvas.insert(canvas_parent_index, widget.canvas)

        values = []
        for x, y in positions:
            x = int(x)
            y = int(y)
            i = y * w * 4 + x * 4
            values.append(tuple(pixels[i:i + 4]))

        return values
Exemplo n.º 36
0
    def setup_panda(self, *largs):
        self.msb = ModelShowbase()
        self.msb.camLens.setFov(52.0)
        self.msb.camLens.setNearFar(1.0, 10000.0)

        with self.canvas:
            self.fbo = Fbo(size=self.size, clear_color=(.3, .3, .3, .2))
            Color(1, 1, 1)
            self.viewport = Rectangle(pos=self.pos,
                                      size=self.size,
                                      texture=self.fbo.texture)
            Callback(self.draw_panda, reset_context=True)

        Clock.schedule_interval(self.update_panda, 1 / 60.)
Exemplo n.º 37
0
    def test_fbo_pixels(self):
        from kivy.graphics import Fbo, ClearColor, ClearBuffers, Ellipse

        fbo = Fbo(size=(512, 512))
        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Ellipse(pos=(100, 100), size=(100, 100))
        fbo.draw()
        data = fbo.pixels

        import pygame
        surface = pygame.image.fromstring(data, (512, 512), 'RGBA', True)
        pygame.image.save(surface, "results.png")
Exemplo n.º 38
0
    def __init__(self, **kwargs):
        self.mesh_data = MeshData()
        self.canvas = Canvas()
        with self.canvas:
            self.fbo = Fbo(size=(10, 10), compute_normal_mat=True)
            self.fbo.add_reload_observer(self.populate_fbo)
        with self.fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
        self.populate_fbo(self.fbo)

        super(GLWindow, self).__init__(**kwargs)

        Clock.schedule_interval(self.update_glsl, 1 / 60.)
Exemplo n.º 39
0
    def test_fbo_pixels(self):
        from kivy.graphics import Fbo, ClearColor, ClearBuffers, Ellipse

        fbo = Fbo(size=(512, 512))
        with fbo:
            ClearColor(0, 0, 0, 1)
            ClearBuffers()
            Ellipse(pos=(100, 100), size=(100, 100))
        fbo.draw()
        data = fbo.pixels

        import pygame
        surface = pygame.image.fromstring(data, (512, 512), 'RGBA', True)
        pygame.image.save(surface, "results.png")
Exemplo n.º 40
0
    def export_as_image(self, *args, **kwargs):
        '''Return an core :class:`~kivy.core.image.Image` of the actual
        widget.

        .. versionadded:: 1.11.0
        '''
        from kivy.core.image import Image
        scale = kwargs.get('scale', 1)

        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            if canvas_parent_index > -1:
                self.parent.canvas.remove(self.canvas)

        fbo = Fbo(size=(self.width * scale, self.height * scale),
                  with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            Scale(1, -1, 1)
            Scale(scale, scale, 1)
            Translate(-self.x, -self.y - self.height, 0)

        fbo.add(self.canvas)
        fbo.draw()
        img = Image(fbo.texture)
        fbo.remove(self.canvas)

        if self.parent is not None and canvas_parent_index > -1:
            self.parent.canvas.insert(canvas_parent_index, self.canvas)

        return img
Exemplo n.º 41
0
def insert_color_ellipse(state, texture_w, texture_h, texture_name, c_r, c_g, c_b):
        """
        TODO
        """
        tile_size = screen.get_tile_size(state)
        texture_w *= tile_size
        texture_h *= tile_size

        texture = Texture.create(size=(texture_w, texture_h), colorfmt='rgba')
        fbo = Fbo(size=(texture_w, texture_h), texture=texture)
        with fbo:
                Color(c_r, c_g, c_b)
                Ellipse(pos=(0, 0), size=(texture_w, texture_h))
        fbo.draw()
        insert(state, texture_name, texture)
Exemplo n.º 42
0
Arquivo: main.py Projeto: fresk/shs
    def _prepare_fbo(self, *args):
        # put all the current canvas into an FBO
        # then use the fbo texture into a Quad, for animating when disable

        # create the Fbo
        self.fbo = Fbo(size=(1, 1))
        with self.fbo.before:
            self.g_translate = Translate(self.x, self.y)
        self.orig_canvas = self.canvas
        self.fbo.add(self.canvas)

        # create a new Canvas
        self.canvas = Canvas()
        self.canvas.add(self.fbo)
        with self.canvas:
            Color(1, 1, 1)
            self.g_quad = Quad(texture=self.fbo.texture)

        # replace the canvas from the parent with the new one
        self.parent.canvas.remove(self.orig_canvas)
        self.parent.canvas.add(self.canvas)

        # ensure we'll be updated when we'll change position
        self.bind(pos=self._update_mesh, size=self._update_mesh, alpha_rotation=self._update_mesh)
        self._update_mesh()
Exemplo n.º 43
0
    def __init__(self, **kwargs):
        # Make sure opengl context exists
        EventLoop.ensure_window()

        self.canvas = RenderContext(use_parent_projection=True,
                                    use_parent_modelview=True)

        with self.canvas:
            self.fbo = Fbo(size=self.size)

        with self.fbo.before:
            PushMatrix()
        with self.fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            self._background_color = Color(*self.background_color)
            self.fbo_rectangle = Rectangle(size=self.size)
        with self.fbo.after:
            PopMatrix()

        super(EffectWidget, self).__init__(**kwargs)

        Clock.schedule_interval(self._update_glsl, 0)

        fbind = self.fbind
        fbo_setup = self.refresh_fbo_setup
        fbind('size', fbo_setup)
        fbind('effects', fbo_setup)
        fbind('background_color', self._refresh_background_color)

        self.refresh_fbo_setup()
        self._refresh_background_color()  # In case thi was changed in kwargs
Exemplo n.º 44
0
    def export_as_image(self, *args, **kwargs):
        '''Return an core :class:`~kivy.core.image.Image` of the actual
        widget.

        .. versionadded:: 1.11.0
        '''
        from kivy.core.image import Image
        scale = kwargs.get('scale', 1)

        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            if canvas_parent_index > -1:
                self.parent.canvas.remove(self.canvas)

        fbo = Fbo(size=(self.width * scale, self.height * scale),
                  with_stencilbuffer=True)

        with fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
            Scale(1, -1, 1)
            Scale(scale, scale, 1)
            Translate(-self.x, -self.y - self.height, 0)

        fbo.add(self.canvas)
        fbo.draw()
        img = Image(fbo.texture)
        fbo.remove(self.canvas)

        if self.parent is not None and canvas_parent_index > -1:
            self.parent.canvas.insert(canvas_parent_index, self.canvas)

        return img
Exemplo n.º 45
0
def toImage(self, bg_color=(1,1,1,0)):
    #create image widget with texture == to a snapshot of me
    from kivy.graphics import Translate, Fbo, ClearColor, ClearBuffers, Scale
    from kivy.core.image import Image as CoreImage

    if self.parent is not None:
        canvas_parent_index = self.parent.canvas.indexof(self.canvas)
        self.parent.canvas.remove(self.canvas)

    fbo = Fbo(size=self.size, with_stencilbuffer=True)

    with fbo:
        ClearColor(*bg_color)
        ClearBuffers()
        Scale(1, -1, 1)
        Translate(-self.x, -self.y - self.height, 0)

    fbo.add(self.canvas)
    fbo.draw()
    #EventLoop.idle()
    cim = CoreImage(fbo.texture, filename = '%s.png'%id(self))

    fbo.remove(self.canvas)

    if self.parent is not None:
        self.parent.canvas.insert(canvas_parent_index, self.canvas)

    return cim
Exemplo n.º 46
0
    def save_png(self, filename):
        if not self.done_draw: # Don't save a blank drawing.
            return False
        self.do_drawing = False
        ### Kivy 1.8.1 has an export_to_png function in the widget class. I'm not using 1.8.1 so I'm writing my own.
        ## Mostly copy-pasted from: https://github.com/kivy/kivy/blob/master/kivy/uix/widget.py (2014/06/16)
        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            self.parent.canvas.remove(self.canvas)
        fbo = Fbo(size=self.size_const)
        with fbo:
            ClearColor(0, 0, 0, 0) # I changed this from 0,0,0,1 to 0,0,0,0 so that I could have a transparent background.
            ClearBuffers()
            Translate(-self.draw_const[0], -self.draw_const[2], 0)

        fbo.add(self.canvas)
        fbo.draw()
        try:
            fbo.texture.save(filename)
            success = True
            kivy.logger.Logger.debug("PaintWidget: Saved file %s" % filename)
        except Exception as e:
            success = False
            kivy.logger.Logger.error("PaintWidget: Can't save file: %s" % filename)
            kivy.logger.Logger.exception(e)
        finally:
            fbo.remove(self.canvas)

            if self.parent is not None:
                self.parent.canvas.insert(canvas_parent_index, self.canvas)

            self.do_drawing = True
            return success
Exemplo n.º 47
0
def export_to_png(self, filename, *args):
    '''Saves an image of the widget and its children in png format at the
    specified filename. Works by removing the widget canvas from its
    parent, rendering to an :class:`~kivy.graphics.fbo.Fbo`, and calling
    :meth:`~kivy.graphics.texture.Texture.save`.
    '''

    if self.parent is not None:
        canvas_parent_index = self.parent.canvas.indexof(self.canvas)
        self.parent.canvas.remove(self.canvas)

    fbo = Fbo(size=self.size,  with_stencilbuffer=True)

    with fbo:
        ClearColor(0, 0, 0, 1)
        ClearBuffers()
        Translate(-self.x, -self.y, 0)

    fbo.add(self.canvas)
    fbo.draw()
    fbo.texture.save(filename, flipped=False)
    fbo.remove(self.canvas)

    if self.parent is not None:
        self.parent.canvas.insert(canvas_parent_index, self.canvas)

    return True
Exemplo n.º 48
0
    def export_to_png(self, filename, *args):
      

        if self.parent is not None:
            canvas_parent_index = self.parent.canvas.indexof(self.canvas)
            if canvas_parent_index > -1:
                self.parent.canvas.remove(self.canvas)

        fbo = Fbo(size=self.size, with_stencilbuffer=True)

        with fbo:
            ClearColor(1, 1, 1, 1)
            ClearBuffers()
            Scale(1, -1, 1)
            Translate(-self.x, -self.y - self.height, 0)

        fbo.add(self.canvas)
        fbo.draw()
        fbo.texture.save(filename, flipped=False)
        fbo.remove(self.canvas)

        if self.parent is not None and canvas_parent_index > -1:
            self.parent.canvas.insert(canvas_parent_index, self.canvas)

        return True
Exemplo n.º 49
0
 def setupVTK(self):
     Clock.schedule_interval(self.updateVTK, 1 / 1.)
     with self.canvas:
         self.fbo = Fbo(size=(512,512), clear_color=(.3, .3, .3, .8), push_viewport=True, with_depthbuffer=True)
         self.size = self.fbo.size
         Color(0, 0, 1)
         Rectangle(pos=self.pos, size=self.size, texture=self.fbo.texture)
         
         Callback(self.drawVTK, reset_context=True)
Exemplo n.º 50
0
class VTKWidget(Widget):
    
    def __init__(self, **kwargs):
        super(VTKWidget,self).__init__(**kwargs)
        self.setupVTK()
    
    def updateVTK(self, *largs):
        self.fbo.ask_update()
        self.canvas.ask_update()

    def setupVTK(self):
        Clock.schedule_interval(self.updateVTK, 1 / 1.)
        with self.canvas:
            self.fbo = Fbo(size=(512,512), clear_color=(.3, .3, .3, .8), push_viewport=True, with_depthbuffer=True)
            self.size = self.fbo.size
            Color(0, 0, 1)
            Rectangle(pos=self.pos, size=self.size, texture=self.fbo.texture)
            
            Callback(self.drawVTK, reset_context=True)
            
    def drawVTK(self, instr):
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)
        VTKClock.tick()
        glViewport(0,0,512,512)
        self.fbo.clear_buffer()
        
        #push GL state of Kivy
        glUseProgram(0)
        glPushAttrib(GL_ALL_ATTRIB_BITS)
        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        
        renWin.Render()

        #pop previous state of Kivy
        glMatrixMode(GL_MODELVIEW)
        glPopMatrix()
        glMatrixMode(GL_PROJECTION)
        glPopMatrix()
        glPopAttrib()
Exemplo n.º 51
0
def radial_gradient(border_color=(1, 1, 0), center_color=(1, 0, 0),
        size=(64, 64)):
    fbo = Fbo(size=size)
    fbo.shader.fs = '''
    $HEADER$
    uniform vec3 border_color;
    uniform vec3 center_color;
    void main (void) {
        float d = clamp(distance(tex_coord0, vec2(0.5, 0.5)), 0., 1.);
        gl_FragColor = vec4(mix(center_color, border_color, d), 1);
    }
    '''
 
    # use the shader on the entire surface
    fbo['border_color'] = [float(x) for x in  border_color]
    fbo['center_color'] = [float(x) for x in  center_color]
    with fbo:
        Color(1, 1, 1)
        Rectangle(size=size)
    fbo.draw()
    return fbo.texture
Exemplo n.º 52
0
    def setup_panda(self, *largs):
        self.msb = ModelShowbase()
        self.msb.camLens.setFov(52.0)
        self.msb.camLens.setNearFar(1.0, 10000.0)

        with self.canvas:
            self.fbo = Fbo(size=self.size, clear_color=(0.3, 0.3, 0.3, 0.2))
            Color(1, 1, 1)
            self.viewport = Rectangle(pos=self.pos, size=self.size, texture=self.fbo.texture)
            Callback(self.draw_panda, reset_context=True)

        Clock.schedule_interval(self.update_panda, 1 / 60.0)
Exemplo n.º 53
0
 def __init__(self, **kwargs):
     self.canvas = Canvas()
     with self.canvas:
         self.fbo = Fbo(size=self.size)
     self.fbo_thumb = Fbo(size=self.thumb_size)
     with self.fbo:
         Color(0, 0, 0)
         self.fbo_rect = Rectangle(size=self.size)
     self.texture = self.fbo.texture
     with self.fbo_thumb:
         Color(1, 1, 1)
         self.fbo_thumb_rect = Rectangle(size=self.thumb_size)
     super(FboCapture, self).__init__(**kwargs)
Exemplo n.º 54
0
    def _init_fbo(self):
        if self.fbo_pos is None:
            self.fbo_pos = self.pos
            self.fbo_size = self.size
            self.fbo_real_size = self.size
            self.fbo_scale = 1
        with self.canvas:
            #self.fbo = Fbo(size=self.fbo_size)
            self.fbo = Fbo(size=self.fbo_real_size)            
#            Rectangle(size=self.fbo_size, texture=self.fbo.texture, pos=self.fbo_pos)
            Rectangle(size=self.fbo_size, texture=self.fbo.texture, 
                      pos=(self.fbo_pos[0],
                           self.fbo_pos[1]))
Exemplo n.º 55
0
    def __init__(self, **kwargs):
        self.mesh_data = MeshData()
        self.canvas = Canvas()
        with self.canvas:
            self.fbo = Fbo(size=(10, 10), compute_normal_mat=True)
            self.fbo.add_reload_observer(self.populate_fbo)
        with self.fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()
        self.populate_fbo(self.fbo)

        super(GLWindow, self).__init__(**kwargs)

        Clock.schedule_interval(self.update_glsl, 1 / 60.)
Exemplo n.º 56
0
def create_texture(state, text, font_name):
        """
        TODO
        """
        font_def = state[IDX_STATE_TEXT][font_name]
        text_lines = text.split("\n")
        n_lines = len(text_lines)
        max_line_length = len(max(text_lines, key=len))
        texture_w = max_line_length * font_def[IDX_TEXT_WIDTH]
        texture_h = n_lines * font_def[IDX_TEXT_HEIGHT]
        texture = Texture.create(size=(texture_w, texture_h), colorfmt='rgba')
        fbo = Fbo(size=(texture_w, texture_h), texture=texture)
        for row in xrange(n_lines):
                cur_row = text_lines[row]
                for col in xrange(len(cur_row)):
                        char = cur_row[col]
                        char_texture = get_character_texture(state, font_name, char)
                        x_pos = col * font_def[IDX_TEXT_WIDTH]
                        y_pos = (n_lines - row - 1) * font_def[IDX_TEXT_HEIGHT]
                        with fbo:
                                Rectangle(pos=(x_pos, y_pos), size=(font_def[IDX_TEXT_WIDTH], font_def[IDX_TEXT_HEIGHT]), texture=char_texture)
                        fbo.draw()
        return texture
Exemplo n.º 57
0
    def init_camera(self):
        self._release_camera()
        self._android_camera = Camera.open(self._index)
        params = self._android_camera.getParameters()
        width, height = self._resolution
        params.setPreviewSize(width, height)
        params.setFocusMode('continuous-picture')
        self._android_camera.setParameters(params)
        # self._android_camera.setDisplayOrientation()
        self.fps = 30.

        pf = params.getPreviewFormat()
        assert(pf == ImageFormat.NV21)  # default format is NV21
        self._bufsize = int(ImageFormat.getBitsPerPixel(pf) / 8. *
                            width * height)

        self._camera_texture = Texture(width=width, height=height,
                                       target=GL_TEXTURE_EXTERNAL_OES,
                                       colorfmt='rgba')
        self._surface_texture = SurfaceTexture(int(self._camera_texture.id))
        self._android_camera.setPreviewTexture(self._surface_texture)

        self._fbo = Fbo(size=self._resolution)
        self._fbo['resolution'] = (float(width), float(height))
        self._fbo.shader.fs = '''
            #extension GL_OES_EGL_image_external : require
            #ifdef GL_ES
                precision highp float;
            #endif

            /* Outputs from the vertex shader */
            varying vec4 frag_color;
            varying vec2 tex_coord0;

            /* uniform texture samplers */
            uniform sampler2D texture0;
            uniform samplerExternalOES texture1;
            uniform vec2 resolution;

            void main()
            {
                vec2 coord = vec2(tex_coord0.y * (
                    resolution.y / resolution.x), 1. -tex_coord0.x);
                gl_FragColor = texture2D(texture1, tex_coord0);
            }
        '''
        with self._fbo:
            self._texture_cb = Callback(lambda instr:
                                        self._camera_texture.bind)
            Rectangle(size=self._resolution)
Exemplo n.º 58
0
def insert_combined(state, texture_size, texture_name, texture_list):
        """
        TODO
        """
        tile_size = screen.get_tile_size(state)
        texture_size *= tile_size

        if len(texture_list) == 0:
                raise YapygTextureDbException("insert_combined() called with empty list")
        elif len(texture_list) == 1:
                # Single texture, just load it and enter it with the
                # tile name as key to texture dict
                load(state, texture_name, texture_list[0])
        else:
                # Combine several textures into one
                texture = Texture.create(size=(texture_size, texture_size), colorfmt='rgba')
                for texture_filename in texture_list:
                        other_texture = Image(source=texture_filename).texture
                        fbo = Fbo(size=(texture_size, texture_size), texture=texture)
                        with fbo:
                                Color(1, 1, 1)
                                Rectangle(pos=(0, 0), size=other_texture.size, texture=other_texture)
                        fbo.draw()
                insert(state, texture_name, texture)