Example #1
0
    def apply_transform(self, trans, post_multiply=False, anchor=(0, 0)):
        '''
        Transforms the scatter by applying the "trans" transformation
        matrix (on top of its current transformation state). The resultant
        matrix can be found in the :attr:`~Scatter.transform` property.

        :Parameters:
            `trans`: :class:`~kivy.graphics.transformation.Matrix`.
                Transformation matix to be applied to the scatter widget.
            `anchor`: tuple, defaults to (0, 0).
                The point to use as the origin of the transformation
                (uses local widget space).
            `post_multiply`: bool, defaults to False.
                If True, the transform matrix is post multiplied
                (as if applied before the current transform).

        Usage example::

            from kivy.graphics.transformation import Matrix
            mat = Matrix().scale(3, 3, 3)
            scatter_instance.apply_transform(mat)

        '''
        t = Matrix().translate(anchor[0], anchor[1], 0)
        t = t.multiply(trans)
        t = t.multiply(Matrix().translate(-anchor[0], -anchor[1], 0))

        if post_multiply:
            self.transform = self.transform.multiply(t)
        else:
            self.transform = t.multiply(self.transform)
Example #2
0
 def look_at(self, v):
     m = Matrix()
     pos = self._position * -1
     m = m.translate(pos[0], pos[1], pos[2])
     self.modelview_matrix = m
     self._look_at = v
     self.update()
Example #3
0
    def apply_angle_scale_trans(self, angle, scale, trans, point=Vector(0, 0)):
        '''Update matrix transformation by adding new angle,
           scale and translate.

        :Parameters:
            `angle` : float
                Rotation angle to add
            `scale` : float
                Scaling value to add
            `trans` : Vector
                Vector translation to add
            `point` : Vector, default to (0, 0)
                Point to apply transformation
        '''
        old_scale = self.scale
        new_scale = old_scale * scale
        if new_scale < self.scale_min or old_scale > self.scale_max:
            scale = 1.

        t = Matrix().translate(
            trans[0] * self.do_translation_x,
            trans[1] * self.do_translation_y,
            0)
        t = t.multiply(Matrix().translate(point[0], point[1], 0))
        t = t.multiply(Matrix().rotate(angle, 0, 0, 1))
        t = t.multiply(Matrix().scale(scale, scale, scale))
        t = t.multiply(Matrix().translate(-point[0], -point[1], 0))
        self.apply_transform(t)
Example #4
0
    def update_viewport(self):
        from kivy.graphics.opengl import glViewport
        from kivy.graphics.transformation import Matrix

        width, height = self.system_size
        w2 = width / 2.
        h2 = height / 2.

        # prepare the viewport
        glViewport(0, 0, width, height)
        projection_mat = Matrix()
        projection_mat.view_clip(0.0, width, 0.0, height, -1.0, 1.0, 0)
        self.render_context['projection_mat'] = projection_mat

        # use the rotated size.
        # XXX FIXME fix rotation
        '''
        width, height = self.size
        w2 = width / 2.
        h2 = height / 2.
        glTranslatef(-w2, -h2, -500)

        # set the model view
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslatef(w2, h2, 0)
        glRotatef(self._rotation, 0, 0, 1)
        glTranslatef(-w2, -h2, 0)
        '''

        self.update_childsize()
Example #5
0
	def updateScene(self, fb, *largs):
		# smooth camera
		cam = fb.scene.camera
		cam._rotation = helpers.mix(cam._rotation, cam._rotationTarget, 0.9)
		cam._distance = helpers.mix(cam._distance, cam._distanceTarget, 0.9)

		# compute camera pos
		cam.position[0] = cos(cam._rotation[2])*cos(cam._rotation[1])*cam._distance
		cam.position[2] = sin(cam._rotation[2])*cos(cam._rotation[1])*cam._distance
		cam.position[1] = sin(cam._rotation[1])*cam._distance

		# setup camera
		fov = cam.fov
		pos = cam.position
		target = fb.scene.camera.target
		asp = self.width / float(self.height)
		proj = Matrix()
		proj.perspective(fov, asp, 0.1, 100)
		modelView = Matrix()
		modelView = modelView.look_at(pos[0],pos[2],pos[1], target[0], target[2], target[1], 0,0,1)

		self.canvas['modelview_mat'] = modelView
		self.canvas['projection_mat'] = proj
		self.canvas['diffuse_light'] = (1.0, 1.0, 0.8)
		self.canvas['ambient_light'] = (0.1, 0.1, 0.1)

		self.mesh1['modelview_mat'] = modelView
		self.mesh1['projection_mat'] = proj
		self.mesh1['diffuse_light'] = (1.0, 2.0, 0.8)
		self.mesh1['ambient_light'] = (0.1, 0.1, 0.1)

		self.mesh2['modelview_mat'] = modelView
		self.mesh2['projection_mat'] = proj
		self.mesh2['diffuse_light'] = (2.0, 1.0, 0.8)
		self.mesh2['ambient_light'] = (0.1, 0.1, 0.1)
Example #6
0
 def look_at(self, *v):
     if len(v) == 1:
         v = v[0]
     m = Matrix()
     pos = self._position * -1
     m = m.look_at(pos[0], pos[1], pos[2], v[0], v[1], v[2], self.up[0], self.up[1], self.up[2])
     self.modelview_matrix = m
     self._look_at = v
     self.update()
Example #7
0
 def update_glsl(self, *largs):
     asp = self.width / float(self.height)
     asp = asp*0.3
     proj = Matrix()
     mat = Matrix()
     mat = mat.look_at(0, 0, self.camera_translate[2], 0, 0, -3, 0, 1, 0)
     proj = proj.view_clip(-asp, asp, -.3, .3, 1, 100, 1)
     
     self.canvas['projection_mat'] = proj
     self.canvas['modelview_mat'] = mat
Example #8
0
    def update_glsl(self, *largs):
        width = self.width if self.width > 1 else 100
        height = self.height if self.height > 1 else 100
        asp = width / float(height)
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 600, 1)
        proj = Matrix()
        proj.perspective(self.perspective_value, asp, 1, 1000)

        matrix_camera = Matrix().identity()
        matrix_camera.look_at(0, 100, 300, 100, 0, -100, 0, 1, 0)
        self.canvas['projection_mat'] = proj
        self.canvas['diffuse_light'] = (0.0, 1.0, 0.0)
        self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
        if self.shadow:
            self.canvas['texture1'] = 1
            self.canvas["enabled_shadow"] = 1.0
        else:

            self.canvas["enabled_shadow"] = 0.0
            self.canvas["texture1"] = 0

        depthProjectionMatrix = Matrix().view_clip(-100 * self.shadow_threshold, 100 * self.shadow_threshold,
                                                   -100 * self.shadow_threshold, 100 * self.shadow_threshold,
                                                   -100 * self.shadow_threshold, 200 * self.shadow_threshold * 2, 0)
        depthViewMatrix = Matrix().look_at(-0.5, -50, -100, 0, 0, 0, 0, 1, 0)
        depthModelMatrix = Matrix().identity()
        depthMVP = depthProjectionMatrix.multiply(depthViewMatrix).multiply(depthModelMatrix)
        self.canvas['depthMVP'] = depthMVP
        self.canvas['cond'] = (0.0, 0.7)
        self.canvas['val_sin'] = (self.alpha, 0.0)

        if self.shadow:
            self.update_fbo(largs[0])
