Beispiel #1
0
 def __init__(self):
     self.window = cube.system.create_window("Test mesh", 640, 480, cube.gl.renderer.Name.OpenGL)
     w = h = 1
     m = Mesh()
     m.mode = Mode.quads
     m.append(
         Kind.vertex,
         vec3f(0, 0, 0),
         vec3f(w, 0, 0),
         vec3f(w, 0, h),
         vec3f(0, 0, h),
         # vec3f(w, h, 0),
         # vec3f(-w, h, 0),
         # vec3f(-w, -h, 0),
         # vec3f(w, -h, 0),
         Kind.color,
         col3f("whitesmoke"),
         col3f("whitesmoke"),
         col3f("whitesmoke"),
         col3f("#000042"),
     )
     print(m)
     r = self.window.renderer
     self.view = m.view(r)
     self.shader = r.new_shader_program(
         [r.new_vertex_shader([vertex_shader]), r.new_fragment_shader([fragment_shader])]
     )
     self.running = False
     self.window.inputs.on_quit.connect(self.stop)
     self.window.inputs.on_resize.connect(self._on_resize)
     self.window.poll()
     self._on_resize(640, 480)
Beispiel #2
0
def create(game):
    mat = gl.Material('player')

    def rand_color():
        import random
        return gl.col3f(random.random(), random.random(), random.random())

    mat.ambient = rand_color()  #gl.col3f(0.2, 0.2, 0.2)
    #mat.diffuse = gl.col3f('black')
    #mat.specular = gl.col3f('black')
    mat.opacity = .5
    mesh = gl.Spheref(gl.vec3f(0), 1).drawable(game.renderer)
    light = game.renderer.new_light(
        gl.PointLightInfo(
            gl.vec3f(0, 8, -1),
            gl.Color3f("#888"),
            gl.Color3f("#333"),
        ))
    player = game.entity_manager.create('player')
    player.add_component(
        Transform(gl.matrix.translate(gl.mat4f(), gl.vec3f(0, .9, 0)),
                  name='position'), )
    player.add_component(Bindable(light, name='light'))
    player.add_component(Bindable(mat, name='material'))
    player.add_component(Drawable(mesh))
    #def change_colors(ev, delta):
    #    mat.ambiant = rand_color()
    #player.add_component(Controller(change_colors, ['tick']))
    return player
    def test_texture_raw(self, painter):
        material = Material()
        import os

        texture = self.renderer.new_texture(
            gl.Surface(Path(os.path.join(os.path.dirname(__file__), "material_test.bmp")))
        )
        texture.generate_mipmap()
        texture.mag_filter(gl.TextureFilter.linear)
        texture.min_filter_bilinear(gl.TextureFilter.linear)
        material.add_texture(
            texture,
            gl.TextureType.ambient,
            gl.TextureMapping.uv,
            gl.StackOperation.add,
            gl.TextureMapMode.wrap,
            gl.BlendMode.basic,
        )
        cube_view = self.cube.drawable(self.renderer)
        painter.state.look_at(gl.vec3f(0, 0.8, -3), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0))
        painter.state.perspective(angle.deg(35), 200 / 200, 0.005, 30.0)
        painter.state.rotate(angle.deg(42), gl.vec3f(1, 1, 0))
        self.deg += 1
        with painter.bind([material.bindable(self.renderer)]):
            painter.draw([cube_view])
Beispiel #4
0
 def __init__(self, window, directory):
     super().__init__(window, directory, bindings = self.bindings)
     #self.ground = ground.create(self)
     self.player = player.create(self)
     self.darklings = [
         darkling.create(self, x, y) for x, y in [
             (-5, 0),
             (-5, -10),
             (5, 0),
             (5, -10),
         ]
     ]
     self.camera = gl.Camera()
     self.camera.position = gl.vec3f(.5, 10, 10)
     self.camera.look_at(gl.vec3f(0, 0, -40))
     self.camera.init_frustum(
         units.deg(45), self.window.width / self.window.height, 0.005, 300.0
     )
     self.__bind_camera_controls()
     self.scene_view = self.scene.drawable(self.renderer)
     self.world = cubeapp.world.World(
         storage = cubeapp.world.Storage(),
         generator = cubeapp.world.Generator(),
         renderer = cubeapp.world.Renderer(self.renderer),
     )
     self.referential = cubeapp.world.world.coord_type()
     self.__has_focus = False
     self.window.inputs.on_mousedown.connect(self.__enter)
     self.__enter()
     self.world.start(self.camera, self.referential)
Beispiel #5
0
def create(game):
    mat = gl.Material('player')
    def rand_color():
        import random
        return gl.col3f(random.random(), random.random(), random.random())
    mat.ambient = rand_color() #gl.col3f(0.2, 0.2, 0.2)
    #mat.diffuse = gl.col3f('black')
    #mat.specular = gl.col3f('black')
    mat.opacity = .5
    mesh = gl.Spheref(gl.vec3f(0), 1).drawable(game.renderer)
    light = game.renderer.new_light(
        gl.PointLightInfo(
            gl.vec3f(0, 8, -1),
            gl.Color3f("#888"),
            gl.Color3f("#333"),
        )
    )
    player = game.entity_manager.create('player')
    player.add_component(
        Transform(
            gl.matrix.translate(gl.mat4f(), gl.vec3f(0, .9, 0)),
            name = 'position'
        ),
    )
    player.add_component(Bindable(light, name = 'light'))
    player.add_component(Bindable(mat, name = 'material'))
    player.add_component(Drawable(mesh))
    #def change_colors(ev, delta):
    #    mat.ambiant = rand_color()
    #player.add_component(Controller(change_colors, ['tick']))
    return player
