Exemplo n.º 1
0
    def render(self, time, frame_time):
        self.ctx.clear(0.2, 0.2, 0.2)

        self.ctx.enable(moderngl.DEPTH_TEST)

        self.fps = 1 / frame_time
        self.control()

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            (self.movX, self.movY, self.movZ),
            (200.0, 200.0, 0.0),
            (0.0, 0.0, 1.0),
        )

        self.light.value = (100, 0, 200)

        self.texture.use(0)
        self.mvp_map.write((proj * lookat).astype('f4'))
        self.vao_map.render(moderngl.TRIANGLE_FAN)

        model_rot = Matrix44.from_z_rotation(
            3.14 / 4) * Matrix44.from_x_rotation(-3.14 / 2)

        for x in range(int(self.positions.size / 3)):
            size = 1 + self.production[x] * (2.5 - 1)
            model_size = Matrix44.from_scale(np.array([size, size, size]))
            self.gradient.value = self.production[x]
            model = Matrix44.from_translation(np.array(
                self.positions[x])) * model_rot * model_size
            self.mvp.write((proj * lookat * model).astype('f4'))
            self.vao.render()

        self.render_ui()
Exemplo n.º 2
0
 def generate_twig_from_file(self, filepath):
     f = open(filepath, 'r')
     for line in f:
         if line.startswith("sphere"):
             arr = line.split(" ")
             if len(arr) > 10:
                 self.needle_num += 1
                 zenith_rotation_angle = degree_to_rad(float(arr[13]))
                 azimuth_rotation_angle = degree_to_rad(float(arr[18]))
                 translate_vector = Vector3([float(arr[20]), float(arr[21]), float(arr[22])])
                 matrix = Matrix44.from_y_rotation(zenith_rotation_angle)
                 matrix = matrix * Matrix44.from_z_rotation(azimuth_rotation_angle)
                 matrix = matrix * Matrix44.from_translation(translate_vector)
                 # applying rotation
                 newNeedle_vertexes = list(map(lambda x: matrix * Vector3(x), self.prim_needle.vertexes))
                 self.vertexes += newNeedle_vertexes
     f.close()
     # generate twig
     r = math.pi * self.twig_diameter / 6.0
     lower_plane, upper_plane = [], []
     for i in range(0, 360, 60):
         angle_rad = degree_to_rad(i)
         x = r * math.cos(angle_rad)
         y = r * math.sin(angle_rad)
         lower_plane.append([x, y, 0])
         upper_plane.append([x, y, self.twig_length])
     self.twig_vertexes = lower_plane + upper_plane
    def render(self, time: float, frame_time: float):
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.use_texture.value = False

        self.light.value = (67.69, -8.14, 52.49)
        self.mvp.write((proj * lookat * rotate).astype('f4').tobytes())

        self.color.value = (0.67, 0.49, 0.29)
        self.objects['ground'].render()

        self.color.value = (0.46, 0.67, 0.29)
        self.objects['grass'].render()

        self.color.value = (1.0, 1.0, 1.0)
        self.objects['billboard'].render()

        self.color.value = (0.2, 0.2, 0.2)
        self.objects['billboard-holder'].render()

        self.use_texture.value = True
        self.texture.use()

        self.objects['billboard-image'].render()
Exemplo n.º 4
0
 def rotate_relative(self, rotation):
     pos = self.get_position()
     rotate_matrix = Matrix44.from_x_rotation(rotation.x) * \
                     Matrix44.from_y_rotation(rotation.y) * \
                     Matrix44.from_z_rotation(rotation.z)
     self.matrix = rotate_matrix * self.matrix
     self.set_position(pos)
    def render(self, time: float, frame_time: float):
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)

        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.use_texture.value = False

        self.light.value = (67.69, -8.14, 52.49)
        self.mvp.write((proj * lookat * rotate).astype('f4').tobytes())

        self.color.value = (0.67, 0.49, 0.29)
        self.vao_ground.render()

        self.color.value = (0.46, 0.67, 0.29)
        self.vao_grass.render()

        self.color.value = (1.0, 1.0, 1.0)
        self.vao_billboard.render()

        self.color.value = (0.2, 0.2, 0.2)
        self.vao_holder.render()

        self.use_texture.value = True
        self.texture.use()

        self.vao_image.render()
    def render(self, time, frame_time):
        if SimpleRenderer.callback and frame_time > 0:
            SimpleRenderer.callback(frame_time)
        # print(time, frame_time)
        self.camera.update()

        self.ctx.clear(0.1, 0.1, 0.1)
        self.ctx.enable(moderngl.DEPTH_TEST)

        # print('---------')
        # print(self.camera.elevation, self.camera.azimuth)
        # print(self.camera.mat_lookat*Vector4([0,0,0,1]))

        # grid
        self.mvp.write((self.camera.mat_projection *
                        self.camera.mat_lookat.inverse).astype('f4'))
        self.grid_vao.render(moderngl.LINES)
        # objects
        for obj in SimpleRenderer.objects:
            # model matrix
            scale = Matrix44.from_scale([obj.radius, obj.radius, obj.radius])
            rotation = Matrix44.from_z_rotation(
                -np.arctan2(obj.vel.y, obj.vel.x))
            translation = Matrix44.from_translation([obj.pos.x, obj.pos.y, 0])
            model = translation * rotation * scale
            # render object
            self.mvp.write(
                (self.camera.mat_projection * self.camera.mat_lookat.inverse *
                 model).astype('f4'))
            self.cyl_vao.render(moderngl.TRIANGLES)