Example #9
0
 def update_glsl(self, dt):
     from kivy.core.window import Window
     g = self.params.get
     w, h = Window.system_size
     projection_mat = Matrix()
     #projection_mat.view_clip(0.0, w, 0.0, h, 10.0, 1000.0, 1)
     projection_mat.perspective(g('fovy', 45.), g('aspect', 1), g('zNear', 10), g('zFar', 1000))
     #projection_mat.view_clip(0.0, w, 0.0, h, -1, 1, 0)
     modelview_mat = Matrix().look_at(0, 200, -200, self.targetx, self.targety, 0, 0, 1, 0)
     self.canvas['projection_mat'] = projection_mat
     self.canvas['modelview_mat'] = modelview_mat
Example #10
0
    def get_look_at(self, x, y, z, azi, ele):
        dx = - np.sin(azi) * np.cos(ele)
        dy = np.sin(ele)
        dz = - np.cos(azi) * np.cos(ele)

        # Not sure why up has to just be up...
        upx, upy, upz = (0, 1, 0)

        mat = Matrix()
        mat = mat.look_at(x, y, z,
                          x + dx, y + dy, z + dz,
                          upx, upy, upz)
        return mat
Example #11
0
    def get_window_matrix(self, x=0, y=0):
        '''Calculate the transformation matrix to convert between window and
        widget coordinates.

        :Parameters:
            `x`: float, defaults to 0
                Translates the matrix on the x axis.
            `y`: float, defaults to 0
                Translates the matrix on the y axis.
        '''
        m = Matrix()
        m.translate(x, y, 0)
        m = self._apply_transform(m)
        return m
Example #12
0
 def render(self, node, matrix, color_transform):
     self._display.canvas.add(PushMatrix())
     self._display.canvas.add(Color(*color_transform.c[:4]))
     matrix_instruction = MatrixInstruction()
     dmatrix = KivyMatrix()
     dmatrix.set(flat=[
         matrix.scale_x, -matrix.skew_1, 0, 0, matrix.skew_0,
         -matrix.scale_y, 0, 0, 0, 0, 1, 0, matrix.translate_x,
         -matrix.translate_y, 0, 1
     ])
     matrix_instruction.matrix = dmatrix
     self._display.canvas.add(matrix_instruction)
     self._display.canvas.add(node)
     self._display.canvas.add(Color(1, 1, 1, 1))
     self._display.canvas.add(PopMatrix())
Example #13
0
    def update_viewport(self):
        from kivy.graphics.opengl import glViewport
        from kivy.graphics.transformation import Matrix
        from math import radians

        w, h = self.system_size
        if self._density != 1:
            w, h = self.size

        smode = self.softinput_mode
        target = self._system_keyboard.target
        targettop = target.to_window(0, target.y)[1] if target else 0
        kheight = self.keyboard_height

        w2, h2 = w / 2., h / 2.
        r = radians(self.rotation)

        x, y = 0, 0
        _h = h
        if smode == 'pan':
            y = kheight
        elif smode == 'below_target':
            y = 0 if kheight < targettop else (kheight - targettop) + dp(9)
        if smode == 'scale':
            _h -= kheight

        # prepare the viewport
        glViewport(x, y, w, _h)

        # do projection matrix
        projection_mat = Matrix()
        projection_mat.view_clip(0.0, w, 0.0, h, -1.0, 1.0, 0)
        self.render_context['projection_mat'] = projection_mat

        # do modelview matrix
        modelview_mat = Matrix().translate(w2, h2, 0)
        modelview_mat = modelview_mat.multiply(Matrix().rotate(r, 0, 0, 1))

        w, h = self.size
        w2, h2 = w / 2., h / 2.
        modelview_mat = modelview_mat.multiply(Matrix().translate(-w2, -h2, 0))
        self.render_context['modelview_mat'] = modelview_mat

        # redraw canvas
        self.canvas.ask_update()

        # and update childs
        self.update_childsize()
    def initialise_canvas(self, size):
        self.matrix = Matrix()

        with self.canvas:
            self.fbo = Fbo(size=size)
            Color(1, 1, 1, 1)
            self.bg = Rectangle(size=self.size,
                                pos=self.pos,
                                texture=self.fbo.texture)
            self.canvas_created = True
        with self.fbo:
            self.matrix_instruction = MatrixInstruction()
            self.matrix_instruction.matrix = self.matrix

        self.fbo.add(self.transition_group)
        self.fbo.add(self.state_group)
Example #15
0
 def rot_down(self, *args):
     asp = self.width / float(self.height)
     proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
     self.canvas['projection_mat'] = proj
     self.canvas['diffuse_light'] = (1.0, 1.0, 0.8)
     self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
     self.rot_y.angle -= 1
Example #16
0
 def check_values_and_draw(self):
     if float(self.ids.TF7.text) + float(self.ids.TF14.text) + float(self.ids.TF21.text) + \
             float(self.ids.TF28.text) != 1:
         self.dialog = MDDialog(
             text=
             "Сумма вероятностей (в столбике \'p\') должна равняться 1.00",
             size_hint=(0.4, 0.3),
             buttons=[
                 MDFlatButton(text='OK', on_release=self.dialog_close)
             ])
         self.dialog.open()
     elif sum([
             float(TF.text) for TF in self.text_fields
             if int(TF.id[2:]) % 7 != 0
     ]) == 0:
         self.dialog = MDDialog(
             text="Все строки данных не мог быть равны нулю!",
             size_hint=(0.4, 0.3),
             buttons=[
                 MDFlatButton(text='OK', on_release=self.dialog_close)
             ])
         self.dialog.open()
     else:
         # Переключаемся на экран с холстом, возвращаем ScatterLayout
         # в изначальное положение и рисуем новую картинку (рисуем с помощью Clock, чтобы Scatter успел прогрузиться)
         self.ids.bottom_nav_barnsley.switch_tab('screen 3')
         trans = Matrix().scale(1, 1, 1)
         self.ids['draw_SL'].transform = trans
         Clock.schedule_once(self.drawing_fern)
    def apply_zoom(self, zoom, touch):
        self.apply_transform(Matrix().scale(zoom, zoom, zoom),
                             post_multiply=True,
                             anchor=self.to_local(*touch.pos))
        width, height = self._map_size

        bottom = height * self.scale / 2
        top = bottom - (height * self.scale - self.height)
        left = width * self.scale / 2
        right = left - (width * self.scale - self.width)

        if height * self.scale > self.height:
            if top > self.center_y:
                self.center_y = top
            elif self.center_y > bottom:
                self.center_y = bottom
        else:
            self.center_y = (top + bottom) / 2

        if width * self.scale > self.width:
            if left < self.center_x:
                self.center_x = left
            elif self.center_x < right:
                self.center_x = right
        else:
            self.center_x = (left + right) / 2
Example #18
0
 def _update_glsl(self, *_):
     p = self.parent.parent
     asp = float(p.width) / p.height * p.size_hint_y / p.size_hint_x
     proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
     self.canvas['projection_mat'] = proj
     self.canvas['diffuse_light'] = (1.0, 1.0, 0.8)
     self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
Example #19
0
    def __init__(self, **kwargs):
        super(MainWindow, self).__init__(**kwargs)

        from kivy.graphics.transformation import Matrix
        mat = Matrix().scale(3, 3, 3)
        self.scat1.apply_transform(mat)
        print "Transform applied"
Example #20
0
 def __init__(self, app, **kwargs):
     super(OctPanel, self).__init__(**kwargs)
     self.app = app
     self.layeranno = []
     self.editmode = EDITOFF
     self.sx = app.ratio
     self.apply_transform(Matrix().scale(self.sx, 1, 1))