Beispiel #6
0
 def __init__(self, window, directory):
     super().__init__(window, directory, bindings=self.bindings)
     #self.ground = ground.create(self)
     self.player = player.create(self)
     self.darklings = [
         darkling.create(self, x, y) for x, y in [
             (-5, 0),
             (-5, -10),
             (5, 0),
             (5, -10),
         ]
     ]
     self.camera = gl.Camera()
     self.camera.position = gl.vec3f(.5, 10, 10)
     self.camera.look_at(gl.vec3f(0, 0, -40))
     self.camera.init_frustum(units.deg(45),
                              self.window.width / self.window.height, 0.005,
                              300.0)
     self.__bind_camera_controls()
     self.scene_view = self.scene.drawable(self.renderer)
     self.world = cubeapp.world.World(
         storage=cubeapp.world.Storage(),
         generator=cubeapp.world.Generator(),
         renderer=cubeapp.world.Renderer(self.renderer),
     )
     self.referential = cubeapp.world.world.coord_type()
     self.__has_focus = False
     self.window.inputs.on_mousedown.connect(self.__enter)
     self.__enter()
     self.world.start(self.camera, self.referential)
Beispiel #7
0
def power_matrix(shape):
    return gl.matrix.scale(
        gl.matrix.translate(
          gl.mat4f(),
            gl.vec3f(shape.x, shape.y - shape.h, -.2)
        ),
        gl.vec3f(shape.w, shape.h, 1)
    )
Beispiel #8
0
 def setUp(self):
     fov = deg(45.0)
     ratio = 640 / 480
     near_dist = 1
     far_dist = 300
     self.frustum = frustum.Frustumil(fov, ratio, near_dist, far_dist)
     up = vec3f(0,1,0)
     front = vec3f(0,0,-1)
     self.frustum.update(front, up)
Beispiel #9
0
 def test_init(self):
     c = Camera()
     self.assertEqual(c.pitch, angle.rad(0))
     self.assertEqual(c.yaw, angle.rad(0))
     self.assertEqual(c.roll, angle.rad(0))
     self.assertEqual(c.position, gl.vec3f())
     self.assertFalse(c.has_frustum)
     self.assertEqual(c.right, gl.vec3f(1, 0, 0))
     self.assertEqual(c.front, gl.vec3f(0, 0, -1))
     self.assertEqual(c.up, gl.vec3f(0, 1, 0))
Beispiel #10
0
 def __call__(self, ev, delta):
     #print("SET POS", ev.channel.name, ev.pos, ev.power, self.player.pos)
     if ev.channel == 'move-player':
         print("MOVE", ev.key)
         self.player.impulsion = {
             'right': gl.vec3f(1, 0, 0),
             'up': gl.vec3f(0, -1, 0),
             'left': gl.vec3f(-1, 0, 0),
             'down': gl.vec3f(0, 1, 0),
         }[ev.key] * 2000
         return
Beispiel #11
0
 def test_transform(self, painter):
     with painter.bind([self.shader, self.vb]):
         painter.state.model = matrix.scale(
             painter.state.model,
             gl.vec3f(0.5, 0.5, 0.5)
         )
         painter.state.model = matrix.translate(
             painter.state.model,
             gl.vec3f(100, 75, 0)
         )
         self.shader['cube_MVP'] = painter.state.mvp
         painter.draw_elements(DrawMode.quads, self.indices, 0, 4)
Beispiel #12
0
 def render(self):
     new_time = time.time()
     self.title.text = "%.2f ms" % ((new_time - self.last_time) * 1000)
     self.last_time = new_time
     with self.renderer.begin(gl.mode_3d) as painter:
         painter.state.look_at(
             gl.vec3f(0,0,-10), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0)
         )
         painter.state.perspective(
             units.deg(45), self.window.width / self.window.height, 0.005, 300.0
         )
         with painter.bind([self.light]):
             painter.draw([self.scene_view])
Beispiel #13
0
 def __init__(self, renderer):
     self.renderer = renderer
     self.__materials = {}
     for lod in range(8):
         mat = gl.Material('ground-%s' % lod)
         mat.ambient = gl.col3f('#' + ('%s' % (lod + 1)) * 3)
         self.__materials[lod] = mat.bindable(renderer)
     mesh = gl.Mesh()
     mesh.mode = gl.DrawMode.quads
     size = 16
     step = 1.0 / size
     for i in (i / size for i in range(size)):
         x = i
         for j in (i / size for i in range(size)):
             y = 1.0 - j
             mesh.kind = gl.ContentKind.vertex
             mesh.append(gl.vec3f(x, 0, y - step))
             mesh.append(gl.vec3f(x, 0, y))
             mesh.append(gl.vec3f(x + step, 0, y))
             mesh.append(gl.vec3f(x + step, 0, y - step))
             mesh.kind = gl.ContentKind.tex_coord0
             mesh.append(gl.vec2f(i, j + step))
             mesh.append(gl.vec2f(i + step, j + step))
             mesh.append(gl.vec2f(i + step, j))
             mesh.append(gl.vec2f(i, j))
             mesh.kind = gl.ContentKind.normal
             mesh.append(gl.vec3f(0, 1, 0))
             mesh.append(gl.vec3f(0, 1, 0))
             mesh.append(gl.vec3f(0, 1, 0))
             mesh.append(gl.vec3f(0, 1, 0))
     self.mesh = mesh.drawable(self.renderer)
     self.__chunks = {}