Exemplo n.º 7
0
def get_rotation(x, y, z):
    logger.debug('Create rotation matrix with (x:{}, y:{}, z:{})'.format(
        x, y, z))
    x_rotation = Matrix44.from_x_rotation(x)
    y_rotation = Matrix44.from_y_rotation(y)
    z_rotation = Matrix44.from_z_rotation(z)
    return z_rotation * y_rotation * x_rotation
Exemplo n.º 8
0
def buildTransMatrix(pos=[0, 0, 0], rot=[0, 0, 0], scale=[1, 1, 1]):
    trans = Matrix44.from_translation(pos)
    rotX = Matrix44.from_x_rotation(np.radians(rot[0]))
    rotY = Matrix44.from_y_rotation(np.radians(rot[1]))
    rotZ = Matrix44.from_z_rotation(np.radians(rot[2]))
    scale = Matrix44.from_scale(scale)
    tMatrix = trans * scale * rotX * rotY * rotZ
    return tMatrix
def applyTransforms(vector, projectionMat):
    r = time.clock() + vector[0] * 10 # rotation offset based on vector's 1st component
    rotX = Matrix44.from_x_rotation(r)
    rotY = Matrix44.from_y_rotation(r)
    rotZ = Matrix44.from_z_rotation(r)
    trans = Matrix44.from_translation(vector) * Matrix44.from_translation([1,1,-5]) # move view back by -5
    scale = Matrix44.from_scale([.5,.5,.5]) # uniformly scale by 0.5
    tMatrix = projectionMat * trans * scale * rotX * rotY * rotZ
    prog['transform'].write(tMatrix.astype('f4').tobytes())
Exemplo n.º 10
0
def scatterCubes(vector, projectionMat):
    view = window.getViewMatrix()
    r = vector[0] * 10.0 # cube rotation offset based on vector's 1st component
    rotX = Matrix44.from_x_rotation(r*time.clock()/10.0) # rotate cubes over time
    rotY = Matrix44.from_y_rotation(r)
    rotZ = Matrix44.from_z_rotation(r)
    trans = Matrix44.from_translation(vector) * Matrix44.from_translation([1.0,1.0,-5.0])
    scale = Matrix44.from_scale([.5,.5,.5]) # uniformly scale by 0.5
    tMatrix = projectionMat * view * trans * scale * rotX * rotY * rotZ
    prog['transform'].write(tMatrix.astype('f4').tobytes())
Exemplo n.º 11
0
    def render(self):
        width, height = self.wnd.size
        self.ctx.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        proj = Matrix44.perspective_projection(45.0, width / height, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(self.wnd.time) * 0.5 + 0.2)

        for mode in ['render_to_texture', 'render_to_window']:
            if mode == 'render_to_texture':
                self.fbo.clear(1.0, 1.0, 1.0)
                self.fbo.use()

            else:
                self.ctx.screen.use()

            self.use_texture.value = False

            self.light.value = (67.69, -8.14, 52.49)
            self.mvp.write((proj * lookat * rotate).astype('f4').tobytes())

            self.color.value = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.color.value = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.color.value = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.color.value = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.use_texture.value = True

            if mode == 'render_to_texture':
                self.texture1.use()

            else:
                self.texture2.use()

            self.objects['billboard-image'].render()
