def __init__(self, width, height): self.width = width self.height = height self.framebuffer = Framebuffer() self.tex1 = Texture(width, height, filter=GL_NEAREST, format=GL_RGBA32F, clamp='st') self.tex2 = Texture(width, height, filter=GL_NEAREST, format=GL_RGBA32F, clamp='st') self.tex3 = Texture(width, height, filter=GL_NEAREST, format=GL_RGBA32F, clamp='st') self.program = ShaderProgram( FragmentShader.open('shaders/ripples.frag'), offsets=(1.0 / width, 1.0 / height), tex2=Sampler2D(GL_TEXTURE1), tex3=Sampler2D(GL_TEXTURE2), )
def __init__(self, application): self.application = application self.width, self.height = width, height = application.mesh_width, application.mesh_height col = Column() self.input_height = LabelInput('Height', self).append_to(col).input self.material = LabelInput('Material', self).append_to(col).input self.widget = Widget('Terrain', col, id='terrain').append_to(application.workspace) self.default_material = Texture(2, 2, GL_RGBA, data=(140, 140, 140, 255)*4) self.vertex_texture = Texture(width, height, GL_RGBA32F) self.normal_texture = Texture(application.width, application.height, GL_RGBA32F, unit=GL_TEXTURE0) self.vertex_fbo = Framebuffer(self.vertex_texture) self.normal_fbo = Framebuffer(self.normal_texture) self.update_vertex_shader = application.shader('update_vertex.frag') self.update_normals_shader = application.shader('update_normals.frag') self.update_normals_shader.vars.offsets = 1.0/application.width, 1.0/application.height self.reset_vertex = application.shader('reset_vertex.frag') self.reset_normals = application.shader('reset_normals.frag') self.vbo = self.generate_vbo(width, height) self.reset() self.updated = None
def __init__(self, window): self.window = window window.set_fullscreen(True) self.fps = ClockDisplay() self.mesh_width = 512 self.mesh_height = 512 self.width = 1024 self.height = 1024 self.shaders = {} self.framebuffer = Framebuffer() self.window.push_handlers(self) font_dir = here('style/fonts') for name in res_listdir(here('style/fonts')): font_path = os.path.join(font_dir, name) pyglet.font.add_file(res_open(font_path)) self.root = Root(self.window, here('style/style.hss')) self.file_open = FileOpen(self.root, pattern=r'.*\.lth$') self.file_open.on_file = self.open self.file_save = FileSave(self.root, pattern=r'.*\.lth$') self.file_save.on_file = self.save self.export_png_dialog = FileSave(self.root, pattern=r'.*\.png$') self.export_png_dialog.on_file = self.export_png self.work_area = Area(id='sidebar').append_to(self.root) self.workspace = Workspace().append_to(self.work_area) self.canvas = LineCanvas().append_to(self.workspace) self.processing_view = Screen(0, 0, self.width, self.height) self.terrain = Terrain(self) self.export_obj_dialog = FileSave(self.root, pattern=r'.*\.obj$') self.export_obj_dialog.on_file = self.terrain.export_obj self.export_heights_dialog = FileSave(self.root, pattern=r'.*\.farr$') self.export_heights_dialog.on_file = self.terrain.export_float_array self.viewport = View3d(self).append_to(self.root) self.toolbar = Toolbar(self) self.node_factory = NodeFactory(self) pyglet.clock.schedule_interval(self.update, 0.05) pyglet.clock.schedule(lambda delta: None) #DEBUG self.temp = self.create_texture() self.height_reset = self.shader('height_reset.frag') self.nodes = [] self.export_target = Texture(self.width, self.height, format=GL_RGB)
def __init__(self): super(Application, self).__init__(resizable=True) self.mapSize = 64 self.mapTexture = Texture(self.mapSize, self.mapSize, data=[0,0,0,255]*(self.mapSize*self.mapSize)) self.probContinue = 0.79 self.minSquares = 10 # keep away from start and friends (and gold) self.goblin_distance = 10 # min distance from start self.husband_distance = 30 # probability of placement self.prob_goblin = 0.1 self.prob_friend = 0.1 self.prob_gold = 0.1 self.prob_king = 0.01 self.prob_husband = 0.01 self.new_map() self.program = ShaderProgram.open('shaders/main.shader') self.program.vars.tex = Sampler2D(GL_TEXTURE0)
def create_minimap(self): self.mm_tex = Texture.open(self.path+'/map/%s.png'%(self.map_name), unit=GL_TEXTURE0, filter=GL_NEAREST) position = [ 0.4, 0.4, 0, 0.4, 1, 0, 1, 1, 0, 1, 0.4, 0, ] texCoord = [ 0, 0, 0, 1, 1, 1, 1, 0, ] normal = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ] position = (c_float*len(position))(*position) texCoord = (c_float*len(texCoord))(*texCoord) normal = (c_float*len(normal))(*normal) self.mm_mesh = VBO(4, position_3=position, texCoord_2=texCoord, normal_3=normal)
def main(): angle = ChangeValue() window = pyglet.window.Window(width=786, height=600, vsync=False) projection = Projection(0, 0, window.width, window.height, near=0.1, far=100) width, height = 128, 128 ripples = Ripples(width, height) height_texture = Texture(width*2, height*2, format=GL_RGBA32F) processor = Processor(height_texture) gaussian = Gaussian(processor) heightmap = Heightmap(width*2, height*2, scale=1.2) sun = Sun() def rain(delta): x = random.randint(0, ripples.width) y = random.randint(0, ripples.height) size = random.random() * 0.5 with nested(ripples.framebuffer, Color): glPointSize(size) glBegin(GL_POINTS) glColor4f(0.2, 0.2, 0.2, 1.0) glVertex3f(x, y, 0) glEnd() fps = pyglet.clock.ClockDisplay() pyglet.clock.schedule_interval(rain, 0.2) pyglet.clock.schedule(lambda delta: None) @window.event def on_draw(): window.clear() ripples.step() processor.copy(ripples.result, height_texture) gaussian.filter(height_texture, 2) heightmap.update_from(height_texture) with nested(projection, Color, sun): glColor3f(7/256.0, 121/256.0, 208/256.0) glPushMatrix() glTranslatef(0, 0, -1) glRotatef(10, 1, 0, 0) glRotatef(angle, 0.0, 1.0, 0.0) glTranslatef(-0.5, 0, -0.5) heightmap.draw() glPopMatrix() fps.draw() ripples.result.draw() heightmap.vertex_texture.draw(2*width, 0, scale=0.5) heightmap.normal_texture.draw(4*width, 0, scale=0.5) glEnable(GL_POINT_SMOOTH) glEnable(GL_LINE_SMOOTH) glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, GL_FALSE) glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB, GL_FALSE) glClampColorARB(GL_CLAMP_READ_COLOR_ARB, GL_FALSE) gl_init(light=False) pyglet.app.run()
def __init__(self, width, height, scale=0.2): self.width = width self.height = height self.view = Screen(0, 0, width, height) self.vertex_texture = Texture(width, height, GL_RGBA32F) self.normal_texture = Texture(width, height, GL_RGBA32F) self.fbo = Framebuffer( self.vertex_texture, self.normal_texture, ) self.fbo.drawto = GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT self.program = ShaderProgram( FragmentShader.open('shaders/heightmap_normal.frag'), offsets=(1.0 / width, 1.0 / height), scale=scale, ) self.vbo = self.generate_vbo(width, height)
def __init__(self, window): self.window = window window.set_fullscreen(True) self.fps = ClockDisplay() self.mesh_width = 512 self.mesh_height = 512 self.width = 1024 self.height = 1024 self.shaders = {} self.framebuffer = Framebuffer() self.window.push_handlers(self) font_dir = here('style/fonts') for name in res_listdir(here('style/fonts')): font_path = os.path.join(font_dir, name) pyglet.font.add_file(res_open(font_path)) self.root = Root(self.window, here('style/style.hss')) self.file_open = FileOpen(self.root, pattern=r'.*\.lth$') self.file_open.on_file = self.open self.file_save = FileSave(self.root, pattern=r'.*\.lth$') self.file_save.on_file = self.save self.export_png_dialog = FileSave(self.root, pattern=r'.*\.png$') self.export_png_dialog.on_file = self.export_png self.viewport = View3d(self).append_to(self.root) self.work_area = Area(id='sidebar').append_to(self.root) self.workspace = Workspace().append_to(self.work_area) self.canvas = LineCanvas().append_to(self.workspace) self.processing_view = Screen(0, 0, self.width, self.height) self.ambient_occlusion = AmbientOcclusion(self) self.terrain = Terrain(self) self.export_obj_dialog = FileSave(self.root, pattern=r'.*\.obj$') self.export_obj_dialog.on_file = self.terrain.export_obj self.export_heights_dialog = FileSave(self.root, pattern=r'.*\.farr$') self.export_heights_dialog.on_file = self.terrain.export_float_array self.toolbar = Toolbar(self) self.node_factory = NodeFactory(self) pyglet.clock.schedule_interval(self.update, 0.05) pyglet.clock.schedule(lambda delta: None) #DEBUG self.temp = self.create_texture() self.height_reset = self.shader('height_reset.frag') self.nodes = [] self.export_target = Texture(self.width, self.height, format=GL_RGB)
def __init__(self, ref): self.temp = Texture( width=ref.width, height=ref.height, format=ref.format, filter=ref.filter, mipmap=ref.mipmap, ) self.width = ref.width self.height = ref.height self.fbo = Framebuffer(self.temp) self.view = Screen(0, 0, self.width, self.height) self.render_target = Framebuffer(self.temp) self.render_target.depth = Depthbuffer(self.width, self.height)
from __future__ import with_statement from contextlib import nested import pyglet from gletools import Texture, Projection, DepthTest, SphereMapping, Matrix from gletools.gl import * rotation = 0 background = Texture.open('background.jpg') sphere_map = Texture.open('sphere_map.jpg') config = Config(buffers=2, samples=4) window = pyglet.window.Window(width=background.width, height=background.height, config=config) projection = Projection(0, 0, window.width, window.height) def quad(min=0.0, max=1.0): glBegin(GL_QUADS) glTexCoord2f(1.0, 1.0) glVertex3f(max, max, 0.0) glTexCoord2f(1.0, 0.0) glVertex3f(max, min, 0.0) glTexCoord2f(0.0, 0.0) glVertex3f(min, min, 0.0) glTexCoord2f(0.0, 1.0) glVertex3f(min, max, 0.0) glEnd() def simulate(delta, _): global rotation rotation += 40.0 * delta class Bunny(object):
def create_texture(self): return Texture(self.width, self.height, format=GL_RGBA32F, clamp='st')
class Terrain(object): id = 'terrain' def __init__(self, application): self.application = application self.width, self.height = width, height = application.mesh_width, application.mesh_height col = Column() self.input_height = LabelInput('Height', self).append_to(col).input self.material = LabelInput('Material', self).append_to(col).input self.widget = Widget('Terrain', col, id='terrain').append_to(application.workspace) self.default_material = Texture(2, 2, GL_RGBA, data=(140, 140, 140, 255)*4) self.vertex_texture = Texture(width, height, GL_RGBA32F) self.normal_texture = Texture(application.width, application.height, GL_RGBA32F, unit=GL_TEXTURE0) self.vertex_fbo = Framebuffer(self.vertex_texture) self.normal_fbo = Framebuffer(self.normal_texture) self.update_vertex_shader = application.shader('update_vertex.frag') self.update_normals_shader = application.shader('update_normals.frag') self.update_normals_shader.vars.offsets = 1.0/application.width, 1.0/application.height self.reset_vertex = application.shader('reset_vertex.frag') self.reset_normals = application.shader('reset_normals.frag') self.vbo = self.generate_vbo(width, height) self.reset() self.updated = None def export_obj(self, filename): if not filename.endswith('.obj'): filename += '.obj' if self.input_height.source: heightmap = self.input_height.source.texture heightmap.retrieve() width, height = self.application.width, self.application.height with open(filename, 'w') as outfile: heights = map(lambda z: (z, float(z)/height), range(height)) widths = map(lambda x: (x, float(x)/width), range(width)) for iz, z in heights: for ix, x in widths: outfile.write('v %f %f %f\n' % (x, heightmap[ix, iz][0], z)) self.normal_texture.retrieve() for normal in self.normal_texture: outfile.write('vn %f %f %f\n' % tuple(normal[:3])) heights = map(lambda x: float(x)/height, range(height)) widths = map(lambda y: float(y)/width, range(width)) for y in heights: for x in widths: outfile.write('vt %f %f\n' % (x, y)) i_width, i_height = width-1, height-1 for z in range(i_height): for x in range(i_width): p1 = x+z*width p2 = p1+width p4 = p1+1 p3 = p2+1 outfile.write('f %i/%i/%i %i/%i/%i %i/%i/%i\n' % ( p1+1, p1+1, p1+1, p2+1, p2+1, p2+1, p3+1, p3+1, p3+1 )) outfile.write('f %i/%i/%i %i/%i/%i %i/%i/%i\n' % ( p1+1, p1+1, p1+1, p3+1, p3+1, p3+1, p4+1, p4+1, p4+1 )) def export_float_array(self, filename): if not filename.endswith('.png'): filename += '.png' if self.input_height.source: heightmap = self.input_height.source.texture heightmap.retrieve() heightmap.save(filename) #print(heightmap) #source = string_at(heightmap.buffer, sizeof(heightmap.buffer)) #image = Image.frombytes("RGB", (self.width, self.height), source) #image.save(filename) def generate_vbo(self, width, height): #as an acceleration the arrays could be prefilled in C v4f = (c_float*(width*height*4))() width_factor, height_factor = 1.0/float(width), 1.0/float(height) for z in range(height): for x in range(width): offset = (x+z*width)*4 v4f[offset:offset+4] = x*width_factor, 0, z*height_factor, 1 i_width, i_height = width-1, height-1 indices = (c_uint*(i_width*i_height*6))() for z in range(i_height): for x in range(i_width): offset = (x+z*i_width)*6 p1 = x+z*width p2 = p1+width p4 = p1+1 p3 = p2+1 indices[offset:offset+6] = p1, p2, p3, p1, p3, p4 return VertexObject( pbo = True, indices = indices, dynamic_draw_v4f = v4f, ) def open(self, data, instances): offset = data['offset'] self.widget.rect.x, self.widget.rect.y = offset['x'], offset['y'] self.widget.layout() input_id = data['input_height'] if input_id: node = instances[input_id] connect(node, self.input_height) material_id = data['material'] if material_id: node = instances[material_id] connect(node, self.material) def reset(self): view = self.application.processing_view self.vertex_fbo.textures[0] = self.vertex_texture with nested(view, self.vertex_fbo, self.reset_vertex): quad(self.width, self.height) self.vbo.vertices.copy_from(self.vertex_texture) with nested(view, self.normal_fbo, self.reset_normals): quad(self.application.width, self.application.height) def update(self): view = self.application.processing_view revision = self.revision if self.material.source: self.material.source.update() if self.input_height.source: self.input_height.source.update() if revision != self.updated: if self.input_height.source and self.input_height.source.complete: source = self.input_height.source.texture source.unit = GL_TEXTURE0 self.vertex_fbo.textures[0] = self.vertex_texture with nested(view, self.vertex_fbo, source, self.update_vertex_shader): quad(self.width, self.height) self.vbo.vertices.copy_from(self.vertex_texture) with nested(view, self.normal_fbo, source, self.update_normals_shader): quad(self.application.width, self.application.height) else: self.reset() self.updated = revision @property def revision(self): if self.input_height.source: height = self.input_height.source.revision else: height = None if self.material.source: material = self.material.source.revision else: material = None return hash((height, material)) def draw(self): glPushMatrix() glTranslatef(-0.5, 0, -0.5) self.normal_texture.unit = GL_TEXTURE0 if self.material.source and self.material.source.complete: self.material.source.texture.unit = GL_TEXTURE1 with nested(self.normal_texture, self.material.source.texture): self.vbo.draw(GL_TRIANGLES) else: self.default_material.unit = GL_TEXTURE1 with nested(self.normal_texture, self.default_material): self.vbo.draw(GL_TRIANGLES) glPopMatrix()
from __future__ import with_statement from contextlib import nested import pyglet from gletools import Texture, Projection, DepthTest, SphereMapping, Matrix from gletools.gl import * rotation = 0 background = Texture.open('background.jpg') sphere_map = Texture.open('sphere_map.jpg') config = Config(buffers=2, samples=4) window = pyglet.window.Window(width=background.width, height=background.height, config=config) projection = Projection(0, 0, window.width, window.height) def quad(min=0.0, max=1.0): glBegin(GL_QUADS) glTexCoord2f(1.0, 1.0) glVertex3f(max, max, 0.0) glTexCoord2f(1.0, 0.0) glVertex3f(max, min, 0.0) glTexCoord2f(0.0, 0.0) glVertex3f(min, min, 0.0) glTexCoord2f(0.0, 1.0) glVertex3f(min, max, 0.0) glEnd() def simulate(delta, _):
from contextlib import nested import pyglet from gletools import ( ShaderProgram, FragmentShader, VertexShader, Depthbuffer, Texture, Projection, UniformArray, Lighting, Color ) from gletools.gl import * from util import Mesh, Processor, Kernel, offsets, gl_init from gaussian import Gaussian ### setup ### window = pyglet.window.Window() projection = Projection(0, 0, window.width, window.height, near=18, far=50) texture = Texture(window.width, window.height, GL_RGBA32F) bunny = Mesh('meshes/brain') processor = Processor(texture) ### Shaders and helpers ### depth = ShaderProgram( VertexShader.open('shaders/normal.vert'), FragmentShader.open('shaders/depth.frag'), ) average = ShaderProgram( VertexShader.open('shaders/normal.vert'), FragmentShader.open('shaders/convolution.frag'), kernel_size = 3*3, kernel = UniformArray(float, 1, [
Texture, Framebuffer, Depthbuffer, Sampler2D, Projection, Screen, ) from gletools.gl import * window = pyglet.window.Window() framebuffer = Framebuffer() framebuffer.textures = [ Texture(window.width, window.height, filter=GL_LINEAR), Texture(window.width, window.height, filter=GL_LINEAR), Texture(window.width, window.height, filter=GL_LINEAR, unit=GL_TEXTURE1), ] framebuffer.depth = Depthbuffer(window.width, window.height) picture = Texture.open('texture.png') depth_shader = VertexShader(''' varying float depth; void main() { depth = -(gl_ModelViewMatrix * gl_Vertex).z; gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = ftransform(); gl_FrontColor = gl_Color; } ''') blur = ShaderProgram( depth_shader,
from __future__ import with_statement from contextlib import nested import pyglet from gletools import ShaderProgram, FragmentShader, Texture, Framebuffer, Projection, Screen from gletools.gl import * window = pyglet.window.Window() texture = Texture(64, 64, filter=GL_LINEAR) screen = Screen(0, 0, texture.width, texture.height) projection = Projection(0, 0, window.width, window.height) framebuffer = Framebuffer() framebuffer.textures[0] = texture program = ShaderProgram( FragmentShader(''' uniform float size; void main(){ vec4 vec = vec4(gl_FragCoord.x-size/2.0, gl_FragCoord.y-size/2.0, 0.0, 1.0) / size; gl_FragColor = (normalize(vec) + 1.0) / 2.0; }''')) program.vars.size = 64.0 rotation = 0.0 def quad(min=0.0, max=1.0): glBegin(GL_QUADS) glTexCoord2f(1.0, 1.0) glVertex3f(max, max, 0.0) glTexCoord2f(1.0, 0.0) glVertex3f(max, min, 0.0) glTexCoord2f(0.0, 0.0)
VertexShader, FragmentShader, Texture, Framebuffer, Depthbuffer, Sampler2D, Projection, Screen, ) from gletools.gl import * window = pyglet.window.Window() framebuffer = Framebuffer() framebuffer.textures = [ Texture(window.width, window.height, filter=GL_LINEAR), Texture(window.width, window.height, filter=GL_LINEAR), Texture(window.width, window.height, filter=GL_LINEAR, unit=GL_TEXTURE1), ] framebuffer.depth = Depthbuffer(window.width, window.height) picture = Texture.open('texture.png') depth_shader = VertexShader(''' varying float depth; void main() { depth = -(gl_ModelViewMatrix * gl_Vertex).z; gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = ftransform(); gl_FrontColor = gl_Color;
class Application(object): def __init__(self, window): self.window = window window.set_fullscreen(True) self.fps = ClockDisplay() self.mesh_width = 512 self.mesh_height = 512 self.width = 1024 self.height = 1024 self.shaders = {} self.framebuffer = Framebuffer() self.window.push_handlers(self) font_dir = here('style/fonts') for name in res_listdir(here('style/fonts')): font_path = os.path.join(font_dir, name) pyglet.font.add_file(res_open(font_path)) self.root = Root(self.window, here('style/style.hss')) self.file_open = FileOpen(self.root, pattern=r'.*\.lth$') self.file_open.on_file = self.open self.file_save = FileSave(self.root, pattern=r'.*\.lth$') self.file_save.on_file = self.save self.export_png_dialog = FileSave(self.root, pattern=r'.*\.png$') self.export_png_dialog.on_file = self.export_png self.viewport = View3d(self).append_to(self.root) self.work_area = Area(id='sidebar').append_to(self.root) self.workspace = Workspace().append_to(self.work_area) self.canvas = LineCanvas().append_to(self.workspace) self.processing_view = Screen(0, 0, self.width, self.height) self.ambient_occlusion = AmbientOcclusion(self) self.terrain = Terrain(self) self.export_obj_dialog = FileSave(self.root, pattern=r'.*\.obj$') self.export_obj_dialog.on_file = self.terrain.export_obj self.export_heights_dialog = FileSave(self.root, pattern=r'.*\.farr$') self.export_heights_dialog.on_file = self.terrain.export_float_array self.toolbar = Toolbar(self) self.node_factory = NodeFactory(self) pyglet.clock.schedule_interval(self.update, 0.05) pyglet.clock.schedule(lambda delta: None) #DEBUG self.temp = self.create_texture() self.height_reset = self.shader('height_reset.frag') self.nodes = [] self.export_target = Texture(self.width, self.height, format=GL_RGB) def export_png(self, filename): if not filename.endswith('.png'): filename += '.png' source = self.terrain.material.source if source: source.texture.unit = GL_TEXTURE0 self.framebuffer.textures[0] = self.export_target glColor4f(1.0, 1.0, 1.0, 1.0) with nested(self.processing_view, source.texture, self.framebuffer): quad(self.width, self.height) glFinish() self.export_target.save(filename) def add_node(self, node): self.nodes.append(node) def remove_node(self, node): self.nodes.remove(node) def open(self, filename): with open(filename) as file: data = load(file) self.empty() instances = dict() nodes_data = dict() for id, node_data in data['nodes'].items(): instance = self.node_factory.create(node_data) instance.id = id instances[id] = instance nodes_data[id] = node_data for id, instance in instances.items(): node_data = nodes_data[id] instance.reconnect(node_data['sources'], instances) self.terrain.open(data['terrain'], instances) self.ambient_occlusion.open(data.get('ambient_occlusion')) workspace_off = data['workspace']['offset'] self.workspace.xoff, self.workspace.yoff = workspace_off['x'], workspace_off['y'] self.viewport.pos.xyz = data['viewport']['position'] self.viewport.rotation.xyz = data['viewport']['rotation'] def save(self, filename): if not filename.endswith('.lth'): filename += '.lth' data = dict( viewport = dict( rotation = list(self.viewport.rotation), position = list(self.viewport.pos), ), ambient_occlusion = self.ambient_occlusion.save(), ) data['nodes'] = nodes = dict() for node in self.nodes: nodes[node.id] = dict( type = node.__class__.__name__, offset = dict(x=node.widget.rect.x, y=node.widget.rect.y), parameters = node.parameters, sources = dict( (name, (slot.source.id if slot.source else None)) for name, slot in node.sources.items() ) ) terrain = self.terrain data['terrain'] = dict( offset = dict(x=terrain.widget.rect.x, y = terrain.widget.rect.y), input_height = terrain.input_height.source.id if terrain.input_height.source else None, material = terrain.material.source.id if terrain.material.source else None, ) data['workspace'] = dict( offset = dict(x=self.workspace.xoff, y=self.workspace.yoff) ) with open(filename, 'w') as file: dump(data, file, sort_keys=True, indent=4) def run(self): pyglet.app.run() def empty(self): for node in list(self.nodes): node.delete() def on_draw(self): glClearColor(0.3, 0.3, 0.3, 1.0) self.window.clear() self.viewport.draw_terrain() self.root.draw() #self.fps.draw() def create_texture(self): return Texture(self.width, self.height, format=GL_RGBA32F, clamp='st') def shader(self, *names, **kwargs): if names in self.shaders: return self.shaders[names] else: shader = ShaderProgram(*[ FragmentShader.open(res_open(here('shaders/%s' % name))) if name.endswith('.frag') else VertexShader.open(res_open(here('shaders/%s' % name))) for name in names ], **kwargs) self.shaders[names] = shader return shader def update(self, delta): self.terrain.update()
def create_protagonist(self, collisionMap, position): character = pyglet.image.load(self.path+'/images/nink.png') character = Texture(character.width, character.height, data=character.get_data('RGBA', character.width*4)) return Protagonist(character, self.program, 1, 1, position, collisionMap, self.normal_mesh)
def create_enemy(self, collision_map, position): character = pyglet.image.load(self.path+'/images/enemy.png') character = Texture(character.width, character.height, data=character.get_data('RGBA', character.width*4)) return Enemy(character, self.program, 1, 1, position, collision_map, self.normal_mesh)
def create_friend(self, collision_map, position, texture): character = pyglet.image.load(self.path+'/images/others.png') character = Texture(character.width, character.height, data=character.get_data('RGBA', character.width*4)) return Friendly(character, self.program, 1, 1, position, collision_map, self.normal_mesh)
# -*- coding: utf-8 -*- from __future__ import with_statement import pyglet from gletools import ( Projection, Framebuffer, Texture, interval, quad, Group, Matrix, ) from gletools.gl import * window = pyglet.window.Window() projection = Projection(0, 0, window.width, window.height) fbo = Framebuffer( Texture(window.width, window.height, data = [100,100,100,255]*(window.width*window.height) ) ) @window.event def on_mouse_drag(x, y, rx, ry, button, modifier): if pyglet.window.mouse.LEFT == button: glColor4f(1,1,1,1) glLineWidth(3) with fbo: glBegin(GL_LINES) glVertex3f(x, y, 0) glVertex3f(x-rx, y-ry, 0) glEnd() rotation = 0.0 @interval(0.03)
self.vbo.normals.copy_from(self.normal_texture) def draw(self): self.vbo.draw(GL_TRIANGLES) if __name__ == '__main__': window = pyglet.window.Window(fullscreen=True) projection = Projection(0, 0, window.width, window.height, near=0.1, far=100) angle = ChangeValue() texture = Texture.open('images/heightmap.png') heightmap = Heightmap(texture.width, texture.height) sun = Sun() @window.event def on_draw(): window.clear() heightmap.update_from(texture) with nested(projection, Color, sun): glColor3f(0.5, 0.5, 0.5) glPushMatrix() glTranslatef(0, 0, -1) glRotatef(20, 1, 0, 0) glRotatef(angle, 0.0, 1.0, 0.0)
import pyglet from pyglet.gl import * from gletools import ShaderProgram, Matrix, Texture, Sampler2D, DepthTest from util import View, make_triangles config = Config(buffers=2, samples=4) window = pyglet.window.Window(config=config, fullscreen=True, vsync=False) view = View(window) size = 1024*4 diffuse = Texture.raw_open('data/patches/snowy_mountains.diffuse', width=size, height=size, format=GL_RGBA32F, mipmap=4, filter=GL_LINEAR_MIPMAP_LINEAR, clamp='st', unit=GL_TEXTURE0, ) terrain = Texture.raw_open('data/patches/snowy_mountains.terrain', width=size, height=size, format=GL_RGBA32F, unit=GL_TEXTURE1, clamp='st', ) program = ShaderProgram.open('terrain.shader', diffuse = Sampler2D(GL_TEXTURE0), terrain = Sampler2D(GL_TEXTURE1), ) normals = ShaderProgram.open('normals.shader') vbo = make_triangles(128, 128, terrain)
import sys import re import random from contextlib import nested import pyglet from gletools import ShaderProgram, FragmentShader, Texture, Framebuffer, Sampler2D from gletools.gl import * from lif_parser import LifParser window = pyglet.window.Window(fullscreen=True, vsync=False) framebuffer = Framebuffer() front = Texture(window.width, window.height, format=GL_RGB, filter=GL_NEAREST) back = Texture(window.width, window.height, format=GL_RGB, filter=GL_NEAREST) framebuffer.textures[0] = front program = ShaderProgram(FragmentShader.open('shader.frag'), ) program.vars.width = float(front.width) program.vars.height = float(front.height) program.vars.texture = Sampler2D(GL_TEXTURE0) def quad(): glBegin(GL_QUADS) glTexCoord2f(1.0, 1.0) glVertex3f(window.width, window.height, 0.0) glTexCoord2f(1.0, 0.0) glVertex3f(window.width, 0.0, 0.0)
from pyglet.gl import * from gletools import ShaderProgram, Matrix, Texture, Sampler2D, DepthTest from util import View, make_triangles config = Config(buffers=2, samples=4) window = pyglet.window.Window(config=config, fullscreen=True, vsync=False) view = View(window) size = 1024 * 4 diffuse = Texture.raw_open( 'data/patches/snowy_mountains.diffuse', width=size, height=size, format=GL_RGBA32F, mipmap=4, filter=GL_LINEAR_MIPMAP_LINEAR, clamp='st', unit=GL_TEXTURE0, ) terrain = Texture.raw_open( 'data/patches/snowy_mountains.terrain', width=size, height=size, format=GL_RGBA32F, unit=GL_TEXTURE1, clamp='st', ) program = ShaderProgram.open( 'terrain.shader',
class Terrain(object): id = 'terrain' def __init__(self, application): self.application = application self.width, self.height = width, height = application.mesh_width, application.mesh_height col = Column() self.input_height = LabelInput('Height', self).append_to(col).input self.material = LabelInput('Material', self).append_to(col).input self.widget = Widget('Terrain', col, id='terrain').append_to(application.workspace) self.default_material = Texture(2, 2, GL_RGBA, data=(140, 140, 140, 255)*4) self.vertex_texture = Texture(width, height, GL_RGBA32F) self.normal_texture = Texture(application.width, application.height, GL_RGBA32F, unit=GL_TEXTURE0) self.vertex_fbo = Framebuffer(self.vertex_texture) self.normal_fbo = Framebuffer(self.normal_texture) self.update_vertex_shader = application.shader('update_vertex.frag') self.update_normals_shader = application.shader('update_normals.frag') self.update_normals_shader.vars.offsets = 1.0/application.width, 1.0/application.height self.reset_vertex = application.shader('reset_vertex.frag') self.reset_normals = application.shader('reset_normals.frag') self.vbo = self.generate_vbo(width, height) self.reset() self.updated = None def export_obj(self, filename): if not filename.endswith('.obj'): filename += '.obj' if self.input_height.source: heightmap = self.input_height.source.texture heightmap.retrieve() width, height = self.application.width, self.application.height with open(filename, 'w') as outfile: heights = map(lambda z: (z, float(z)/height), range(height)) widths = map(lambda x: (x, float(x)/width), range(width)) for iz, z in heights: for ix, x in widths: outfile.write('v %f %f %f\n' % (x, heightmap[ix, iz][0], z)) self.normal_texture.retrieve() for normal in self.normal_texture: outfile.write('vn %f %f %f\n' % tuple(normal[:3])) heights = map(lambda x: float(x)/height, range(height)) widths = map(lambda y: float(y)/width, range(width)) for y in heights: for x in widths: outfile.write('vt %f %f\n' % (x, y)) i_width, i_height = width-1, height-1 for z in range(i_height): for x in range(i_width): p1 = x+z*width p2 = p1+width p4 = p1+1 p3 = p2+1 outfile.write('f %i/%i/%i %i/%i/%i %i/%i/%i\n' % ( p1+1, p1+1, p1+1, p2+1, p2+1, p2+1, p3+1, p3+1, p3+1 )) outfile.write('f %i/%i/%i %i/%i/%i %i/%i/%i\n' % ( p1+1, p1+1, p1+1, p3+1, p3+1, p3+1, p4+1, p4+1, p4+1 )) def export_float_array(self, filename): if not filename.endswith('.farr'): filename += '.farr' if self.input_height.source: heightmap = self.input_height.source.texture heightmap.retrieve() string = string_at(heightmap.buffer, heightmap.width*heightmap.height*4) with open(filename, 'wb') as outfile: outfile.write(string) def generate_vbo(self, width, height): #as an acceleration the arrays could be prefilled in C v4f = (c_float*(width*height*4))() width_factor, height_factor = 1.0/float(width), 1.0/float(height) for z in range(height): for x in range(width): offset = (x+z*width)*4 v4f[offset:offset+4] = x*width_factor, 0, z*height_factor, 1 i_width, i_height = width-1, height-1 indices = (c_uint*(i_width*i_height*6))() for z in range(i_height): for x in range(i_width): offset = (x+z*i_width)*6 p1 = x+z*width p2 = p1+width p4 = p1+1 p3 = p2+1 indices[offset:offset+6] = p1, p2, p3, p1, p3, p4 return VertexObject( pbo = True, indices = indices, dynamic_draw_v4f = v4f, ) def open(self, data, instances): offset = data['offset'] self.widget.rect.x, self.widget.rect.y = offset['x'], offset['y'] self.widget.layout() input_id = data['input_height'] if input_id: node = instances[input_id] connect(node, self.input_height) material_id = data['material'] if material_id: node = instances[material_id] connect(node, self.material) def reset(self): view = self.application.processing_view self.vertex_fbo.textures[0] = self.vertex_texture with nested(view, self.vertex_fbo, self.reset_vertex): quad(self.width, self.height) self.vbo.vertices.copy_from(self.vertex_texture) with nested(view, self.normal_fbo, self.reset_normals): quad(self.application.width, self.application.height) def update(self): view = self.application.processing_view revision = self.revision if self.material.source: self.material.source.update() if self.input_height.source: self.input_height.source.update() if revision != self.updated: self.application.ambient_occlusion.changed = True if self.input_height.source and self.input_height.source.complete: source = self.input_height.source.texture source.unit = GL_TEXTURE0 self.vertex_fbo.textures[0] = self.vertex_texture with nested(view, self.vertex_fbo, source, self.update_vertex_shader): quad(self.width, self.height) self.vbo.vertices.copy_from(self.vertex_texture) with nested(view, self.normal_fbo, source, self.update_normals_shader): quad(self.application.width, self.application.height) else: self.reset() self.application.ambient_occlusion.update() self.updated = revision def get_source(self): if self.input_height.source and self.input_height.source.complete: return self.input_height.source.texture @property def revision(self): if self.input_height.source: height = self.input_height.source.revision else: height = None if self.material.source: material = self.material.source.revision else: material = None return hash((height, material)) def draw(self): glPushMatrix() glTranslatef(-0.5, 0, -0.5) self.normal_texture.unit = GL_TEXTURE0 ambient_occlusion = self.application.ambient_occlusion.result ambient_occlusion.unit = GL_TEXTURE2 if self.material.source and self.material.source.complete: self.material.source.texture.unit = GL_TEXTURE1 with nested(self.normal_texture, self.material.source.texture, ambient_occlusion): self.vbo.draw(GL_TRIANGLES) else: self.default_material.unit = GL_TEXTURE1 with nested(self.normal_texture, self.default_material, ambient_occlusion): self.vbo.draw(GL_TRIANGLES) glPopMatrix()
class Application(object): def __init__(self, window): self.window = window window.set_fullscreen(True) self.fps = ClockDisplay() self.mesh_width = 512 self.mesh_height = 512 self.width = 1024 self.height = 1024 self.shaders = {} self.framebuffer = Framebuffer() self.window.push_handlers(self) font_dir = here('style/fonts') for name in res_listdir(here('style/fonts')): font_path = os.path.join(font_dir, name) pyglet.font.add_file(res_open(font_path)) self.root = Root(self.window, here('style/style.hss')) self.file_open = FileOpen(self.root, pattern=r'.*\.lth$') self.file_open.on_file = self.open self.file_save = FileSave(self.root, pattern=r'.*\.lth$') self.file_save.on_file = self.save self.export_png_dialog = FileSave(self.root, pattern=r'.*\.png$') self.export_png_dialog.on_file = self.export_png self.work_area = Area(id='sidebar').append_to(self.root) self.workspace = Workspace().append_to(self.work_area) self.canvas = LineCanvas().append_to(self.workspace) self.processing_view = Screen(0, 0, self.width, self.height) self.terrain = Terrain(self) self.export_obj_dialog = FileSave(self.root, pattern=r'.*\.obj$') self.export_obj_dialog.on_file = self.terrain.export_obj self.export_heights_dialog = FileSave(self.root, pattern=r'.*\.farr$') self.export_heights_dialog.on_file = self.terrain.export_float_array self.viewport = View3d(self).append_to(self.root) self.toolbar = Toolbar(self) self.node_factory = NodeFactory(self) pyglet.clock.schedule_interval(self.update, 0.05) pyglet.clock.schedule(lambda delta: None) #DEBUG self.temp = self.create_texture() self.height_reset = self.shader('height_reset.frag') self.nodes = [] self.export_target = Texture(self.width, self.height, format=GL_RGB) def export_png(self, filename): if not filename.endswith('.png'): filename += '.png' source = self.terrain.material.source if source: source.texture.unit = GL_TEXTURE0 self.framebuffer.textures[0] = self.export_target glColor4f(1.0, 1.0, 1.0, 1.0) with nested(self.processing_view, source.texture, self.framebuffer): quad(self.width, self.height) glFinish() self.export_target.save(filename) def add_node(self, node): self.nodes.append(node) def remove_node(self, node): self.nodes.remove(node) def open(self, filename): with open(filename) as file: data = load(file) self.empty() instances = dict() nodes_data = dict() for id, node_data in data['nodes'].items(): instance = self.node_factory.create(node_data) instance.id = id instances[id] = instance nodes_data[id] = node_data for id, instance in instances.items(): node_data = nodes_data[id] instance.reconnect(node_data['sources'], instances) self.terrain.open(data['terrain'], instances) workspace_off = data['workspace']['offset'] self.workspace.xoff, self.workspace.yoff = workspace_off[ 'x'], workspace_off['y'] self.viewport.pos.xyz = data['viewport']['position'] self.viewport.rotation.xyz = data['viewport']['rotation'] def save(self, filename): if not filename.endswith('.lth'): filename += '.lth' data = dict(viewport=dict( rotation=list(self.viewport.rotation), position=list(self.viewport.pos), )) data['nodes'] = nodes = dict() for node in self.nodes: nodes[node.id] = dict( type=node.__class__.__name__, offset=dict(x=node.widget.rect.x, y=node.widget.rect.y), parameters=node.parameters, sources=dict((name, (slot.source.id if slot.source else None)) for name, slot in node.sources.items())) terrain = self.terrain data['terrain'] = dict( offset=dict(x=terrain.widget.rect.x, y=terrain.widget.rect.y), input_height=terrain.input_height.source.id if terrain.input_height.source else None, material=terrain.material.source.id if terrain.material.source else None, ) data['workspace'] = dict( offset=dict(x=self.workspace.xoff, y=self.workspace.yoff)) with open(filename, 'w') as file: dump(data, file, sort_keys=True, indent=4) def run(self): pyglet.app.run() def empty(self): for node in list(self.nodes): node.delete() def on_draw(self): glClearColor(0.3, 0.3, 0.3, 1.0) self.window.clear() self.viewport.draw_terrain() self.root.draw() #self.fps.draw() def create_texture(self): return Texture(self.width, self.height, format=GL_RGBA32F, clamp='st') def shader(self, *names, **kwargs): if names in self.shaders: return self.shaders[names] else: shader = ShaderProgram( *[ FragmentShader.open(res_open(here('shaders/%s' % name))) if name.endswith('.frag') else VertexShader.open( res_open(here('shaders/%s' % name))) for name in names ], **kwargs) self.shaders[names] = shader return shader def update(self, delta): self.terrain.update()
self.horizontal = ShaderProgram( FragmentShader.open('shaders/gaussian/horizontal.frag'), off = off, ) def filter(self, texture, steps=1): for _ in range(steps): self.processor.filter(texture, self.vertical) self.processor.filter(texture, self.horizontal) ### Application code ### if __name__ == '__main__': window = pyglet.window.Window() projection = Projection(0, 0, window.width/8, window.height/8, near=18, far=50) render = Texture(window.width/8, window.height/8, GL_RGBA32F) render_processor = Processor(render) display = Texture(window.width, window.height, GL_RGBA32F) display_processor = Processor(display) bunny = Mesh('meshes/bunny') gaussian_render = Gaussian(render_processor) gaussian_display = Gaussian(display_processor) angle = 0.0 def simulate(delta): global angle angle += 10.0 * delta pyglet.clock.schedule_interval(simulate, 0.01) @window.event def on_draw():
from __future__ import with_statement from contextlib import nested import pyglet from gletools import ShaderProgram, FragmentShader, Texture, Framebuffer, Projection, Screen from gletools.gl import * window = pyglet.window.Window() texture = Texture(256, 256, filter=GL_LINEAR) framebuffer = Framebuffer() framebuffer.textures[0] = texture screen = Screen(0, 0, texture.width, texture.height) projection = Projection(0, 0, window.width, window.height) program = ShaderProgram( FragmentShader(''' uniform vec3 seed_vector; float nice_noise1(vec2 co){ return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453); } void main(){ gl_FragColor = vec4( nice_noise1(gl_TexCoord[0].xy * seed_vector.x), nice_noise1(gl_TexCoord[0].xy * seed_vector.y), nice_noise1(gl_TexCoord[0].xy * seed_vector.z), 0 ); }''') ) from random import random program.vars.seed_vector = [random() for _ in xrange(3)] rotation = 0.0
import pyglet from gletools import ShaderProgram, FragmentShader, Texture, Framebuffer, Projection, Screen from gletools.gl import * from random import random from util import quad, Processor, ChangeValue from gaussian import Gaussian window = pyglet.window.Window() projection = Projection(0, 0, window.width, window.height) noise = ShaderProgram( FragmentShader.open('shaders/noise.frag'), seed=0.0, ) width, height = 64, 64 noise_texture = Texture(width, height, format=GL_RGBA32F) noise_processor = Processor(noise_texture) texture = Texture(64, 64, format=GL_RGBA32F) processor = Processor(texture) noise_processor.filter(noise_texture, noise) processor.copy(noise_texture, texture) gaussian = Gaussian(processor) gaussian.filter(texture, 2) rotation = ChangeValue() @window.event def on_draw(): window.clear()
class Application(pyglet.window.Window): def __init__(self): super(Application, self).__init__(resizable=True) self.mapSize = 64 self.mapTexture = Texture(self.mapSize, self.mapSize, data=[0,0,0,255]*(self.mapSize*self.mapSize)) self.probContinue = 0.79 self.minSquares = 10 # keep away from start and friends (and gold) self.goblin_distance = 10 # min distance from start self.husband_distance = 30 # probability of placement self.prob_goblin = 0.1 self.prob_friend = 0.1 self.prob_gold = 0.1 self.prob_king = 0.01 self.prob_husband = 0.01 self.new_map() self.program = ShaderProgram.open('shaders/main.shader') self.program.vars.tex = Sampler2D(GL_TEXTURE0) def on_draw(self): self.clear() with nested(self.program, self.mapTexture): self.program.vars.mvp = Matrix() self.program.vars.modelview = Matrix() self.program.vars.playerPosition = (0.0, 0.0, 0.0) self.program.vars.playerLight = 1.0 position = [ -1, -1, 0, -1, 1, 0, 1, 1, 0, 1, -1, 0, ] texCoord = [ 0, 0, 0, 1, 1, 1, 1, 0, ] normal = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ] position = (c_float*len(position))(*position) texCoord = (c_float*len(texCoord))(*texCoord) normal = (c_float*len(normal))(*normal) VBO(4, position_3=position, texCoord_2=texCoord, normal_3=normal).draw(GL_QUADS) def save_map(self): tileId = float(255)/56 halfId = float(255*2)/56 for i in range(self.mapSize*self.mapSize): if self.mapTexture.buffer[i*4] == 255: self.mapTexture.buffer[i*4] = int(54*tileId + halfId) self.mapTexture.buffer[i*4 + 1] = 0 elif self.mapTexture.buffer[i*4 + 1] == 255: self.mapTexture.buffer[i*4] = int(tileId*45 + halfId) self.mapTexture.buffer[i*4 + 1] = 0 else: self.mapTexture.buffer[i*4 + 1] = int(tileId*47 + halfId) self.mapTexture.update() self.mapTexture.save('ground.png') p = open('points.txt', 'w') p.write('start, %d, %d\n'%(self.start_point[0], self.mapSize - self.start_point[1])) p.write('husband, %d, %d\n'%(self.husband[0], self.mapSize - self.husband[1])) if self.king_goblin != None: p.write('king, %d, %d\n'%(self.king_goblin[0], self.mapSize - self.king_goblin[1])) for i in self.friendly: p.write('friend, %d, %d\n'%(i[0], self.mapSize - i[1])) for i in self.gold: p.write('gold, %d, %d\n'%(i[0], self.mapSize - i[1])) for i in self.goblin: p.write('enemy, %d, %d\n'%(i[0], self.mapSize - i[1])) p.close() def new_map(self): for i in range(self.mapSize*self.mapSize): self.mapTexture.buffer[i*4] = 0 self.mapTexture.buffer[i*4+1] = 0 self.mapTexture.buffer[i*4+2] = 0 self.mapTexture.buffer[i*4+3] = 255 start_x = int((random.random()/2 + 0.25) * self.mapSize) start_y = int((random.random()/2 + 0.25) * self.mapSize) self.start_point = (start_x, start_y) self.friendly = [] self.king_goblin = None self.goblin = [] self.gold = [] self.husband = None self.mapTexture.buffer[(start_y * self.mapSize + start_x) * 4] = 255 #idea from http://properundead.com/2009/03/cave-generator.html points = [(start_x, start_y)] squares = 0 while len(points) > 0: point = points[0] points = points[1:] if point[0] < 1 or point[0] >= self.mapSize-1: continue if point[1] < 1 or point[1] >= self.mapSize-1: continue if self.can_add(point): self.add_point(point) if random.random() < self.probContinue or squares < self.minSquares: r2 = int(random.random() * 4) + 1 x = [0, 1, 2, 3] random.shuffle(x) for i in range(r2): if x[i] == 0: points.append((point[0]-1, point[1])) elif x[i] == 1: points.append((point[0]+1, point[1])) elif x[i] == 2: points.append((point[0], point[1]-1)) elif x[i] == 3: points.append((point[0], point[1]+1)) squares += 1 # Prune unconnected for y in range(self.mapSize): for x in range(self.mapSize): if x < 1 or x >= self.mapSize - 1: continue if y < 1 or y >= self.mapSize - 1: continue if start_x == x and start_y == y: continue if not self.can_add((x, y)): continue if (not self.can_add((x+1, y))) and (not self.can_add((x-1, y))) and (not self.can_add((x, y+1))) and (not self.can_add((x, y-1))): self.add_point((x, y)) self.add_husband() for y in range(self.mapSize): for x in range(self.mapSize): if not self.can_add((x,y)): self.add_gold((x,y)) self.add_goblin((x,y)) self.add_goblin_king((x,y)) self.add_friend((x,y)) print 'goblins: %s'%(len(self.goblin)) print 'friendly: %s'%(len(self.friendly)) print 'gold: %s'%(len(self.gold)) self.mapTexture.update() with nested(self.mapTexture): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) def add_gold(self, point): if random.random() < self.prob_gold: if dist(point, self.start_point) > 10 and random.random() > self.prob_gold: if self.king_goblin == None or dist(point, self.king_goblin) > self.goblin_distance: found = False for i in self.goblin: if dist(point, i) < self.goblin_distance: found = True break if not found: self.gold.append(point) def add_goblin(self, point): if random.random() < self.prob_gold: if dist(point, self.start_point) > 10 and random.random() > self.prob_goblin: if (self.king_goblin == None or dist(point, self.king_goblin) > self.goblin_distance) and (self.husband == None or dist(point, self.husband) > self.goblin_distance): found = False for i in self.friendly: if dist(point, i) < self.goblin_distance: found = True break if not found: self.goblin.append(point) def add_goblin_king(self, point): if random.random() < self.prob_king: if self.king_goblin == None and (self.husband == None or dist(point, self.husband) > self.goblin_distance): found = False for i in self.goblin: if dist(point, i) < self.goblin_distance: found = True break if not found: self.king_goblin = point def add_husband(self): while self.husband == None: for y in range(self.mapSize): for x in range(self.mapSize): if (not self.can_add((x,y))) and random.random() < self.prob_husband: self.husband = (x,y) def add_friend(self, point): if random.random() < self.prob_friend: if dist(point, self.start_point) > 10 and random.random() > self.prob_goblin: if self.king_goblin == None or dist(point, self.king_goblin) > self.goblin_distance: found = False for i in self.goblin: if dist(point, i) < self.goblin_distance: found = True break if not found: self.friendly.append(point) def can_add(self, point): return self.mapTexture.buffer[(point[1] * self.mapSize + point[0]) * 4+1] != 255 def add_point(self, point): self.mapTexture.buffer[(point[1] * self.mapSize + point[0]) * 4+1] = 255 def on_key_press(self, symbol, modifiers): if symbol == key.ENTER: self.save_map() elif symbol == key.SPACE: self.new_map() elif symbol == key.ESCAPE or symbol == key.Q: exit() def on_mouse_motion(self, x, y, dx, dy): return pyglet.event.EVENT_HANDLED def on_mouse_press(self, px, py, button, modifiers): x = float(px)/(self.width/2) -1 y = float(py)/(self.height/2) -1 print x print y return pyglet.event.EVENT_HANDLED def on_mouse_release(self, x, y, button, modifiers): return pyglet.event.EVENT_HANDLED def on_mouse_drag(self, px, py, dx, dy, buttons, modifiers): x = float(px)/(self.width/2) -1 y = float(py)/(self.height/2) -1 return pyglet.event.EVENT_HANDLED def on_resize(self, width, height): # Override the default on_resize handler to create a 3D projection self.projection = Matrix.perspective(width, height, 60, 0.1, 1000) glViewport(0, 0, width, height) glClearColor(0,0,0, 255) return pyglet.event.EVENT_HANDLED
def __init__(self, map_name, path): super(Application, self).__init__(resizable=True, width=512, height=512, caption='Nink saves the town') # Start screen self.menuTexture = Texture.open(path+'/images/start.png', unit=GL_TEXTURE0, filter=GL_NEAREST) self.husbTexture = Texture.open(path+'/images/husb_death.png', unit=GL_TEXTURE0, filter=GL_NEAREST) self.ninkTexture = Texture.open(path+'/images/nink_death.png', unit=GL_TEXTURE0, filter=GL_NEAREST) self.winTexture = Texture.open(path+'/images/win.png', unit=GL_TEXTURE0, filter=GL_NEAREST) self.make_menu_mesh() # Healthbar self.heart = Texture.open(path+'/images/heart.png', unit=GL_TEXTURE0, filter=GL_NEAREST) self.make_heart_meshes() # Sounds self.bg_music = pyglet.media.load(path+'/sound/TIGshot.mp3') self.win_sound = pyglet.media.load(path+'/sound/win.wav') self.hurt_sound = pyglet.media.StaticSource(pyglet.media.load(path+'/sound/hurt.wav')) self.pickup_sound = pyglet.media.StaticSource(pyglet.media.load(path+'/sound/pickup.wav')) self.arrow_sound = pyglet.media.StaticSource(pyglet.media.load(path+'/sound/arrow.wav')) self.death_sound = pyglet.media.StaticSource(pyglet.media.load(path+'/sound/death.wav')) self.goblin_death_sound = pyglet.media.StaticSource(pyglet.media.load(path+'/sound/goblin_death.wav')) self.follow_sound = pyglet.media.StaticSource(pyglet.media.load(path+'/sound/follow.wav')) self.scale = 96/2 self.time = 0 self.game = 0 self.camera = Matrix() self.camera = self.camera.translate(0, -5, -10) self.path = path # Main shader self.program = ShaderProgram.open(path+'/shaders/main.shader') self.program.vars.tex = Sampler2D(GL_TEXTURE0) # Map self.map_name = map_name mapimg = pyglet.image.load(path+'/map/'+map_name+'.png') self.ground = self.create_ground(mapimg) self.walls = self.create_walls(mapimg) self.create_minimap() # Normal Mesh position = [ -0.5, -0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, -0.5, 0, ] texCoord = [ 0, 0, 0, 1, 1, 1, 1, 0, ] normal = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ] position = (c_float*len(position))(*position) texCoord = (c_float*len(texCoord))(*texCoord) normal = (c_float*len(normal))(*normal) self.normal_mesh = VBO(4, position_3=position, texCoord_2=texCoord, normal_3=normal) # Gold Mesh position = [ -0.25, -0.25, 0, -0.25, 0.25, 0, 0.25, 0.25, 0, 0.25, -0.25, 0, ] texCoord = [ 0, 0, 0, 1, 1, 1, 1, 0, ] normal = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ] position = (c_float*len(position))(*position) texCoord = (c_float*len(texCoord))(*texCoord) normal = (c_float*len(normal))(*normal) self.gold_mesh = VBO(4, position_3=position, texCoord_2=texCoord, normal_3=normal) # Friend texture character = pyglet.image.load(path+'/images/others.png') self.friendTex = Texture(character.width, character.height, data=character.get_data('RGBA', character.width*4)) # Gold texture gold = pyglet.image.load(path+'/images/gold.png') self.goldTex = Texture(gold.width, gold.height, data=gold.get_data('RGBA', gold.width*4)) # Arrow texture arrow = pyglet.image.load(path+'/images/arrow.png') self.arrowTex = Texture(arrow.width, arrow.height, data=arrow.get_data('RGBA', arrow.width*4)) # Game state self.arrows = [] self.enemy = [] self.friendly = [] self.gold = [] # Datapoints points = csv.reader(open(path+'/map/'+map_name+'.txt', 'rb'), delimiter=',') for row in points: point = (((float(row[1])+0.5)/mapimg.width * self.scale*2) - self.scale, ((float(row[2])-0.5)/mapimg.width * self.scale*2) - self.scale) if row[0] == 'start': self.start_point = Vector(point[0], 0, point[1]) self.player = self.create_protagonist(self.walls.collisionMap, point) elif row[0] == 'husband': h = self.create_husband(self.walls.collisionMap, point) h.husband = True self.friendly.append(h) self.husband = h elif row[0] == 'friend': self.friendly.append(self.create_friend(self.walls.collisionMap, point, self.friendTex)) elif row[0] == 'gold': self.gold.append(self.create_gold(self.walls.collisionMap, point)) elif row[0] == 'enemy': self.enemy.append(self.create_enemy(self.walls.collisionMap, point)) pyglet.clock.schedule_interval(lambda x: self.on_update(x), 1.0/50.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); self.keys = key.KeyStateHandler() self.push_handlers(self.keys)
def update_from(self, source): with nested(self.fbo, self.view, source, self.program): quad(self.width, self.height, 0, 0) self.vbo.vertices.copy_from(self.vertex_texture) self.vbo.normals.copy_from(self.normal_texture) def draw(self): self.vbo.draw(GL_TRIANGLES) if __name__ == "__main__": window = pyglet.window.Window(fullscreen=True) projection = Projection(0, 0, window.width, window.height, near=0.1, far=100) angle = ChangeValue() texture = Texture.open("images/heightmap.png") heightmap = Heightmap(texture.width, texture.height) sun = Sun() @window.event def on_draw(): window.clear() heightmap.update_from(texture) with nested(projection, Color, sun): glColor3f(0.5, 0.5, 0.5) glPushMatrix() glTranslatef(0, 0, -1) glRotatef(20, 1, 0, 0) glRotatef(angle, 0.0, 1.0, 0.0)