Beispiel #14
0
    def test_sphere(self, painter):
        s = scene.from_string("s 0 0 0 1", "nff")
        self.assertIsNotNone(s)
        self.assertEqual(len(s.meshes), 1)
        self.assertEqual(len(s.materials), 1)
        mesh = s.meshes[0]
        mat = s.materials[0]
        self.assertIsNotNone(mesh)
        self.assertIsNotNone(mat)
        mat.ambient = gl.Color3f("white")

        painter.state.look_at(gl.vec3f(0, 0.8, -3), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0))
        painter.state.perspective(angle.deg(45), 200 / 200, 0.005, 30.0)
        with painter.bind([mat.bindable(self.renderer)]):
            painter.draw([mesh.drawable(self.renderer)])
Beispiel #15
0
def create(game, x, z):
    mat = gl.Material('player')
    mat.ambient = gl.col3f('#100')
    mat.diffuse = gl.col3f('#f55')
    mat.specular = gl.col3f('#f00')
    mat.shininess = .5
    mat.shading_model = gl.material.ShadingModel.gouraud

    mesh = gl.Spheref(gl.vec3f(0), 1).drawable(game.renderer)

    entity = game.entity_manager.create('Darkling')
    transform = entity.add_component(
        Transform(gl.matrix.translate(gl.mat4f(), gl.vec3f(x, 1, z))))
    entity.add_component(Bindable(mat))
    entity.add_component(Drawable(mesh))
    return entity
Beispiel #16
0
 def test_cube(self, painter):
     material = Material()
     material.add_color(
         gl.ShaderParameterType.vec3,
         StackOperation.add
     )
     cube_view = self.cube.drawable(self.renderer)
     painter.state.look_at(
         gl.vec3f(0, .8, -3), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0)
     )
     painter.state.perspective(
         angle.deg(35), 200 / 200, 0.005, 30.0
     )
     painter.state.rotate(angle.deg(32), gl.vec3f(0, 1, 0))
     with painter.bind([material.bindable(self.renderer)]):
         painter.draw([cube_view])
Beispiel #17
0
    def test_parameter(self):
        self.vs = self.renderer.new_vertex_shader([
            """
            uniform mat4 mat44f;
            uniform vec3 vec3f;
            uniform float floats[4];
            uniform float floats2[4];
            void main(void)
            {
               gl_FrontColor = gl_Color;
               for (int i = 0; i < 4; i++)
                   gl_FrontColor.r *= floats[i] + floats2[i];
               gl_Position = mat44f * vec4(vec3f, 0);
            }
            """
        ])
        self.fs = self.renderer.new_fragment_shader(["""
            void main(void)
            {
                gl_FragColor = gl_Color;
            }
        """])

        shader = self.renderer.new_shader_program([self.vs, self.fs])
        shader["vec3f"] = vec3f()
        shader["mat44f"] = mat4f()
        shader["floats"] = 12.0
        shader["floats"][1] = 12.0
        shader["floats"][0] = 12.0
Beispiel #18
0
def create(game, x, z):
    mat = gl.Material('player')
    mat.ambient = gl.col3f('#100')
    mat.diffuse = gl.col3f('#f55')
    mat.specular = gl.col3f('#f00')
    mat.shininess = .5
    mat.shading_model = gl.material.ShadingModel.gouraud

    mesh = gl.Spheref(gl.vec3f(0), 1).drawable(game.renderer)

    entity = game.entity_manager.create('Darkling')
    transform = entity.add_component(
        Transform(gl.matrix.translate(gl.mat4f(), gl.vec3f(x, 1, z)))
    )
    entity.add_component(Bindable(mat))
    entity.add_component(Drawable(mesh))
    return entity
Beispiel #19
0
    def test_look_at(self):
        m = gl.mat4f(self.s.model)
        v = gl.mat4f(self.s.view)
        p = gl.mat4f(self.s.projection)
        mvp = gl.mat4f(self.s.mvp)

        self.assertEqual(m, self.s.model)
        self.assertEqual(v, self.s.view)
        self.assertEqual(p, self.s.projection)
        self.assertEqual(mvp, self.s.mvp)

        self.s.look_at(gl.vec3f(0,0,0), gl.vec3f(1,2,3), gl.vec3f(0, 1, 0))

        self.assertEqual(m, self.s.model)
        self.assertNotEqual(v, self.s.view)
        self.assertEqual(p, self.s.projection)
        self.assertNotEqual(mvp, self.s.mvp)
Beispiel #20
0
 def __render_size(self, size, material, chunks, referential, painter, state):
     for chunk in chunks:
         origin = chunk.node.origin - referential
         if origin.y != 0: continue
         state.model = gl.matrix.scale(
             gl.matrix.translate(
                 gl.mat4f(),
                 gl.vec3f(
                     origin.x * chunk.size,
                     origin.y * chunk.size,
                     origin.z * chunk.size
                 )
             )
             , gl.vec3f(chunk.node.size * chunk.size)
         )
         with painter.bind([material]):
             painter.draw([self.mesh])
Beispiel #21
0
    def test_paint(self, painter):
        m = Mesh()
        m.mode = gl.DrawMode.quads
        m.append(gl.vec3f(0, 0, 0))
        m.append(gl.vec3f(0, 100, 0))
        m.append(gl.vec3f(100, 100, 0))
        m.append(gl.vec3f(100, 0, 0))
        m.kind = gl.ContentKind.color
        m.append(gl.Color3f("red"))
        m.append(gl.Color3f("blue"))
        m.append(gl.Color3f("green"))
        m.append(gl.Color3f("gray"))

        view = m.drawable(self.renderer)

        with painter.bind([self.shader]):
            self.shader['cube_MVP'] = painter.state.mvp
            painter.draw([view])
Beispiel #22
0
 def render(self):
     with self.renderer.begin(gl.mode_3d) as painter:
         painter.state.projection = self.projection_matrix
         painter.state.model = gl.matrix.look_at(
             self.player.camera.position,
             self.player.camera.position + self.player.camera.front,
             gl.vec3f(0, 1, 0)
         )
         self.world.render(painter)