Exemplo n.º 12
0
def update(dt):
    proj = Matrix44.perspective_projection(50, width / height, 0.1, 1000.0)
    rotX = Matrix44.from_x_rotation(0)
    rotY = Matrix44.from_y_rotation(time.clock() * 1.5)
    rotZ = Matrix44.from_z_rotation(
        180 * np.pi / 180)  # rotate 180 degrees. Convert degrees to radians
    trans = Matrix44.from_translation(
        [np.sin(time.clock()) / 4,
         np.sin(time.clock()) / 4,
         -1.3])  # bounce diagonally from corner to corner, move back by -1.3
    scale = Matrix44.from_scale([.5, .5, .5])  # uniformly scale by 0.5
    tMatrix = proj * trans * scale * rotX * rotY * rotZ
    prog['transform'].write(tMatrix.astype('f4').tobytes())
    ctx.clear(.1, .1, .1)
    vao.render()
Exemplo n.º 13
0
  def getModelMatrix(self):
      scale = mat4.from_scale([0.2, 0.2, 0.2])
      
      roty = mat4.from_y_rotation(-self.hAngle)

      vdiff = self.vAngle - self.oldvAngle
      rotx = mat4.from_x_rotation(self.getxRot(vdiff))
      
      zdiff = self.hAngle - self.oldhAngle
      rotz = mat4.from_z_rotation(-self.getzRot(zdiff))

      trans = mat4.from_translation(self.position, dtype='f')
      self.oldhAngle = self.hAngle
      self.oldvAngle = self.vAngle
      
      return scale * rotz * rotx * roty * trans
Exemplo n.º 14
0
    def build_matrix(self):
        """Builds and stores the transformation matrix internally"""

        m = Matrix44.identity()
        if isinstance(self.scale, list) or isinstance(self.scale, tuple):
            m.m11 = self.scale[0]
            m.m22 = self.scale[1]
            m.m33 = self.scale[2]
        else:
            m *= self.scale
            m.m44 = 1
        m = Matrix44.from_x_rotation(math.radians(self.pitch)) * m
        m = Matrix44.from_y_rotation(math.radians(self.yaw)) * m
        m = Matrix44.from_z_rotation(math.radians(self.roll)) * m
        m = Matrix44.from_translation(Vector3(self.position)) * m
        self.m = numpy.array(m).astype("f4")
    def render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        # self.ctx.enable(mgl.DEPTH_TEST)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        w, h = self.texture.size
        gw, gh = 16, 16
        nx, ny, nz = int(w / gw), int(h / gh), 1

        print('=' * 50)

        self.compute['time'] = time
        GL_WRITE_ONLY = 0x88B9
        GL_R32F = 0x822E
        self.texture.bind_to_image(0, GL_WRITE_ONLY, GL_R32F)
        self.compute.run(nx, ny, nz)
        print('-' * 50)

        with self.scope:
            self.prog['UseTexture'] = False

            self.prog['Light'] = (67.69, -8.14, 52.49)
            self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

            self.prog['Color'] = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.prog['Color'] = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.prog['Color'] = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.prog['Color'] = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.prog['UseTexture'] = True

            self.objects['billboard-image'].render()
    def render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        # self.ctx.enable(mgl.DEPTH_TEST)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        w, h = self.texture.size
        gw, gh = 16, 16
        nx, ny, nz = int(w/gw), int(h/gh), 1

        print('=' * 50)

        self.compute['time'] = time
        GL_WRITE_ONLY = 0x88B9
        GL_R32F = 0x822E
        self.texture.bind_to_image(0,GL_WRITE_ONLY, GL_R32F)
        self.compute.run(nx, ny, nz)
        print('-' * 50)

        with self.scope:
            self.prog['UseTexture'] = False

            self.prog['Light'] = (67.69, -8.14, 52.49)
            self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

            self.prog['Color'] = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.prog['Color'] = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.prog['Color'] = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.prog['Color'] = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.prog['UseTexture'] = True

            self.objects['billboard-image'].render()
Exemplo n.º 17
0
    def build_matrix(self):
        """Builds and stores the viewport matrix internally
        Automatically builds the MVP matrix as well"""
        # Note that by nature, a camera perspective inverts everything
        # So we negate everything and also do it in reverse

        # Overrides PositionMatrix, reverse everything, ignore scale
        m = Matrix44.identity()
        m = Matrix44.from_translation(-1 * Vector3(self.position)) * m
        m = Matrix44.from_z_rotation(-math.radians(self.roll)) * m
        m = Matrix44.from_y_rotation(-math.radians(self.yaw)) * m
        m = Matrix44.from_x_rotation(-math.radians(self.pitch)) * m
        if self.tp:
            # Third person enabled
            m = Matrix44.from_translation([0, 0, -self.tp_distance]) * m

        self.m = m
        self.mvp = numpy.array(self.p * self.m).astype("f4")