Example #21
0
    def SetValueSub(self, fRad: float) -> None:
        """ Sets the value """
        if self.iLeftBoundaryAngle != self.iRightBoundaryAngle:
            iCheckAngle: int = int(degrees(self.fTotalAngle + fRad) * -1)
            # print iCheckAngle,' ',self.iLeftBoundaryAngle,' ',self.iRightBoundaryAngle
            if self.iRightBoundaryAngle > 0:
                if iCheckAngle > self.iRightBoundaryAngle:
                    return
            else:
                if iCheckAngle < self.iRightBoundaryAngle:
                    return
            if self.iLeftBoundaryAngle < 0:
                if iCheckAngle < self.iLeftBoundaryAngle:
                    return
            else:
                if iCheckAngle > self.iLeftBoundaryAngle:
                    return

        if fRad > 0.0:
            self.uDirection = u'left'
        else:
            self.uDirection = u'right'
        self.fTotalAngle += fRad
        self.iAngle = int(degrees(self.fTotalAngle)) * -1
        anchor = (self.xx + self.width / 2, self.yy + self.height / 2)
        '''
        print 'Angle:',self.fTotalAngle
        print 'Angle:', int(self.fTotalAngle*-57.5)
        print 'Angle:', degrees(self.fTotalAngle)*-1
        self.iAngle=int(degrees(self.fTotalAngle)*-1)
        print 'Angle:',self.iAngle
        '''
        self.apply_transform(Matrix().rotate(fRad, 0, 0, 1), anchor=anchor)
Example #22
0
 def on_orientation(self, *args):
     # rotate anchored on window center
     rot = self.orientation - self.scatter._get_rotation()
     self.scatter.apply_transform(Matrix().rotate((np.pi / 180) * rot, 0, 0,
                                                  1),
                                  anchor=Metrics.get('origin'))
     self.update_state()
Example #23
0
 def update_glsl(self, *largs):
     asp = self.width / float(self.height)
     proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
     #proj = Matrix().perspective(90, asp, 0, 100)
     self.canvas['projection_mat'] = proj
     self.canvas['diffuse_light'] = (0.0, 1.0, 0.8)
     self.canvas['ambient_light'] = (0.1, 0.6, 0.1)
Example #24
0
 def zoom(self, value):
     new_scale = self.scale + value
     if 0.1 <= new_scale <= 1.5:
         rescale = new_scale * 1.0 / self.scale
         self.apply_transform(Matrix().scale(rescale, rescale, rescale),
                              post_multiply=True,
                              anchor=self.to_local(*self.hex_layout.origin.tup))  # == window center
Example #25
0
 def scale_at(self, scale, x, y):
     scatter = self._scatter
     scale = clamp(scale, scatter.scale_min, scatter.scale_max)
     rescale = scale * 1.0 / scatter.scale
     scatter.apply_transform(Matrix().scale(rescale, rescale, rescale),
                             post_multiply=True,
                             anchor=scatter.to_local(x, y))
Example #26
0
    def on_touch_move(self, touch):
        ud = touch.ud

        if not 'tank_touch' in ud:
            return False

        if 'rotation_mode' in ud:
            # if the current touch is already in the 'rotate' mode, rotate the tower.
            dx = touch.x - self.center_x
            dy = touch.y - self.center_y
            angle = boundary(atan2(dy, dx) * 360 / 2 / pi, -60, 60)

            angle_change = self.tank_tower_scatter.rotation - angle
            rotation_matrix = Matrix().rotate(-radians(angle_change), 0, 0, 1)
            self.tank_tower_scatter.apply_transform(rotation_matrix,
                                                    post_multiply=True,
                                                    anchor=(105, 15))

        elif touch.x > self.right:
            # if the finger moved too far to the right go into rotation mode
            ud['rotation_mode'] = True

        else:
            # if the user wants only to drag the tank up and down, let him do it!
            self.y += touch.dy
            pass
Example #27
0
 def _set_pos(self, pos):
     _pos = self.bbox[0]
     if pos == _pos:
         return
     t = Vector(*pos) - _pos
     trans = Matrix().translate(t.x, t.y, 0)
     self.apply_transform(trans)
Example #28
0
    def on_press(self):
        # Setup the scatter layout to show in the popup
        scatter = Scatter(do_rotation=False,
                          size_int=(300, 300),
                          scale_min=1.0,
                          scale_max=10.0)

        image_source = join(globals_.photo_path, 'thumbs',
                            basename(self.source))

        image = AsyncImage(source=image_source)
        scatter.add_widget(image)
        # Resize the scatter object
        multiplier = 6
        mat = Matrix().scale(multiplier, multiplier, multiplier)
        scatter.apply_transform(mat)

        popup = Popup(title=basename(self.source),
                      content=scatter,
                      size_hint=(0.8, 1),
                      pos_hint={
                          'x': 0.0,
                          'y': 0.0
                      })
        popup.open()
Example #29
0
 def update_glsl(self, *largs):
     asp = self.width / float(self.height)
     proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
     self.canvas['projection_mat'] = proj
     self.canvas['diffuse_light'] = (1.0, 1.0, 0.8)
     self.canvas['ambient_light'] = (0.1, 0.1, 0.1)
     self.rot.angle += 1
Example #30
0
    def add_screen(self, screen):
        self.screen_in.pos = self.screen_out.pos
        self.screen_in.size = self.screen_out.size
        self.manager.real_remove_widget(self.screen_out)

        self.fbo_in = self.make_screen_fbo(self.screen_in)
        self.fbo_out = self.make_screen_fbo(self.screen_out)
        self.manager.canvas.add(self.fbo_in)
        self.manager.canvas.add(self.fbo_out)

        screen_rotation = Config.getfloat('graphics', 'rotation')
        pos = (0, 1)
        if screen_rotation == 90:
            pos = (0, 0)
        elif screen_rotation == 180:
            pos = (-1, 0)
        elif screen_rotation == 270:
            pos = (-1, 1)

        self.render_ctx = RenderContext(fs=self.fs, vs=self.vs)
        with self.render_ctx:
            BindTexture(texture=self.fbo_out.texture, index=1)
            BindTexture(texture=self.fbo_in.texture, index=2)
            Rotate(screen_rotation, 0, 0, 1)
            Rectangle(size=(1, -1), pos=pos)
        self.render_ctx['projection_mat'] = Matrix().\
            view_clip(0, 1, 0, 1, 0, 1, 0)
        self.render_ctx['tex_out'] = 1
        self.render_ctx['tex_in'] = 2
        self.manager.canvas.add(self.render_ctx)
Example #31
0
    def __init__(self, *args, **kwargs):
        self.render_context = RenderContext()
        super(RvitWidget, self).__init__(**kwargs)
        self.top_buttons = BoxLayout(orientation='horizontal',
                                     size_hint=(1.0, None),
                                     size=(0, 20),
                                     pos_hint={'right': 1.0,
                                               'top': 1.0},)
        self.title_label = Label()
        self.top_buttons.add_widget(self.title_label)

        self.configurable_properties = {}

        if 'inspect' in dir(self):
            self.inspect_button = Button(text='inspect',
                                         on_press=lambda x: self.inspect(),
                                         background_color=rvit.core.WHITE,
                                         pos_hint={'x': 0.0, 'top': 1.0})

            self.top_buttons.add_widget(self.inspect_button)

        self.disable_button = ToggleButton(size_hint=(None, None),
                                           background_color=rvit.core.RED,
                                           size=(20, 20),
                                           state='down',
                                           )

        def enabled_state_changed(inst, value):
            self.enabled = value == 'down'
        self.enabled = True
        self.disable_button.bind(state=enabled_state_changed)
        self.top_buttons.add_widget(self.disable_button)

        self.add_widget(self.top_buttons)

        self.render_context['modelview_mat'] = Matrix().identity()
        self.render_context['projection_mat'] = Matrix().identity()
        self.render_context['window_size'] = [float(Window.width), float(Window.height)]
        self.canvas.before.add(self.render_context)

        self.update_event = None
        # self.update_interval.dispatch()
        # self.on_show_controls

        prop = self.property('update_interval')
        # dispatch this property on the button instance
        prop.dispatch(self)
    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        '''
        
        Called when a button is pressed.
        
        '''
        scaleFactor = .03
        anchor = (0, 0)

        if keycode[1] == self.data.config.get('Ground Control Settings',
                                              'zoomIn'):
            mat = Matrix().scale(1 - scaleFactor, 1 - scaleFactor, 1)
            self.scatterInstance.apply_transform(mat, anchor)
        if keycode[1] == self.data.config.get('Ground Control Settings',
                                              'zoomOut'):
            mat = Matrix().scale(1 + scaleFactor, 1 + scaleFactor, 1)
            self.scatterInstance.apply_transform(mat, anchor)