Beispiel #23
0
    def __call__(self, ev, delta):
        tiles = pos_to_tiles(self.board, ev.new, ev.player.radius)
        ev.player.force = gl.vec3f(0)
        self.current_tiles = tiles
        colliding = []
        for tile in tiles:
            controllers = self.cells.get(tile, [])
            for controller in controllers:
                controller(self.board, tile, ev.player, colliding)

        for tile in self.last_colliding:
            if tile not in colliding:
                self.cells.get(tile)[0].prepare(self.board, tile)
        self.last_colliding = colliding
        tile_w, tile_h = self.board.tile_width, self.board.tile_height
        border = gl.vec2f(self.board.border, self.board.border)
        for i, tile in enumerate(colliding):
            self.cells.get(tile)[0].set_color(self.board, tile, gl.col3f('purple'))
            tile_pos = gl.vec2f(tile.x * tile_w, tile.y * tile_h) + border
            print("PIF!", i, ev.new, tile, tile_pos, self.board.border,
                  tile_w, tile_h)
            if ev.new.x >= tile_pos.x and \
               ev.new.x < tile_pos.x + tile_w:
                if ev.new.y + ev.player.radius >= tile_pos.y \
                   and ev.new.y < tile_pos.y + tile_h:
                    print("YEAH!", i, ev.new, tile, tile_pos, self.board.border,
                          tile_w, tile_h)
                    if ev.player.velocity.y > 0:
                        ev.player.velocity.y *= -.5
                    if abs(ev.player.velocity.y) < 50:
                        ev.player.force = -ev.player.gravity
                        ev.player.velocity.y = 0
                        ev.player.velocity.x *= .9
                        if abs(ev.player.velocity.x) < 5:
                            ev.player.velocity.x = 0
                    ev.player.pos.y = tile_pos.y - ev.player.radius
                elif ev.new.y - ev.player.radius <= tile_pos.y + tile_h and \
                     ev.new.y > tile_pos.y:
                    print("BIM")
                    if ev.player.velocity.y < 0:
                        ev.player.velocity.y *= -1
                    ev.player.pos.y = tile_pos.y + tile_h + ev.player.radius
            if ev.new.y >= tile_pos.y and \
               ev.new.y < tile_pos.y + tile_h:
                if ev.new.x > ev.old.x and \
                   ev.new.x + ev.player.radius >= tile_pos.x and \
                   ev.new.x < tile_pos.x + tile_w:
                    if ev.player.velocity.x > 0:
                        ev.player.velocity.x *= -.9
                    ev.player.pos.x = tile_pos.x - ev.player.radius
                elif ev.new.x - ev.player.radius <= tile_pos.x + tile_w and \
                     ev.new.x > tile_pos.x:
                    if ev.player.velocity.x < 0:
                        ev.player.velocity.x *= -.9
                    ev.player.pos.x = tile_pos.x + tile_w + ev.player.radius
Beispiel #24
0
    def setUp(self):
        self.window = create_window(
            "PainterSetup", 200, 200, WindowFlags.hidden, Name.OpenGL
        )
        self.renderer = self.window.renderer
        # Should be created before any shader
        self.target = self.renderer.context.new_render_target()

        gen = self.renderer.generate_shader(gl.ShaderType.vertex)
        for i in self.vs_inputs: gen.input(*i)
        for o in self.vs_outputs: gen.output(*o)
        for p in self.vs_parameters: gen.parameter(*p)
        self.vs = gen.routine(self.VSRoutine, "main").shader()

        gen = self.renderer.generate_shader(gl.ShaderType.fragment)
        for i in self.fs_inputs: gen.input(*i)
        for o in self.fs_outputs: gen.output(*o)
        for p in self.fs_parameters: gen.parameter(*p)
        self.fs = gen.routine(self.FSRoutine, "main").shader()

        x, y, w, h = (
            11, 42,
            120, 140
        )
        self.shader = self.renderer.new_shader_program([self.fs, self.vs])
        self.vb = self.renderer.new_vertex_buffer([
            gl.make_vba(
                gl.ContentKind.vertex,
                list(gl.vec3f(*v) for v in [
                    (x, y, 0),
                    (x, y + h, 0),
                    (x + w, y + h, 0),
                    (x + w, y, 0),
                ]),
                gl.ContentHint.static_content
            ),
            make_vba(
                ContentKind.color,
                [
                    Color3f('#e00'),
                    Color3f('#9cd'),
                    Color3f('#ffc'),
                    Color3f('#00f'),
                ],
                ContentHint.static_content
            )
        ])
        self.indices = self.renderer.new_index_buffer(
            make_vba(
                ContentKind.index,
                [ 0, 1, 2, 3],
                ContentHint.static_content
            )
        )
    def test_texture(self, painter):
        material = Material()
        material.add_color(gl.ShaderParameterType.vec3, gl.StackOperation.add)
        import os

        material.add_texture(
            os.path.join(os.path.dirname(__file__), "material_test.bmp"),
            gl.TextureType.ambient,
            gl.TextureMapping.uv,
            gl.StackOperation.add,
            gl.TextureMapMode.wrap,
            gl.BlendMode.basic,
        )
        cube_view = self.cube.drawable(self.renderer)
        painter.state.look_at(gl.vec3f(0, 0.8, -3), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0))
        painter.state.perspective(angle.deg(35), 200 / 200, 0.005, 30.0)
        painter.state.rotate(angle.deg(42), gl.vec3f(1, 1, 0))
        self.deg += 1
        with painter.bind([material.bindable(self.renderer)]):
            painter.draw([cube_view])