Exemplo n.º 18
0
    def render(self):
        width, height = self.wnd.size
        self.ctx.screen.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)
        with self.ctx.scope(mgl.DEPTH_TEST):

            proj = Matrix44.perspective_projection(45.0, width / height, 0.1,
                                                   1000.0)
            lookat = Matrix44.look_at(
                (47.697, -8.147, 24.498),
                (0.0, 0.0, 8.0),
                (0.0, 0.0, 1.0),
            )

            rotate = Matrix44.from_z_rotation(
                np.sin(self.wnd.time) * 0.5 + 0.2)

            self.prog['UseTexture'] = False

            self.prog['Light'] = (67.69, -8.14, 52.49)
            self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

            self.prog['Color'] = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.prog['Color'] = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.prog['Color'] = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.prog['Color'] = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.prog['UseTexture'] = True
            # self.texture.use()
            self.sampler.use()

            self.objects['billboard-image'].render()
Exemplo n.º 19
0
    def frames():
        with create_context() as ctx:
            renderer = Renderer(ctx, (w, h), mesh, projection=projection)

            for _ in count():
                t = time.time() - beginning
                theta = t * angular_velocity
                rotation = Matrix44.from_z_rotation(
                    theta[2]) * Matrix44.from_y_rotation(
                        theta[1]) * Matrix44.from_x_rotation(theta[0])
                camera = Matrix44.from_translation(np.array([0, 0, -d
                                                             ])) * rotation
                renderer.render(camera, light1)
                buffer = np.mean(renderer.snapshot2(), axis=-1)
                lines = ascii.shade(buffer)
                text = "resolution: {w}x{h}, fov: {fov:.2f}, fps: {fps:.2f}, d: {d:.2f}, by: vidstige 2020".format(
                    w=w, h=h, fov=fov, fps=fps, d=d)
                lines[-2] = scroller(lines[-2], text, t, w=-12)
                yield b"\033[2J\033[1;1H" + b'\n'.join(lines) + b"\n"
                duration = (time.time() - beginning) - t
                if dt - duration > 0:
                    time.sleep(dt - duration)
Exemplo n.º 20
0
    def render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        # self.ctx.enable(mgl.DEPTH_TEST)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1,
                                               1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.fbo.clear(0, (1.0, 1.0, 1.0))
        self.fbo.clear(-1, 1.0)
        for scope in [self.scope1, self.scope2]:
            with scope:
                self.prog['UseTexture'] = False

                self.prog['Light'] = (67.69, -8.14, 52.49)
                self.prog['Mvp'] = (proj * lookat *
                                    rotate).astype('f4').tobytes()

                self.prog['Color'] = (0.67, 0.49, 0.29)
                self.objects['ground'].render()

                self.prog['Color'] = (0.46, 0.67, 0.29)
                self.objects['grass'].render()

                self.prog['Color'] = (1.0, 1.0, 1.0)
                self.objects['billboard'].render()

                self.prog['Color'] = (0.2, 0.2, 0.2)
                self.objects['billboard-holder'].render()

                self.prog['UseTexture'] = True

                self.objects['billboard-image'].render()
Exemplo n.º 21
0
    def __init__(self,
                 shader,
                 transform_matrix=None,
                 parent_transform=None,
                 parent=None):
        super().__init__(parent=parent)
        self.shader = shader
        self._ptr = parent_transform
        self._pos = [0.0, 0.0, 0.0]
        self._tm = Matrix44.from_translation(self._pos)
        self._angle = 0.0
        self._rm = Matrix44.from_z_rotation(self._angle)
        self._scale = [1.0, 1.0, 1.0]
        self._sm = Matrix44.from_scale(self.scale)
        if transform_matrix:
            self._trfm = transform_matrix
        else:
            self._trfm = self._tm * self._rm * self._sm

        self._gtr = self._trfm  # global transform include parent transformations
        if self.parent and self.parent.__class__ is TransformGrp:
            self._gtr = self.parent.transform * self._trfm
        self.dirty = True  # global transform calculated