Example #33
0
 def on_center_map(self, *args):
     """
     Restore the track map to the default position/zoom/rotation
     """
     scatter = self.ids.scatter
     scatter.scale = 1
     scatter.rotation = 0
     scatter.transform = Matrix().translate(self.pos[0], self.pos[1], 0)
Example #34
0
 def __init__(self):
     super().__init__()
     self.canvas = RenderContext()
     self.canvas.shader.source = 'hello_cube.glsl'
     ff = ((b'my_vertex_position', 3, 'float'), )
     vv = (0, 0, 0, 1., 0, 0, 1., 1., 0, 0, 1., 0, 0, 0, 1., 1., 0, 1., 1.,
           1., 1., 0, 1., 1.)
     ii = (0, 1, 1, 2, 2, 3, 3, 0, 0, 4, 1, 5, 2, 6, 3, 7, 4, 5, 5, 6, 6, 7,
           7, 4)
     with self.canvas:
         Mesh(fmt=ff, vertices=vv, indices=ii, mode='lines')
     self.canvas['center_the_cube'] = Matrix().translate(-.5, -.5, -.5)
     self.canvas['my_view'] = Matrix().look_at(3, 3, 2, 0, 0, 0, 0, 0, 1)
     self.canvas['my_proj'] = Matrix()
     aspect = Window.size[0] / Window.size[1]
     self.canvas['my_proj'].perspective(30, aspect, .1, 100)
     Clock.schedule_interval(self.increase_angle, 1 / 60)
    def transform_with_touch(self, touch):
        super().transform_with_touch(touch)
        dx = (touch.x - self._last_touch_pos[touch][0])
        dy = (touch.y - self._last_touch_pos[touch][1])
        dx = dx / self.translation_touches
        dy = dy / self.translation_touches

        width, height = self._map_size
        left = width * self.scale / 2
        right = left - (width * self.scale - self.width)
        bottom = height * self.scale / 2
        top = bottom - (height * self.scale - self.height)

        if right < self.center_x + dx < left:
            self.apply_transform(Matrix().translate(dx, 0, 0))
        if top < self.center_y + dy < bottom:
            self.apply_transform(Matrix().translate(0, dy, 0))
    def pan(self, delta):
        self.matrix = self.matrix.multiply(Matrix().translate(
            delta[0], delta[1], 0))

        self.fbo.bind()
        self.fbo.clear_buffer()
        self.matrix_instruction.matrix = self.matrix
        self.fbo.release()
Example #37
0
    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        '''
        
        Called when a button is pressed.
        
        '''
        scaleFactor = .03
        anchor = (0,0)
        
#         print 'gcodeCanvas',keycode, text, modifiers  # handy for exploring keyboard input
        
        if keycode[1] == self.data.config.get('Ground Control Settings', 'zoomIn'):
            mat = Matrix().scale(1-scaleFactor, 1-scaleFactor, 1)
            self.scatterInstance.apply_transform(mat, anchor)
            return True # we handled this key - don't pass to other callbacks
        elif keycode[1] == self.data.config.get('Ground Control Settings', 'zoomOut'):
            mat = Matrix().scale(1+scaleFactor, 1+scaleFactor, 1)
            self.scatterInstance.apply_transform(mat, anchor)
            return True # we handled this key - don't pass to other callbacks
        elif keycode[1] == self.data.config.get('Ground Control Settings', 'runKey'):
            self.parent.startRun() # "click" the 'Run' button
            return True # we handled this key - don't pass to other callbacks
        elif keycode[1] == self.data.config.get('Ground Control Settings', 'pauseKey'):
            self.parent.pause() # "click" the 'Pause' button
            return True # we handled this key - don't pass to other callbacks
        elif keycode[1] == self.data.config.get('Ground Control Settings', 'stopKey'):
            self.parent.stopRun() # "click" the 'Stop' button
            return True # we handled this key - don't pass to other callbacks
#         elif keycode[1] == self.data.config.get('Ground Control Settings', 'fakeServo_Off'):
#             if self.data.config.get('Ground Control Settings', 'fsModeAllowed') == "Allowed":
#                 if 'ctrl' in modifiers or 'alt' in modifiers or 'meta' in modifiers:
#                     self.data.gcode_queue.put("B99 ON \n")
#                 else:
#                     self.data.gcode_queue.put("B99 OFF \n")
#                 return True # we handled this key - don't pass to other callbacks
#             else:
#                 return False # we didn't handle this key - let next callback handle it
        elif keycode[1] == self.data.config.get('Ground Control Settings', 'fakeServo_Off'):
            if 'ctrl' in modifiers or 'alt' in modifiers or 'meta' in modifiers:
                if self.data.config.get('Ground Control Settings', 'fsModeAllowed') == "Allowed":
                    self.data.gcode_queue.put("B99 ON \n")
            else:
                self.data.gcode_queue.put("B99 OFF \n")
            return True # we handled this key - don't pass to other callbacks
        else:
                return False # we didn't handle this key - let next callback handle it
Example #38
0
 def moveRight(self):
     try:
         self.scatter.apply_transform(Matrix().translate(x=-100 /
                                                         self.scatter.scale,
                                                         y=0,
                                                         z=0))
     except Exception as e:
         handleCrash(e)
Example #39
0
 def zoomZero(self):
     try:
         zeroScale = self.odd.height / self.scatter.height
         oldScale = self.scatter.scale
         self.scatter.transform = Matrix()
         self.scatter.scale = zeroScale
     except Exception as e:
         handleCrash(e)
Example #40
0
 def apply_angle_scale_trans(self, angle, scale, trans, point):
     #FIXME: this does not work as expected
     newscale = self.scale * scale
     if newscale < self.minscale or newscale > self.maxscale:
         newscale = 1
     tf = Matrix().rotate(angle, 1, 1,
                          1).scale(scale, scale,
                                   1).translate(trans.x, trans.y, 0)
     super(MapViewerPlane, self).apply_transform(tf)
Example #41
0
 def check_trans(self, matrix):
     pos_matrix = Matrix().translate(self.pos[0], self.pos[1], 0)
     pos = matrix.multiply(pos_matrix).get()[12:14]
     if pos[0] > 0 or pos[1] > 0:
         return False
     elif (pos[0] + self.width * self.scale < Window.size[0]
           or pos[1] + self.height * self.scale < Window.size[1]):
         return False
     return True
Example #42
0
 def __init__(self, angle, axis, render_context):
     # It shold be way to get current context
     # but in simple case we may just pass it to constructor 
    self.context = render_context
    self._axis = axis
    self._angle = angle
    self.renderer = render_context
    self.prev_mvm = Matrix()
    self.matrix = Matrix()
    Callback(self._rotate) # here we perform rotation