Beispiel #26
0
 def test_update_ambiant(self, painter):
     material = Material()
     material.ambiant = gl.col3f(1,0,0)
     mesh = gl.Spheref(gl.vec3f(0), 1).drawable(self.renderer)
     painter.state.look_at(
         gl.vec3f(0, .8, 10), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0)
     )
     painter.state.perspective(
         angle.deg(35), 200 / 200, 0.005, 30.0
     )
     bindable = material.bindable(self.renderer)
     s = painter.push_state()
     s.translate(1, 0, 0)
     with painter.bind([bindable]):
         painter.draw([mesh])
     painter.pop_state()
     s = painter.push_state()
     s.translate(-1, 0, 0)
     material.ambiant = gl.col3f(0, 1, 1)
     with painter.bind([bindable]):
         painter.draw([mesh])
Beispiel #27
0
 def test_render_color0(self, painter):
     material = Material()
     material.add_color(
         gl.ShaderParameterType.vec3,
         StackOperation.add
     )
     painter.state.translate(100, 100, 0)
     painter.state.scale(100, 100, 0)
     painter.state.rotate(angle.deg(20), gl.vec3f(1, 1, 0))
     cube_view = self.cube.drawable(self.renderer)
     with painter.bind([material.bindable(self.renderer)]):
         painter.draw([cube_view])
Beispiel #28
0
    def test_sphere_light(self, painter):
        s = scene.from_string("s 0 0 0 1", "nff")
        self.assertIsNotNone(s)
        self.assertEqual(len(s.meshes), 1)
        self.assertEqual(len(s.materials), 1)
        mesh = s.meshes[0]
        mat = s.materials[0]
        self.assertIsNotNone(mesh)
        self.assertIsNotNone(mat)
        mat.ambient = gl.Color3f("#222")
        mat.shading_model = gl.material.ShadingModel.gouraud
        mat.diffuse = gl.Color3f("white")
        mat.specular = gl.Color3f("white")
        mat.shininess = 3

        painter.state.look_at(gl.vec3f(0, 0.8, -3), gl.vec3f(0, 0, 0), gl.vec3f(0, 1, 0))
        painter.state.perspective(angle.deg(45), 200 / 200, 0.005, 30.0)
        light = self.renderer.new_light(
            gl.PointLightInfo(gl.vec3f(5, -1, 0), gl.Color3f("black"), gl.Color3f("#0f0f0f"))
        )
        with painter.bind([light, mat.bindable(self.renderer)]):
            painter.draw([mesh.drawable(self.renderer)])
Beispiel #29
0
def create(entity_manager, event_manager, renderer, initial_player_pos=(0, 0)):
    s = """
tess 6
shader img/rabbit.tif
s 1.0 -4.0 2.0 4.0 20 20
    """
    sc = scene.from_string(s, "nff")
    mesh = sc.meshes[0]
    mat = sc.materials[0]
    light = renderer.new_light(
        gl.PointLightInfo(
            gl.vec3f(0, 8, -1),
            gl.Color3f("#888"),
            gl.Color3f("#333"),
        ))
    #mat.textures[0].texture.generate_mipmap()

    player = entity_manager.create(
        'player',
        velocity=gl.vec3f(0),
        gravity=gl.vec3f(0, 1000, 0),
        force=gl.vec3f(0),
        impulsion=gl.vec3f(0),
        radius=30,
    )
    player.pos = initial_player_pos

    transform = player.add_component(
        Transform(player_matrix(player.pos, player.radius)))
    player.add_component(Bindable(mat, name='material'))
    player.add_component(Drawable(mesh))
    player.add_component(Controller(MovePlayer(player, event_manager)))
    player.add_component(
        Controller(AnimatePlayer(
            player=player,
            event_manager=event_manager,
        )))
    return player
Beispiel #30
0
 def __init__(self, cam, mouse, velocity = 40):
     super().__init__()
     self.move_left =  Channel()
     self.move_right = Channel()
     self.move_forward =    Channel()
     self.move_backward =  Channel()
     self.move_up =    Channel(dir = gl.vec3f(0, 1, 0))
     self.move_down =  Channel(dir = gl.vec3f(0, -1, 0))
     self.mouse_move = Channel()
     self.channels = [
         self.move_left,
         self.move_right,
         self.move_up,
         self.move_down,
         self.move_forward,
         self.move_backward,
         self.mouse_move,
         Channel('tick'),
     ]
     self.camera = cam
     self.mouse = mouse
     self.velocity = velocity
     self.dir = gl.vec3f()
Beispiel #31
0
 def __init__(self, cam, mouse, velocity=40):
     super().__init__()
     self.move_left = Channel()
     self.move_right = Channel()
     self.move_forward = Channel()
     self.move_backward = Channel()
     self.move_up = Channel(dir=gl.vec3f(0, 1, 0))
     self.move_down = Channel(dir=gl.vec3f(0, -1, 0))
     self.mouse_move = Channel()
     self.channels = [
         self.move_left,
         self.move_right,
         self.move_up,
         self.move_down,
         self.move_forward,
         self.move_backward,
         self.mouse_move,
         Channel('tick'),
     ]
     self.camera = cam
     self.mouse = mouse
     self.velocity = velocity
     self.dir = gl.vec3f()