Exemplo n.º 22
0
    def render(self, clr_color=(1.0, 1.0, 1.0)):
        fbo = self.fbo
        fbo.clear(*clr_color)

        cam_ratio = self.fbo.size[0] / self.fbo.size[1]

        p = Matrix44.perspective_projection(self.cam_angle, cam_ratio, 0.00001,
                                            1000000.0)
        v = Matrix44.look_at(
            self.cam_pos,
            (0, 0, 0),
            self.cam_up,
        )

        rx = Matrix44.from_x_rotation(self.rotate_x)
        ry = Matrix44.from_y_rotation(self.rotate_y)
        rz = Matrix44.from_z_rotation(self.rotate_z)
        m = rx * ry * rz

        self._projection.write(p.astype('f4').tobytes())
        mv = v * m
        self._modelview.write(mv.astype('f4').tobytes())
        n = mv.inverse.transpose()
        self._normalMat.write(n.astype('f4').tobytes())
        self._mode.value = 2  # Phong
        #lightPos.value = tuple(tuple(n*Vector4.from_vector3(light_pos))[:3])
        self._lightPos.value = tuple(self.light_pos)
        self._lightColor.value = tuple(self.light_color)
        self._lightPower.value = self.light_power
        self._ambientColor.value = tuple(self.ambien_color)
        self._diffuseColor.value = tuple(self.diffuse_color)
        self._specColor.value = tuple(self.spec_color)
        self._shininess.value = self.shininess
        self._mainColor.value = tuple(self.main_color)

        self.vao.render()
        return fbo.read()
    def render(self):
        width, height = self.wnd.size
        self.ctx.screen.viewport = self.wnd.viewport
        self.ctx.clear(1.0, 1.0, 1.0)
        with self.ctx.scope(mgl.DEPTH_TEST):

            proj = Matrix44.perspective_projection(45.0, width / height, 0.1, 1000.0)
            lookat = Matrix44.look_at(
                (47.697, -8.147, 24.498),
                (0.0, 0.0, 8.0),
                (0.0, 0.0, 1.0),
            )

            rotate = Matrix44.from_z_rotation(np.sin(self.wnd.time) * 0.5 + 0.2)

            self.prog['UseTexture'] = False

            self.prog['Light'] = (67.69, -8.14, 52.49)
            self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

            self.prog['Color'] = (0.67, 0.49, 0.29)
            self.objects['ground'].render()

            self.prog['Color'] = (0.46, 0.67, 0.29)
            self.objects['grass'].render()

            self.prog['Color'] = (1.0, 1.0, 1.0)
            self.objects['billboard'].render()

            self.prog['Color'] = (0.2, 0.2, 0.2)
            self.objects['billboard-holder'].render()

            self.prog['UseTexture'] = True
            # self.texture.use()
            self.sampler.use()

            self.objects['billboard-image'].render()
    def render(self, time, frame_time):
        self.ctx.clear(1.0, 1.0, 1.0)
        # self.ctx.enable(mgl.DEPTH_TEST)
        proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)
        lookat = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )

        rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)

        self.fbo.clear(0, (1.0, 1.0, 1.0))
        self.fbo.clear(-1, 1.0)
        for scope in [self.scope1, self.scope2]:
            with scope:
                self.prog['UseTexture'] = False

                self.prog['Light'] = (67.69, -8.14, 52.49)
                self.prog['Mvp'] = (proj * lookat * rotate).astype('f4').tobytes()

                self.prog['Color'] = (0.67, 0.49, 0.29)
                self.objects['ground'].render()

                self.prog['Color'] = (0.46, 0.67, 0.29)
                self.objects['grass'].render()

                self.prog['Color'] = (1.0, 1.0, 1.0)
                self.objects['billboard'].render()

                self.prog['Color'] = (0.2, 0.2, 0.2)
                self.objects['billboard-holder'].render()

                self.prog['UseTexture'] = True

                self.objects['billboard-image'].render()