Example #43
0
    def update_camera(self, pos, angle):
        self.eye_pos = pos
        self.eye_angle = angle
        x, y, z = pos
        azi, ele = angle
        asp = self.width / float(self.height)
        mat = self.get_look_at(x, y, z, azi, ele)

        proj = Matrix()
        proj.perspective(30, asp, 1, 100)

        self.canvas['projection_mat'] = proj
        self.canvas['modelview_mat'] = mat

        self.fixed_x.x = x
        self.fixed_y.y = y
        self.fixed_z.z = z
        self.fixed_azi.angle = azi * 180/np.pi
        self.fixed_ele.angle = ele * 180/np.pi
Example #44
0
    def update_glsl(self, *largs):
        global no_width_error_enable
        if self.player_velocity[0] != 0:
            self.camera_translate_instruction.x += self.player_velocity[0]
        if self.player_velocity[1] != 0:
            self.camera_translate_instruction.y += self.player_velocity[1]
        if self.player_velocity[2] != 0:
            self.camera_translate_instruction.z += self.player_velocity[2]
        if self.height > 0:
            asp = self.width / float(self.height)
        else:
            if no_width_error_enable:
                print("[ TestingKivy3D ] ERROR in update_glsl: Failed to get width.")
                no_width_error_enable = False

        clip_top = 0.06  # NOTE: 0.03 is ~1.72 degrees, if that matters
        # formerly field_of_view_factor
        # was changed to .03 when projection_near was changed from 1 to .1
        # was .3 when projection_near was 1

        clip_right = asp*clip_top  # formerly overwrote asp
        self.projection_near = 0.1
        projectionMatrix = Matrix().view_clip(-clip_right, clip_right, -1*clip_top, clip_top, self.projection_near, 100, 1)  # last params: far, perspective
        #projectionMatrix = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)  # last params: far, perspective
        modelViewMatrix = Matrix()
        modelViewMatrix.translate(self.camera_translate_instruction.x, self.camera_translate_instruction.y, self.camera_translate_instruction.z)
        if (self.camera_translate_instruction.x != self.look_point[0] or
            self.camera_translate_instruction.y != self.look_point[1] or
            self.camera_translate_instruction.z != self.look_point[2]):
            try:
                modelViewMatrix = modelViewMatrix.look_at(self.camera_translate_instruction.x, self.camera_translate_instruction.y, self.camera_translate_instruction.z, self.look_point[0], self.look_point[1], self.look_point[2], 0, 1, 0)  # 0,1,0 is y-up orientation
            except:
                print("[ TestingKivy3D ] Could not finish modelViewMatrix.look_at:")
        else:
            print("[ TestingKivy3D ] Can't run modelViewMatrix.look_at since camera is at look_point")

        self.gl_widget.canvas['projection_mat'] = projectionMatrix
        self.gl_widget.canvas['modelview_mat'] = modelViewMatrix
        self.gl_widget.canvas["camera_world_pos"] = [self.camera_translate_instruction.x, self.camera_translate_instruction.y, self.camera_translate_instruction.z]
        self.gl_widget.canvas['ambient_light'] = (0.1, 0.1, 0.1)
Example #45
0
    def update_viewport(self):
        from kivy.graphics.opengl import glViewport
        from kivy.graphics.transformation import Matrix
        from math import radians

        w, h = self.system_size
        w2, h2 = w / 2., h / 2.
        r = radians(self.rotation)

        # prepare the viewport
        glViewport(0, 0, w, h)

        # do projection matrix
        projection_mat = Matrix()
        projection_mat.view_clip(0.0, w, 0.0, h, -1.0, 1.0, 0)
        self.render_context['projection_mat'] = projection_mat

        # do modelview matrix
        modelview_mat = Matrix().translate(w2, h2, 0)
        modelview_mat = modelview_mat.multiply(Matrix().rotate(r, 0, 0, 1))

        w, h = self.size
        w2, h2 = w / 2., h / 2.
        modelview_mat = modelview_mat.multiply(Matrix().translate(-w2, -h2, 0))
        self.render_context['modelview_mat'] = modelview_mat

        # redraw canvas
        self.canvas.ask_update()

        # and update childs
        self.update_childsize()
Example #46
0
    def apply_transform(self, trans, post_multiply=False, anchor=(0, 0)):
        '''
        Transforms scatter by trans (on top of its current transformation state)

        :Parameters:
            `trans`: transformation matrix from transformation lib.
                Transformation to be applied to the scatter widget
            `anchor`: tuple, default to (0, 0)
                The point to use as the origin of the transformation
                (uses local widget space)
            `post_multiply`: bool, default to False
                If true the transform matrix is post multiplied
                (as if applied before the current transform)
        '''
        t = Matrix().translate(anchor[0], anchor[1], 0)
        t = t.multiply(trans)
        t = t.multiply(Matrix().translate(-anchor[0], -anchor[1], 0))

        if post_multiply:
            self.transform = self.transform.multiply(t)
        else:
            self.transform = t.multiply(self.transform)
Example #47
0
    def update_fbo(self, time):
        width = self.width if self.width > 1 else 100
        height = self.height if self.height > 1 else 100
        asp = (width / float(height))
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 600, 1)
        proj = Matrix()
        proj.perspective(self.perspective_value, asp, 1, 1000)

        lightInvDir = (0.5, 2, 2)
        depthProjectionMatrix = Matrix().view_clip(-100 * self.shadow_threshold, 100 * self.shadow_threshold,
                                                   -100 * self.shadow_threshold, 100 * self.shadow_threshold,
                                                   -100 * self.shadow_threshold, 200 * self.shadow_threshold * 2, 0)
        depthViewMatrix = Matrix().look_at(-0.5, -50, -100, 0, 0, 0, 0, 1, 0)
        depthModelMatrix = Matrix().identity()
        depthMVP = depthProjectionMatrix.multiply(depthViewMatrix).multiply(depthModelMatrix)

        self.fbo['projection_mat'] = proj
        self.fbo['depthMVP'] = depthMVP
        self.fbo['diffuse_light'] = (0.0, 1.0, 0.0)
        self.fbo['ambient_light'] = (0.1, 0.1, 0.1)
        for m_pos in range(len(self.nodes)):
            motion_matrix = Matrix().view_clip(-asp, asp, -1, 1, 1, 600, 1)
            angle = self.nodes[m_pos].rotate[0] * 3.14 / 180
            pos = self.nodes[m_pos].get_pos()

            trans = self.nodes[m_pos].translate[:]

            result = [0, 0, 0]
            result[0] = 0.3 if trans[0] < pos[0] else -0.3
            result[1] = 0.3 if trans[1] < pos[1] else -0.3
            result[2] = 0.3 if trans[2] < pos[2] else -0.3

            motion_matrix = motion_matrix.translate(trans[0] + 0.1,
                                                    trans[1] + 0.1,
                                                    trans[2])
            self.motion_blur_fbo['oldTransformation{0}'.format(str(m_pos))] = motion_matrix

        self.motion_blur_fbo['projection_mat'] = proj
        self.motion_blur_fbo['depthMVP'] = depthMVP

        if self.picking_fbo:
            self.picking_fbo['projection_mat'] = proj

        self.alpha += 10 * time
        self.fbo['cond'] = (0.0, 0.7)
        self.fbo['val_sin'] = (self.alpha, 0.0)
Example #48
0
class SingleRotate(object):
    
    def __init__(self, angle, axis, render_context):
        # It shold be way to get current context
        # but in simple case we may just pass it to constructor 
       self.context = render_context
       self._axis = axis
       self._angle = angle
       self.renderer = render_context
       self.prev_mvm = Matrix()
       self.matrix = Matrix()
       Callback(self._rotate) # here we perform rotation

    def radians(self, degrees):
       """ Calculate radians from angle here """
       return degrees * (3.14159265 / 180.) 

    @property
    def angle(self):
       return self._angle 

    @angle.setter
    def angle(self, v):
       self._angle = v
       angle = self.radians(self._angle)
       ax, ay, az = self._axis
       # calculate rotated matrix and store it
       self.matrix = Matrix().rotate(angle, ax, ay, az)

    def clear(self):
       Callback(self._clear)

    def _rotate(self, *args):
       " This sets rotation in callback "
       # get previous matrix and save it
       self.prev_mvm = self.renderer['modelview_mat']
       # do multiply for rotation
       self.context['modelview_mat'] = self.prev_mvm.multiply(self.matrix)

    def _clear(self, *args):
       self.renderer['modelview_mat'] = self.prev_mvm