Beispiel #32
0
    def __init__(self, window, directory):
        super().__init__(window, directory, bindings=self.bindings)
        self.window.add_font(self.directory / 'FreeMono.ttf')
        self.resource_manager.add_path(str(self.directory / 'resource'))
        document = self.window.load_document(DOCUMENT)
        self.title = document.by_id("title")
        size = gl.vec2u(10, 10)
        border = 5
        self.board = board.load(
            self.directory / 'resource/map/00.txt',
            game=self,
            border=border,
            screen_size=self.window.size,
        )
        self.player = player.create(
            entity_manager=self.entity_manager,
            event_manager=self.event_manager,
            renderer=self.renderer,
            initial_player_pos=gl.vec3f(border + 200, border + 200, 0),
        )
        self.camera = camera.create(entity_manager=self.entity_manager,
                                    initial_player_pos=self.player.pos)
        self.light = self.renderer.new_light(
            gl.PointLightInfo(
                gl.vec3f(0, 2, -1),
                gl.Color3f("#888"),
                gl.Color3f("#333"),
            ))
        self.scene_view = self.scene.drawable(self.renderer)
        self.last_time = time.time()
        window.inputs.on_mousedown.connect(self.__on_mousedown)
        window.inputs.on_mouseup.connect(self.__on_mouseup)

        for key in ('up', 'down', 'left', 'right'):
            slot = getattr(self.input_translator.keyboard, key).key_held
            slot.connect(lambda ev, key=key: self.event_manager.push(
                Event('move-player', key=key)))
Beispiel #33
0
def create(shape, entity_manager):
    mat = gl.Material('power')
    mat.ambient = gl.col3f('#888')
    mat.diffuse = gl.col3f('#000')
    mat.specular = gl.col3f('#000')
    #mat.shininess = 0
    #mat.shading_model = gl.material.ShadingModel.gouraud
    mat.add_color(
        gl.ShaderParameterType.vec3,
        gl.StackOperation.add
    )
    mesh = gl.Mesh()
    mesh.mode = gl.DrawMode.quads
    mesh.kind = gl.ContentKind.vertex
    mesh.append(gl.vec3f(0, 0, 0))
    mesh.append(gl.vec3f(0, 1, 0))
    mesh.append(gl.vec3f(1, 1, 0))
    mesh.append(gl.vec3f(1, 0, 0))
    mesh.kind = gl.ContentKind.color
    mesh.append(gl.col3f('red'))
    mesh.append(gl.col3f('green'))
    mesh.append(gl.col3f('green'))
    mesh.append(gl.col3f('red'))
    mesh.kind = gl.ContentKind.normal
    mesh.append(gl.vec3f(0, 0, 1))
    mesh.append(gl.vec3f(0, 0, 1))
    mesh.append(gl.vec3f(0, 0, 1))
    mesh.append(gl.vec3f(0, 0, 1))
    power = entity_manager.create('power', shape = shape)

    transform = power.add_component(Transform(power_matrix(shape)))
    power.add_component(Bindable(mat))
    power.add_component(Drawable(mesh))

    refill = Controller(Refill(power))

    def start_power(ev, delta):
        power.add_component(refill)
    power.add_component(Controller(start_power, ['start-power']))

    def stop_power(ev, delta):
        power.remove_component(refill)
        power.shape.h = 1
        transform.node.value = power_matrix(power.shape)
    power.add_component(Controller(stop_power, ['stop-power']))

    return power
Beispiel #34
0
    def setUp(self):
        super().setUp()

        x, y, w, h = (
            10, 10,
            180, 180
        )
        self.vb = self.renderer.new_vertex_buffer([
            gl.make_vba(
                gl.ContentKind.vertex,
                [
                    gl.vec3f(x, y, 0),
                    gl.vec3f(x, y + h, 0),
                    gl.vec3f(x + w, y + h, 0),
                    gl.vec3f(x + w, y, 0),
                ],
                gl.ContentHint.static_content
            ),
            gl.make_vba(
                gl.ContentKind.tex_coord0,
                [
                    gl.vec2f(0, 0),
                    gl.vec2f(0, 1),
                    gl.vec2f(1, 1),
                    gl.vec2f(1, 0),
                ],
                gl.ContentHint.static_content
            )
        ])
        self.indices = self.renderer.new_index_buffer(
            gl.make_vba(
                gl.ContentKind.index,
                [ 0, 1, 2, 3],
                gl.ContentHint.static_content
            )
        )
Beispiel #35
0
 def __init__(self, **kw):
     super().__init__(**kw)
     self.window.add_font(self.directory / 'FreeMono.ttf')
     document = self.window.load_document(DOCUMENT)
     self.title = document.by_id("title")
     self.cube = self.create_cube()
     self.light = self.renderer.new_light(
         gl.PointLightInfo(
             gl.vec3f(0, 2, -1),
             gl.Color3f("#888"),
             gl.Color3f("#333"),
         )
     )
     self.scene_view = self.scene.drawable(self.renderer)
     self.last_time = time.time()
Beispiel #36
0
 def test_simple(self):
     m = Mesh()
     data = [
         (0, 0, 0),
         (1, 0, 0),
         (2, 0, 0),
         (0, 1, 0),
         (0, 2, 0),
         (0, 0, 1),
         (0, 0, 2),
     ]
     self.assertEqual(m.kind, gl.ContentKind.vertex)
     self.assertEqual(m.mode, gl.DrawMode.triangle_strip)
     for v in data:
         m.append(gl.vec3f(*v))
     self.assertEqual(str(m), '<Mesh 7 vertice>')
     m.kind = gl.ContentKind.color
     for v in data:
         m.append(gl.Color3f(*v))
     self.assertEqual(str(m), '<Mesh 7 vertice, 7 colors3>')
     m.kind = gl.ContentKind.normal
     for v in data:
         m.append(gl.vec3f(*v))
     self.assertEqual(str(m), '<Mesh 7 vertice, 7 normals, 7 colors3>')