def main():
    glfw.init()
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window = glfw.create_window(800, 600, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_resize)

    shader = Shader(CURDIR / 'shaders/5.1.transform.vs', CURDIR / 'shaders/5.1.transform.fs')

    vertices = [
     # positions      tex_coords
     0.5,  0.5, 0.0,  1.0, 1.0,  # top right
     0.5, -0.5, 0.0,  1.0, 0.0,  # bottom right
    -0.5, -0.5, 0.0,  0.0, 0.0,  # bottom left
    -0.5,  0.5, 0.0,  0.0, 1.0,  # top left
    ]
    vertices = (c_float * len(vertices))(*vertices)

    indices = [
        0, 1, 3,
        1, 2, 3
    ]
    indices = (c_uint * len(indices))(*indices)

    vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(vao)

    vbo = gl.glGenBuffers(1)
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW)

    ebo = gl.glGenBuffers(1)
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo)
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, gl.GL_STATIC_DRAW)

    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 5 * sizeof(c_float), c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)

    # -- load texture 1
    texture1 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    # -- load texture 2
    texture2 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('awesomeface.png')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    shader.use()
    shader.set_int("texture1", 0)
    shader.set_int("texture2", 1)

    while not glfw.window_should_close(window):
        process_input(window)

        gl.glClearColor(.2, .3, .3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
        gl.glActiveTexture(gl.GL_TEXTURE1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)

        translation = Matrix44.from_translation([0.5, -0.5, 0.0])
        rotation = Matrix44.from_z_rotation(glfw.get_time())
        transform = translation * rotation

        shader.use()
        shader.set_mat4('transform', transform)
        gl.glBindVertexArray(vao)
        gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0))

        # -- second container
        translation = Matrix44.from_translation([-0.5, 0.5, 0.0])
        scale = Matrix44.from_scale([math.sin(glfw.get_time())]*3)
        transform = translation * scale

        shader.set_mat4('transform', transform)
        gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0))

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    gl.glDeleteBuffers(1, id(ebo))
    glfw.terminate()
Exemplo n.º 26
0
 def update(self):
     center = Matrix44.from_translation(self.target)
     azim = Matrix44.from_z_rotation(self.azimuth)
     elev = Matrix44.from_x_rotation(self.elevation)
     dist = Matrix44.from_translation([0, 0, self.distance])
     self.mat_lookat = center * azim * elev * dist
Exemplo n.º 27
0
proj = Matrix44.perspective_projection(45.0, width / height, 0.1, 1000.0)
lookat = Matrix44.look_at(
    (2, 2, 1),  # eye / camera position
    (0.0, 0.0, 0.0),  # lookat
    (0.0, 0.0, 1.0),  # camera up vector
)

import matplotlib.pyplot as plt

f, axarr = plt.subplots(1, 13, sharex=True, sharey=True, figsize=(20, 2))

base_light = np.array((100, 100, 100))

for rot in np.arange(0, 6.1, 0.5):
    fbo.clear(0.0, 0.0, 0.0, 0.0)
    rotate = np.array(Matrix44.from_z_rotation(rot))

    # this keep the light in place
    prog['Lights'].value = tuple(
        np.matmul(rotate[:3, :3], base_light).reshape(1, -1)[0])
    # prog['Lights'].value = (10, 10, 10)

    prog['Mvp'].write((proj * lookat * rotate).astype('f4').tobytes())

    for vb, color in zip(vertex_buffers, FACE_COLORS):
        prog['Color'].value = color
        vb.render(moderngl.TRIANGLES)

    img = Image.frombytes('RGB', fbo.size, fbo.read(), 'raw', 'RGB', 0, -1)

    # plt.subplot(171 + (rot * 2))