Example #49
0
    def update_viewport(self):
        from kivy.graphics.opengl import glViewport
        from kivy.graphics.transformation import Matrix
        from math import radians

        w, h = self.system_size
        if self._density != 1:
            w, h = self.size

        smode = self.softinput_mode
        kheight = self.keyboard_height

        w2, h2 = w / 2.0, h / 2.0
        r = radians(self.rotation)

        x, y = 0, 0
        _h = h
        if smode:
            y = kheight
        if smode == "scale":
            _h -= kheight

        # prepare the viewport
        glViewport(x, y, w, _h)

        # do projection matrix
        projection_mat = Matrix()
        projection_mat.view_clip(0.0, w, 0.0, h, -1.0, 1.0, 0)
        self.render_context["projection_mat"] = projection_mat

        # do modelview matrix
        modelview_mat = Matrix().translate(w2, h2, 0)
        modelview_mat = modelview_mat.multiply(Matrix().rotate(r, 0, 0, 1))

        w, h = self.size
        w2, h2 = w / 2.0, h / 2.0
        modelview_mat = modelview_mat.multiply(Matrix().translate(-w2, -h2, 0))
        self.render_context["modelview_mat"] = modelview_mat

        # redraw canvas
        self.canvas.ask_update()

        # and update childs
        self.update_childsize()
Example #50
0
    def recalc(self, *args, **kwargs):
        block = copy.deepcopy(self.block)
        
        block['x'] -= block['blend_left'] / 2
        block['y'] -= block['blend_top'] / 2
        block['width'] += block['blend_left'] / 2 + block['blend_right'] / 2
        block['height'] += block['blend_top'] / 2 + block['blend_bottom'] / 2
        
        print(block['x'], block['y'], block['width'], block['height'])
        
        if block['x'] < 0: block['x'] = 0
        if block['y'] < 0: block['x'] = 0
        if block['width'] > 1: block['width'] = 1
        if block['height'] > 1: block['height'] = 1
    
        w, h = self.source.texture.width, self.source.texture.height
        sw, sh = self.source.width / self.source.texture.width, self.source.height / self.source.texture.height

#        self.texture = self.source.texture.get_region(
#            sw * min(block['x'] * w, w) - (block['blend_left'] * w / 2),
#            sh * min(block['y'] * h, h) - (block['blend_top'] * h / 2),
#            sw * min(block['width'] * w, w) + (block['blend_right'] * w / 2),
#            sh * min(block['height'] * h, h) + (block['blend_bottom'] * h / 2)
#        )

        self.texture = self.source.texture.get_region(
            sw * min(block['x'] * w, w),
            sh * min(block['y'] * h, h),
            sw * min(block['width'] * w, w),
            sh * min(block['height'] * h, h)
        )
                          
        before = [
            [-1, -1],
            [1, -1],
            [1, 1],
            [-1, 1]
        ]
        
        # Adjust size of section if edge blending is used
        points = block['points']
        points[3] = [points[3][0] - block['blend_left'], points[3][1] + block['blend_bottom']]
        points[2] = [points[2][0] + block['blend_right'], points[2][1] + block['blend_bottom']]
        points[0] = [points[0][0] - block['blend_left'], points[0][1] - block['blend_top']]
        points[1] = [points[1][0] + block['blend_right'], points[1][1] - block['blend_top']]

        after = numpy.array(points)
        
        A = []
        for a, b in zip(after, before):
            A.append([
                b[0], 0, -a[0] * b[0],
                b[1], 0, -a[0] * b[1], 1, 0]);
            A.append([
                0, b[0], -a[1] * b[0],
                0, b[1], -a[1] * b[1], 0, 1]);
                                
        A = numpy.array(A)

        B = numpy.array([[c for p in block['points'] for c in p]])
        B = B.transpose()

        m = numpy.dot(numpy.linalg.inv(A), B)

        m = m.transpose().reshape(-1,).tolist()
                
        matrix = Matrix()
        matrix.set([
            m[0], m[1],   0, m[2],
            m[3], m[4],   0, m[5],
               0,    0,   1,    0,
            m[6], m[7],   0,    1
        ])
        
        self.canvas['uTransformMatrix'] = matrix

        self.canvas['brightness'] = float(block.get('brightness', 1))
        self.canvas['alpha_mask'] = int(block.get('alpha_mask', False)) # Because Kivy can't pass booleans to shaders, apparently.
        self.canvas['adjust'] = float(self.client.minion['settings'].get('displayminion_color_adjust_range', 0))

        self.canvas['tex_x'] = block['x']
        self.canvas['tex_y'] = block['y']
        self.canvas['tex_width'] = block['width']
        self.canvas['tex_height'] = block['height']
        
        self.canvas['blend_top'] = float(block['blend_top'])
        self.canvas['blend_bottom'] = float(block['blend_bottom'])
        self.canvas['blend_left'] = float(block['blend_left'])
        self.canvas['blend_right'] = float(block['blend_right'])
        
        self.canvas.clear()
        with self.canvas:
            self.rect = Rectangle(texture = self.texture, size = (2, 2), pos = (-1, -1))
Example #51
0
    def _show_image(
            config, img, scale=None, translation=None,
            rotation=None, transform_matrix=None):
        from kivy.graphics.texture import Texture
        from kivy.graphics.fbo import Fbo
        from kivy.graphics import (
            Mesh, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle,
            Color)
        from kivy.graphics.context_instructions import (
            PushMatrix, PopMatrix, Rotate, Translate, Scale, MatrixInstruction,
            BindTexture)
        from kivy.graphics.transformation import Matrix
        img_fmt = img.get_pixel_format()
        img_w, img_h = img.get_size()
        size = config['orig_size']
        pos = config['pos']
        canvas = config['canvas']

        if img_fmt not in ('yuv420p', 'rgba', 'rgb24', 'gray', 'bgr24', 'bgra'):
            ofmt = get_best_pix_fmt(
                img_fmt, ('yuv420p', 'rgba', 'rgb24', 'gray', 'bgr24', 'bgra'))
            swscale = SWScale(
                iw=img_w, ih=img_h, ifmt=img_fmt, ow=0, oh=0, ofmt=ofmt)
            img = swscale.scale(img)
            img_fmt = img.get_pixel_format()

        kivy_ofmt = {
            'yuv420p': 'yuv420p', 'rgba': 'rgba', 'rgb24': 'rgb',
            'gray': 'luminance', 'bgr24': 'bgr', 'bgra': 'bgra'}[img_fmt]

        if kivy_ofmt == 'yuv420p':
            w2 = int(img_w / 2)
            h2 = int(img_h / 2)
            tex_y = Texture.create(size=(img_w, img_h), colorfmt='luminance')
            tex_u = Texture.create(size=(w2, h2), colorfmt='luminance')
            tex_v = Texture.create(size=(w2, h2), colorfmt='luminance')

            with canvas:
                fbo = Fbo(size=(img_w, img_h))
            with fbo:
                BindTexture(texture=tex_u, index=1)
                BindTexture(texture=tex_v, index=2)
                Rectangle(size=fbo.size, texture=tex_y)
            fbo.shader.fs = CeedDataReader._YUV_RGB_FS
            fbo['tex_y'] = 0
            fbo['tex_u'] = 1
            fbo['tex_v'] = 2

            tex = fbo.texture
            dy, du, dv, _ = img.to_memoryview()
            tex_y.blit_buffer(dy, colorfmt='luminance')
            tex_u.blit_buffer(du, colorfmt='luminance')
            tex_v.blit_buffer(dv, colorfmt='luminance')
        else:
            tex = Texture.create(size=(img_w, img_h), colorfmt=kivy_ofmt)
            tex.blit_buffer(img.to_memoryview()[0], colorfmt=kivy_ofmt)
        tex.flip_vertical()

        with canvas:
            StencilPush()
            Rectangle(pos=pos, size=size)
            StencilUse()

            PushMatrix()
            center = pos[0] + size[0] / 2, pos[1] + size[1] / 2
            if rotation:
                Rotate(angle=rotation, axis=(0, 0, 1), origin=center)
            if scale:
                Scale(scale, scale, 1, origin=center)
            if translation:
                Translate(*translation)
            if transform_matrix is not None:
                mat = Matrix()
                mat.set(array=transform_matrix)
                m = MatrixInstruction()
                m.matrix = mat
            Rectangle(size=(img_w, img_h), texture=tex, pos=pos)
            PopMatrix()

            StencilUnUse()
            Rectangle(pos=pos, size=size)
            StencilPop()