Beispiel #37
0
    def test_no_copy(self):
        self.assertIs(self.s, self.s.scale(1,2,3))
        self.assertIs(self.s, self.s.translate(1,2,3))
        self.assertIs(self.s, self.s.rotate(angle.deg(0), gl.vec3f(1,2,3)))
        self.assertIs(self.s, self.s.look_at(
            gl.vec3f(0,0,0), gl.vec3f(1,2,3), gl.vec3f(0, 1, 0)
        ))
        self.assertIs(self.s, self.s.perspective(angle.deg(45), 1, 31, 32))
        self.assertIs(self.s, self.s.ortho(0, 0, 200, 200))

        self.assertIs(
            self.s,
            self.s.scale(1,2,3).translate(1,2,3).rotate(
                angle.deg(0), gl.vec3f(1,2,3)
            ).look_at(
                gl.vec3f(0,0,0), gl.vec3f(1,2,3), gl.vec3f(0, 1, 0)
            ).perspective(angle.deg(45), 1, 31, 32).ortho(0, 0, 200, 200)
        )
Beispiel #38
0
    def cube(self):
        if self.__cube is not None:
            return self.__cube
        self.__cube = gl.Mesh()

        vertices = [
            (-.5, -.5,  .5),
            (-.5,  .5,  .5),
            (.5,  .5,  .5),
            (.5, -.5,  .5),
            (-.5, -.5, -.5),
            (-.5,  .5, -.5),
            (.5,  .5, -.5),
            (.5, -.5, -.5),
        ]
        colors = [
            (0, 0, 1),
            (1, 0, 0),
            (0, 1, 0),
            (1, 1, 0),
            (1, 1, 1),
            (1, 0, 0),
            (1, 0, 1),
            (0, 0, 1),
        ]
        indices = [
            0,2,1,  0,3,2,
            4,3,0,  4,7,3,
            4,1,5,  4,0,1,
            3,6,2,  3,7,6,
            1,6,5,  1,2,6,
            7,5,6,  7,4,5
        ]
        self.__cube.mode = gl.DrawMode.triangles

        for i in indices:
            self.__cube.kind = gl.ContentKind.vertex
            self.__cube.append(gl.vec3f(*vertices[i]))
            self.__cube.kind = gl.ContentKind.color
            self.__cube.append(gl.Color3f(*colors[i]))

        return self.__cube
Beispiel #39
0
 def __call__(self, ev, elapsed):
     if ev.channel == 'tick':
         if self.dir:
             self.camera.move(self.dir * elapsed * self.velocity)
             self.dir = self.dir * .8
         self.camera.rotate(units.deg(self.mouse.yrel / 10), self.camera.right)
         self.camera.rotate(units.deg(self.mouse.xrel / 10), gl.vec3f(0, 1, 0))
     else:
         if hasattr(ev.channel, 'dir'):
             dir = ev.channel.dir
         else:
             if ev.channel == self.move_left:
                 dir = -self.camera.right
             elif ev.channel == self.move_right:
                 dir = self.camera.right
             elif ev.channel == self.move_forward:
                 dir = self.camera.front
             elif ev.channel == self.move_backward:
                 dir = -self.camera.front
             dir.y = 0
         self.dir = gl.vector.normalize(self.dir + dir)
Beispiel #40
0
 def __call__(self, ev, elapsed):
     if ev.channel == 'tick':
         if self.dir:
             self.camera.move(self.dir * elapsed * self.velocity)
             self.dir = self.dir * .8
         self.camera.rotate(units.deg(self.mouse.yrel / 10),
                            self.camera.right)
         self.camera.rotate(units.deg(self.mouse.xrel / 10),
                            gl.vec3f(0, 1, 0))
     else:
         if hasattr(ev.channel, 'dir'):
             dir = ev.channel.dir
         else:
             if ev.channel == self.move_left:
                 dir = -self.camera.right
             elif ev.channel == self.move_right:
                 dir = self.camera.right
             elif ev.channel == self.move_forward:
                 dir = self.camera.front
             elif ev.channel == self.move_backward:
                 dir = -self.camera.front
             dir.y = 0
         self.dir = gl.vector.normalize(self.dir + dir)
Beispiel #41
0
    def create_cube(self):
        mat = gl.Material('cube')
        mat.ambient = gl.col3f('#100')
        mat.diffuse = gl.col3f('#f55')
        mat.specular = gl.col3f('#f00')
        mat.shininess = 5
        mat.shading_model = gl.material.ShadingModel.gouraud


        mesh =  cube.gl.Cube3f(cube.gl.vec3f(), 1).drawable(self.renderer)

        entity = self.entity_manager.create('Cube')
        transform = entity.add_component(
            Transform(gl.matrix.scale(gl.mat4f(), gl.vec3f(4)))
        )
        entity.add_component(Bindable(mat))
        entity.add_component(Drawable(mesh))
        class Animate:
            channels = ['tick']
            velocity = 10
            def __call__(self, ev, delta):
                transform.node.rotate(units.deg(45) * delta * self.velocity, gl.vec3f(1, .5, 0))
        entity.add_component(Controller(Animate()))
        return entity
Beispiel #42
0
 def render(self):
     new_time = time.time()
     #self.title.text = "%.2f ms" % ((new_time - self.last_time) * 1000)
     self.last_time = new_time
     with self.renderer.begin(gl.mode_2d) as painter:
         #painter.state.look_at(
         #    gl.vec3f(0,0,-1), gl.vec3f(0, 0, 1), gl.vec3f(0, 1, 0)
         #)
         #painter.state.perspective(
         #    units.deg(45), self.window.width / self.window.height, 0.005, 300.0
         #)
         #painter.state.look_at(
         #    gl.vec3f(self.window.width / 2, self.window.height / 2, -800),
         #    gl.vec3f(self.window.width / 2, self.window.height / 2, 0),
         #    gl.vec3f(0, 1, 0)
         #)
         #painter.state.perspective(
         #    units.deg(45), self.window.width / self.window.height, 0.005, 3000.0
         #)
         painter.state.view = gl.matrix.translate(
             gl.mat4f(), -self.camera.pos +
             gl.vec3f(self.window.width / 2, self.window.height / 2, 0))
         with painter.bind([self.light]):
             painter.draw([self.scene_view])