Exemplo n.º 28
0
    def render(self, time, frame_time):

        # Move our camera depending on keybinds
        self.move_camera()

        # Black background, turn on depth
        self.ctx.clear(0.0, 0.0, 0.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        # Set our world scale for tessellation
        self.scale.write(np.float32(self.camera.scale).astype('f4').tobytes())  # pylint: disable=too-many-function-args

        # Put projection and look-at matrix into uniform
        self.mvp.write((self.camera.mat_projection *
                        self.camera.mat_lookat).astype('f4').tobytes())

        # Setup time, camera_position into shaders
        self.time.write(np.float32(time * 0.2).astype('f4').tobytes())  # pylint: disable=too-many-function-args
        self.camera_position.write(
            self.camera.camera_position.xy.astype('f4').tobytes())

        # Tessellate that floor!
        self.vao.render(moderngl.PATCHES)

        # ZEBRA TIME
        # Put in projection, camera position (which we call light for some reason?), and the time
        self.zmvp.write((self.camera.mat_projection *
                         self.camera.mat_lookat).astype('f4').tobytes())
        self.zlight.write((self.camera.camera_position).astype('f4').tobytes())
        self.ztime.write(np.float32(time * 0.2).astype('f4').tobytes())  # pylint: disable=too-many-function-args

        self.zuse.write(np.float32(self.zebraTime).astype('f4').tobytes())  # pylint: disable=too-many-function-args

        if not self.zebraTime:
            # Make the car look forwards properly
            wheresMyCar = Matrix44.from_translation([0, 0, -0.02])
            wheresMyCar = Matrix44.from_x_rotation(np.pi) * wheresMyCar
            wheresMyCar = Matrix44.from_z_rotation(
                (np.pi / 2) - self.camera.angle) * wheresMyCar
            # Put that movement into the shader
            self.zrotate.write((wheresMyCar).astype('f4').tobytes())

            # Set our texture, then render every part of the car with the right color
            self.car["texture"].use()
            for i in self.carDict:
                color = self.carDict[i]
                self.zcolor.write(np.array(color).astype('f4').tobytes())
                self.car[i]["vao"].render()

        else:
            # We need to get our zebra looking the right way and also slightly lower than where he starts
            rotateMyZebra = Matrix44.from_translation([0, -0.05, 0])
            rotateMyZebra = Matrix44.from_x_rotation(np.pi / 2) * rotateMyZebra
            rotateMyZebra = Matrix44.from_z_rotation(
                (np.pi / 2) - self.camera.angle) * rotateMyZebra
            # Put that movement into the shader
            self.zrotate.write((rotateMyZebra).astype('f4').tobytes())

            # Show us the zebra!
            self.texture.use()
            self.vao2.render()
Exemplo n.º 29
0
 def rotate_z(self, angle):
     self._rotation *= Matrix44.from_z_rotation(angle)
     self._update_uniforms()
Exemplo n.º 30
0
 def angle(self, val):
     self._angle = val
     self._rm = Matrix44.from_z_rotation(self._angle)
     self.dirty = True
Exemplo n.º 31
0
    def render(self, time: float, _frame_time: float):
        # pass 0: clear buffers
        self.ctx.clear(1.0, 1.0, 1.0)
        self.ctx.enable(moderngl.DEPTH_TEST)

        cam_proj = Matrix44.perspective_projection(45.0, self.aspect_ratio,
                                                   0.1, 1000.0)
        cam_look_at = Matrix44.look_at(
            (47.697, -8.147, 24.498),
            (0.0, 0.0, 8.0),
            (0.0, 0.0, 1.0),
        )
        cam_rotate = Matrix44.from_z_rotation(np.sin(time) * 0.5 + 0.2)
        cam_mvp = cam_proj * cam_look_at * cam_rotate
        self.mvp.write(cam_mvp.astype('f4').tobytes())

        # build light camera
        light_rotate = Matrix44.from_z_rotation(time)
        light_pos = light_rotate * Vector3((-60.69, -40.14, 52.49))
        self.light.value = tuple(light_pos)
        light_look_at = Matrix44.look_at(
            light_pos,
            target=(0, 0, 0),
            up=(0.0, 0.0, 1.0),
        )
        # light projection matrix (scene dependant)
        light_proj = Matrix44.perspective_projection(
            fovy=90.0 / 4,  # smaller value increase shadow precision
            aspect=self.wnd.aspect_ratio,
            near=60.0,
            far=100.0)
        # light model view projection matrix
        mvp_light = light_proj * light_look_at
        bias_matrix = (Matrix44.from_translation(
            (0.5, 0.5, 0.5), dtype='f4') * Matrix44.from_scale(
                (0.5, 0.5, 0.5), dtype='f4'))
        mvp_depth_bias = bias_matrix * mvp_light
        # send uniforms to shaders
        self.mvp_depth.write(mvp_depth_bias.astype('f4').tobytes())
        self.mvp_shadow.write(mvp_light.astype('f4').tobytes())

        # pass 1: render shadow-map (depth framebuffer -> texture) from light view
        self.fbo_depth.use()
        self.fbo_depth.clear(1.0, 1.0, 1.0)
        # https://moderngl.readthedocs.io/en/stable/reference/context.html?highlight=culling#moderngl.Context.front_face
        # clock wise -> render back faces
        self.ctx.front_face = 'cw'
        for vao_shadow in self.objects_shadow.values():
            vao_shadow.render()

        # pass 2: render the scene and retro project depth shadow-map
        # counter clock wise -> render front faces
        self.ctx.front_face = 'ccw'
        self.use_color_texture.value = False

        self.ctx.screen.use()
        self.sampler_depth.use(location=0)
        self.tex_depth.use(location=0)

        # pass 2a: render colored scene with shadow
        for object_name, object_color in (
            ("ground", (0.67, 0.49, 0.29)),
            ("grass", (0.46, 0.67, 0.29)),
            ("billboard", (1.0, 1.0, 1.0)),
            ("billboard-holder", (0.2, 0.2, 0.2)),
        ):
            self.color.value = object_color
            self.objects[object_name].render()
        # pass 2b: render textured scene with shadow
        self.use_color_texture.value = True
        self.objects['billboard-image'].render()
Exemplo n.º 32
0
	def renderSceneFromEye(self, fbo_curr, eEyePos):
		fbo_curr.use()

		fbo_curr.clear(1.0, 1.0, 1.0, 1.0)

		'''
		if self.fbo_left == fbo_curr:
			fbo_curr.clear(0.32, 0.0, 0.0, 1.0)
		else:
			fbo_curr.clear(0.0, 0.0, 0.32, 1.0)
		'''

		ipd_translate = None
		if eyePosition.LEFT == eEyePos:
			ipd_translate = Matrix44.from_translation(Vector4([ 0.0, 5.0, 0.0, 1.0]))
		elif eyePosition.RIGHT == eEyePos:
			ipd_translate = Matrix44.from_translation(Vector4([ 0.0, -5.0, 0.0, 1.0]))
		else:
			ipd_translate = Matrix44.from_translation(Vector4([ 0.0, 0.0, 0.0, 1.0]))

		self.ctx.enable(moderngl.DEPTH_TEST)

		'''
		self.mvp_sample.write((self.proj_sample * self.lookat_sample).astype('f4').tobytes())

		self.texture_sample.use()
		self.vao_sample.render(moderngl.TRIANGLE_STRIP)
		'''

		time_sample = time.clock() - self.start_time
		rotate = Matrix44.from_z_rotation(np.sin(time_sample*10.0) * 0.5 + 0.2)

		self.bUseTexture_sample.value = False

		self.light_sample.value = (67.69, -8.14, 52.49)

		if visualMode.STEREO == self.eVisualMode:
			self.mvp_sample.write((self.proj_sample_stereo * self.lookat_sample * ipd_translate * rotate).astype('f4').tobytes())

		else:
			self.mvp_sample.write((self.proj_sample * self.lookat_sample * ipd_translate * rotate).astype('f4').tobytes())

		#self.mvp_sample.write((self.proj_sample * self.lookat_sample * ipd_translate).astype('f4').tobytes())
		#self.mvp_sample.write((self.proj_sample * self.lookat_sample).astype('f4').tobytes())
		#self.mvp_sample.write((self.proj_sample * ipd_translate * rotate).astype('f4').tobytes())

		self.color_sample.value = (0.67, 0.49, 0.29)
		self.objects['ground'].render()

		self.color_sample.value = (0.46, 0.67, 0.29)
		self.objects['grass'].render()

		self.color_sample.value = (1.0, 1.0, 1.0)
		self.objects['billboard'].render()

		self.color_sample.value = (0.2, 0.2, 0.2)
		self.objects['billboard-holder'].render()

		self.bUseTexture_sample.value = True
		self.texture_sample.use()

		self.objects['billboard-image'].render()
Exemplo n.º 33
0
vertices = np.dstack([x, y, z])
print(vertices.shape)

vbo = ctx.buffer(vertices.astype('f4').tobytes())
vao = ctx.simple_vertex_array(prog, vbo, 'in_vert')

width = 512
height = 512

ctx.enable(moderngl.DEPTH_TEST)
fbo = ctx.simple_framebuffer((width, height))
fbo.use()
fbo.clear(1.0, 1.0, 1.0, 1.0)

proj = Matrix44.perspective_projection(45.0, width / height, 0.1, 1000.0)
lookat = Matrix44.look_at(
    (0, 1, 3),  # eye / camera position
    (0.0, 0.0, 0.0),  # lookat
    (0.0, 0.0, 1.0),  # camera up vector
)

rotate = Matrix44.from_z_rotation(np.sin(0) * 0.5 + 0.2)

prog['Mvp'].write((proj * lookat * rotate).astype('f4').tobytes())
# prog['Light'].value = (67.69, -8.14, 52.49)
prog['Color'].value = (1, 0, 0)
vao.render(moderngl.LINE_STRIP)

Image.frombytes('RGB', fbo.size, fbo.read(), 'raw', 'RGB', 0, -1).show()
Exemplo n.º 34
0
 def rotate(self, angle):
     self._angle += angle
     self._rm = Matrix44.from_z_rotation(self._angle)
     self.dirty = True
Exemplo n.º 35
0
 def rotate_z(self, angle):
     """Helper function that multiplies the `model_matrix` with a rotation
     matrix around the z axis."""
     m = Matrix44.from_z_rotation(angle)
     self.model_matrix = m.dot(self.model_matrix)