Example #52
0
 def make_matrix(elems):
     mat = Matrix()
     mat.set(array=elems)
     return mat
Example #53
0
 def update_projection_matrix(self):
     m = Matrix()
     m.perspective(self.fov * 0.5, self.aspect, self.near, self.far)
     self.projection_matrix = m
Example #54
0
 def _update_labels(self):
     xlabel = self._xlabel
     ylabel = self._ylabel
     x = self.x
     y = self.y
     width = self.width
     height = self.height
     padding = self.padding
     x_next = padding + x
     y_next = padding + y
     xextent = x + width
     yextent = y + height
     ymin = self.ymin
     ymax = self.ymax
     xmin = self.xmin
     precision = self.precision
     x_overlap = False
     y_overlap = False
     # set up x and y axis labels
     if xlabel:
         xlabel.text = self.xlabel
         xlabel.texture_update()
         xlabel.size = xlabel.texture_size
         xlabel.pos = (x + width / 2. - xlabel.width / 2., padding + y)
         y_next += padding + xlabel.height
     if ylabel:
         ylabel.text = self.ylabel
         ylabel.texture_update()
         ylabel.size = ylabel.texture_size
         ylabel.x = padding + x - (ylabel.width / 2. - ylabel.height / 2.)
         x_next += padding + ylabel.height
     xpoints = self._ticks_majorx
     xlabels = self._x_grid_label
     xlabel_grid = self.x_grid_label
     ylabel_grid = self.y_grid_label
     ypoints = self._ticks_majory
     ylabels = self._y_grid_label
     # now x and y tick mark labels
     if len(ylabels) and ylabel_grid:
         # horizontal size of the largest tick label, to have enough room
         ylabels[0].text = precision % ypoints[0]
         ylabels[0].texture_update()
         y1 = ylabels[0].texture_size
         y_start = y_next + (
             padding + y1[1]
             if len(xlabels) and xlabel_grid else 0
         ) + (padding + y1[1] if not y_next else 0)
         yextent = y + height - padding - y1[1] / 2.
         if self.ylog:
             ymax = log10(ymax)
             ymin = log10(ymin)
         ratio = (yextent - y_start) / float(ymax - ymin)
         y_start -= y1[1] / 2.
         func = (lambda x: 10 ** x) if self.ylog else lambda x: x
         y1 = y1[0]
         for k in xrange(len(ylabels)):
             ylabels[k].text = precision % func(ypoints[k])
             ylabels[k].texture_update()
             ylabels[k].size = ylabels[k].texture_size
             y1 = max(y1, ylabels[k].texture_size[0])
             ylabels[k].pos = (x_next, y_start + (ypoints[k] - ymin) *
                               ratio)
         if len(ylabels) > 1 and ylabels[0].top > ylabels[1].y:
             y_overlap = True
         else:
             x_next += y1 + padding
     if len(xlabels) and xlabel_grid:
         func = log10 if self.xlog else lambda x: x
         # find the distance from the end that'll fit the last tick label
         xlabels[0].text = precision % func(xpoints[-1])
         xlabels[0].texture_update()
         xextent = x + width - xlabels[0].texture_size[0] / 2. - padding
         # find the distance from the start that'll fit the first tick label
         if not x_next:
             xlabels[0].text = precision % func(xpoints[0])
             xlabels[0].texture_update()
             x_next = padding + xlabels[0].texture_size[0] / 2.
         xmin = func(xmin)
         ratio = (xextent - x_next) / float(func(self.xmax) - xmin)
         func = (lambda x: 10 ** x) if self.xlog else lambda x: x
         right = -1
         for k in xrange(len(xlabels)):
             xlabels[k].text = precision % func(xpoints[k])
             # update the size so we can center the labels on ticks
             xlabels[k].texture_update()
             xlabels[k].size = xlabels[k].texture_size
             xlabels[k].pos = (x_next + (xpoints[k] - xmin) * ratio -
                               xlabels[k].texture_size[0] / 2., y_next)
             if xlabels[k].x < right:
                 x_overlap = True
                 break
             right = xlabels[k].right
         if not x_overlap:
             y_next += padding + xlabels[0].texture_size[1]
     # now re-center the x and y axis labels
     if xlabel:
         xlabel.x = x_next + (xextent - x_next) / 2. - xlabel.width / 2.
     if ylabel:
         ylabel.y = y_next + (yextent - y_next) / 2. - ylabel.height / 2.
         t = Matrix().translate(ylabel.center[0], ylabel.center[1], 0)
         t = t.multiply(Matrix().rotate(-radians(270), 0, 0, 1))
         ylabel.transform = t.multiply(Matrix().translate(-ylabel.center[0],
                                                          -ylabel.center[1],
                                                          0))
     if x_overlap:
         for k in xrange(len(xlabels)):
             xlabels[k].text = ''
     if y_overlap:
         for k in xrange(len(ylabels)):
             ylabels[k].text = ''
     return x_next, y_next, xextent, yextent