Beispiel #43
0
def player_matrix(pos, radius):
    return gl.matrix.rotate(
        gl.matrix.scale(gl.matrix.translate(gl.mat4f(), pos),
                        gl.vec3f(radius, radius, 1)), units.deg(0),
        gl.vec3f(1, 1, 0))
Beispiel #44
0
def create(game, size, border, tile_width, tile_height, rows):
    mat = gl.Material('ground')
    mat.ambient = gl.col3f('#888')
    mat.diffuse = gl.col3f('#000')
    mat.specular = gl.col3f('#000')
    #mat.shininess = 0
    #mat.shading_model = gl.material.ShadingModel.gouraud
    mat.add_color(
        gl.ShaderParameterType.vec3,
        gl.StackOperation.add
    )
    coords = []
    colors = []
    indices = list(range(size.x * size.y * 4))
    for i in range(size.x):
        x = i * tile_width + border
        for j in range(size.y):
            y = j * tile_height + border
            coords.extend([
                gl.vec3f(x, y, 0),
                gl.vec3f(x, y + tile_height, 0),
                gl.vec3f(x + tile_width, y + tile_height, 0),
                gl.vec3f(x + tile_width, y, 0),
            ])
            colors.extend([
                gl.col3f('#356712'),
                gl.col3f('#356712'),
                gl.col3f('#356712'),
                gl.col3f('#356712'),
            ])
    ground_vb = game.renderer.new_vertex_buffer([
        gl.make_vba(
            gl.ContentKind.vertex,
            coords,
            gl.ContentHint.static_content
        ),
        gl.make_vba(
            gl.ContentKind.color,
            colors,
            gl.ContentHint.static_content
        )
    ])
    ground_ib = game.renderer.new_index_buffer(
        gl.make_vba(
            gl.ContentKind.index,
            indices,
            gl.ContentHint.static_content
        )
    )
    # Set initial color
    #colors_attr = ground_vb[1]
    #colors_attr[0] = gl.col3f('blue')
    #colors_attr[1] = gl.col3f('blue')
    #ground_vb.reload(1)

    board = game.entity_manager.create(
        'board',
        ib = ground_ib,
        vb = ground_vb,
        size = size,
        tile_height = tile_height,
        tile_width = tile_width,
        border = border,
        rows = rows,
        event_manager = game.event_manager,
    )
    transform = board.add_component(
        Transform(
            gl.matrix.translate(
                #gl.matrix.scale(
                   gl.mat4f(),
                #    gl.vec3f(size, size, 1)
                #),
                gl.vec3f(-.5, -.5, 0)
            )
        )
    )
    board.add_component(Bindable(mat))
    board.add_component(Drawable(DrawGround(board, len(indices))))
    board.add_component(Controller(CellManager(board = board)))

    return board
Beispiel #45
0
def create(game):
    mat = gl.Material('ground')
    mat.ambient = gl.col3f('black')
    mat.diffuse = gl.col3f('brown')
    mat.specular = gl.col3f('gray')
    mat.shininess = 1000
    mat.shading_model = gl.material.ShadingModel.gouraud
    mat.add_texture("ground.bmp", gl.TextureType.ambient, gl.TextureMapping.uv,
                    gl.StackOperation.add, gl.TextureMapMode.wrap,
                    gl.BlendMode.basic)
    mesh = gl.Mesh()
    mesh.mode = gl.DrawMode.quads
    size = 40
    step = 1.0 / size
    for i in (i / size for i in range(size)):
        x = i
        for j in (i / size for i in range(size)):
            y = 1.0 - j
            mesh.kind = gl.ContentKind.vertex
            mesh.append(gl.vec3f(x, y, 0))
            mesh.append(gl.vec3f(x, y - step, 0))
            mesh.append(gl.vec3f(x + step, y - step, 0))
            mesh.append(gl.vec3f(x + step, y, 0))
            mesh.kind = gl.ContentKind.tex_coord0
            mesh.append(gl.vec2f(i, j))
            mesh.append(gl.vec2f(i, j + step))
            mesh.append(gl.vec2f(i + step, j + step))
            mesh.append(gl.vec2f(i + step, j))
            mesh.kind = gl.ContentKind.normal
            mesh.append(gl.vec3f(0, 0, 1))
            mesh.append(gl.vec3f(0, 0, 1))
            mesh.append(gl.vec3f(0, 0, 1))
            mesh.append(gl.vec3f(0, 0, 1))
    light = game.renderer.new_light(
        gl.PointLightInfo(
            gl.vec3f(0, 2, -1),
            gl.Color3f("#888"),
            gl.Color3f("#333"),
        ))
    ground = game.entity_manager.create("ground")
    ground.add_component(
        cubeapp.game.entity.component.Transform(
            gl.matrix.rotate(
                gl.matrix.translate(gl.matrix.scale(gl.mat4f(), gl.vec3f(20)),
                                    gl.vec3f(-.5, 0, 0)), units.deg(-90),
                gl.vec3f(1, 0, 0))))
    ground.add_component(cubeapp.game.entity.component.Bindable(mat))
    ground.add_component(cubeapp.game.entity.component.Drawable(mesh))
    return ground