Example #55
0
    def _paint_electrodes_data_setup(
            self, config, electrode_names,
            spacing=2, draw_size=(0, 0), draw_size_hint=(1, 1),
            draw_pos=(0, 0), draw_pos_hint=(None, None), volt_scale=1e-6,
            time_axis_s=1, volt_axis=100, transform_matrix=None,
            label_width=70):
        from kivy.graphics import (
            Mesh, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle,
            Color)
        from kivy.graphics.context_instructions import (
            PushMatrix, PopMatrix, Scale, MatrixInstruction)
        from kivy.graphics.transformation import Matrix
        from kivy.base import EventLoop
        EventLoop.ensure_window()
        from kivy.core.text import Label
        from kivy.metrics import dp, sp

        n_rows = len(electrode_names)
        if not n_rows:
            raise ValueError("There must be at least one electrode specified")
        n_cols = len(electrode_names[0])
        if not n_cols:
            raise ValueError("There must be at least one electrode specified")
        if not all((len(row) == n_cols for row in electrode_names)):
            raise ValueError(
                "The number of electrodes in all rows must be the same")
        n_electrodes = sum(map(len, electrode_names))

        orig_w, orig_h = config['orig_size']
        fbo = config['canvas']

        label_height = 45 if label_width else 0
        draw_w, draw_h = draw_size
        draw_hint_w, draw_hint_h = draw_size_hint
        w = int(draw_w if draw_hint_w is None else orig_w * draw_hint_w)
        h = int(draw_h if draw_hint_h is None else orig_h * draw_hint_h)

        draw_x, draw_y = draw_pos
        draw_hint_x, draw_hint_y = draw_pos_hint
        x = int(draw_x if draw_hint_x is None else orig_w * draw_hint_x)
        y = int(draw_y if draw_hint_y is None else orig_h * draw_hint_y)

        ew = int((w - label_width - max(0, n_cols - 1) * spacing) / n_cols)
        eh = int((h - label_height - max(0, n_rows - 1) * spacing) / n_rows)

        with fbo:
            PushMatrix()
            # center = x + w / 2., y + h / 2.
            # if scale:
            #     Scale(scale, scale, 1, origin=center)
            if transform_matrix is not None:
                mat = Matrix()
                mat.set(array=transform_matrix)
                m = MatrixInstruction()
                m.matrix = mat

        positions = [(0, 0), ] * n_electrodes
        graphics = [None, ] * n_electrodes
        i = 0

        electrode_color = 1, 215 / 255, 0, 1
        for row, row_names in enumerate(reversed(electrode_names)):
            ey = y + label_height
            if row:
                ey += (eh + spacing) * row

            for col, name in enumerate(row_names):
                if name is None:
                    i += 1
                    continue

                ex = x + label_width
                if col:
                    ex += (ew + spacing) * col

                positions[i] = ex, ey
                fbo.add(Color(*electrode_color))
                fbo.add(StencilPush())
                fbo.add(Rectangle(pos=(ex, ey), size=(ew, eh)))
                fbo.add(StencilUse())
                graphics[i] = Mesh(mode='line_strip')
                fbo.add(graphics[i])
                fbo.add(StencilUnUse())
                fbo.add(Rectangle(pos=(ex, ey), size=(ew, eh)))
                fbo.add(StencilPop())

                i += 1

                if label_width:
                    if not col:
                        fbo.add(Color(1, 1, 1, 1))
                        label = Label(text=name, font_size=sp(40))
                        label.refresh()
                        _w, _h = label.texture.size
                        rect = Rectangle(
                            pos=(x, ey + (eh - _h) / 2.),
                            size=label.texture.size)
                        rect.texture = label.texture
                        fbo.add(rect)

                    if not row:
                        fbo.add(Color(1, 1, 1, 1))
                        label = Label(text=name, font_size=sp(40))
                        label.refresh()
                        _w, _h = label.texture.size
                        rect = Rectangle(
                            pos=(ex + (ew - _w) / 2., y),
                            size=label.texture.size)
                        rect.texture = label.texture
                        fbo.add(rect)

        with fbo:
            Color(1, 1, 1, 1)
            PopMatrix()

        electrodes_data = [None, ] * n_electrodes
        # y_min, y_max = float('inf'), float('-inf')
        alignment = np.array(self.electrode_intensity_alignment)

        # get the frequency from any channel
        name = None
        for row_names in electrode_names:
            for name in row_names:
                if name is not None:
                    break
            if name is not None:
                break
        freq = self.electrodes_metadata[name]['sampling_frequency']

        frame_n = int(1 / config['rate'] * freq)
        n_t = int(time_axis_s * freq)
        t_vals = np.arange(n_t) / (n_t - 1) * ew
        y_scale = (eh / 2) / volt_axis

        for i, name in enumerate(itertools.chain(*electrode_names)):
            if name is None:
                continue
            offset, scale = self.get_electrode_offset_scale(name)
            electrodes_data[i] = \
                self.electrodes_data[name], offset, scale / volt_scale
            # y_min = min(np.min(data), y_min)
            # y_max = max(np.max(data), y_max)

        new_config = {
            'alignment': alignment, 'frame_n': frame_n, 't_vals': t_vals,
            'y_scale': y_scale, 'electrodes_data': electrodes_data, 'n_t': n_t,
            'positions': positions, 'graphics': graphics, 'eh': eh}
        return CallableGen(self._paint_electrodes_data(new_config))
Example #56
0
    def _show_mea_outline(self, config, transform_matrix=None):
        from kivy.graphics import (
            Line, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle,
            Color)
        from kivy.graphics.context_instructions import (
            PushMatrix, PopMatrix, Rotate, Translate, Scale, MatrixInstruction,
            BindTexture)
        from kivy.graphics.transformation import Matrix
        from kivy.base import EventLoop
        EventLoop.ensure_window()
        from kivy.core.text import Label
        from kivy.metrics import dp, sp

        size = config['orig_size']
        pos = config['pos']
        canvas = config['canvas']
        mea_w = max(self.view_controller.mea_num_cols - 1, 0) * \
            self.view_controller.mea_pitch
        mea_h = max(self.view_controller.mea_num_rows - 1, 0) * \
            self.view_controller.mea_pitch
        last_col = "ABCDEFGHJKLMNOPQRSTUVWXYZ"[
            self.view_controller.mea_num_cols - 1]

        with canvas:
            StencilPush()
            Rectangle(pos=pos, size=size)
            StencilUse()

            PushMatrix()
            if transform_matrix is not None:
                mat = Matrix()
                mat.set(array=transform_matrix)
                m = MatrixInstruction()
                m.matrix = mat
            Color(1, 215 / 255, 0, .2)
            Line(points=[0, 0, mea_w, 0, mea_w, mea_h, 0, mea_h], close=True)

            label = Label(text='A1', font_size=sp(12))
            label.refresh()
            _w, _h = label.texture.size
            rect = Rectangle(
                pos=(mea_w, mea_h - _h / 2.), size=label.texture.size)
            rect.texture = label.texture

            label = Label(
                text='A{}'.format(self.view_controller.mea_num_rows),
                font_size=sp(12))
            label.refresh()
            _w, _h = label.texture.size
            rect = Rectangle(
                pos=(-_w, mea_h - _h / 2.), size=label.texture.size)
            rect.texture = label.texture

            label = Label(text='{}1'.format(last_col), font_size=sp(12))
            label.refresh()
            _w, _h = label.texture.size
            rect = Rectangle(pos=(mea_w, -_h / 2.), size=label.texture.size)
            rect.texture = label.texture

            label = Label(
                text='{}{}'.format(last_col, self.view_controller.mea_num_rows),
                font_size=sp(12))
            label.refresh()
            _w, _h = label.texture.size
            rect = Rectangle(pos=(-_w, -_h / 2.), size=label.texture.size)
            rect.texture = label.texture
            PopMatrix()

            StencilUnUse()
            Rectangle(pos=pos, size=size)
            StencilPop()
Example #57
0
 def apply_transform(self, rescale, anchor=(0, 0)):
     trans = Matrix().scale(rescale, rescale, rescale)
     t = Matrix().translate(anchor[0], anchor[1], 0)
     t = t.multiply(trans)
     t = t.multiply(Matrix().translate(-anchor[0], -anchor[1], 0))
     self.transform.matrix = t
Example #58
0
 def get_window_matrix(self, x=0, y=0):
     m = Matrix()
     m.translate(x, y, 0)
     return m
Example #59
-1
    def update_glsl(self, *largs):
        asp = self.width / float(self.height)
        asp = 15 / 6.0
        proj = Matrix()
        mat = Matrix()
        mat = mat.look_at(
            self.camera_loc[0] * self.camera_r,
            self.camera_loc[1] * self.camera_r,
            self.camera_loc[2] * self.camera_r,
            0,
            0,
            0,
            self.camera_up[0],
            self.camera_up[1],
            self.camera_up[2],
        )
        proj = proj.view_clip(-asp * 0.5, asp * 0.5, -0.5, 0.5, 1, 10, 1)

        self.canvas["projection_mat"] = proj
        self.canvas["modelview_mat"] = mat