def __init__(self, display_region, panda_app, kivy_app, **kwargs): self.display_region = display_region panda_app.taskMgr.add( lambda _: display_region.set_draw_callback(self.update_kivy)) self.mouse = PandaMouse( panda_app=panda_app, display_region=display_region, on_mouse_event=self.on_mouse_event, ) self.ignored_touches = set() panda_app.buttonThrowers[0].node().set_keystroke_event('keystroke') panda_app.accept('keystroke', self.on_keystroke) panda_app.buttonThrowers[0].node().set_button_down_event('button-down') panda_app.accept('button-down', self.on_button_down) panda_app.buttonThrowers[0].node().set_button_up_event('button-up') panda_app.accept('button-up', self.on_button_up) self._has_updated = False super().__init__(**kwargs) with self.canvas.before: Callback(lambda _: self.reset_gl_context()) Callback(lambda _: gl.glEnableVertexAttribArray(0)) Callback(lambda _: gl.glEnableVertexAttribArray(1)) with self.canvas.after: Callback(lambda _: gl.glDisableVertexAttribArray(0)) Callback(lambda _: gl.glDisableVertexAttribArray(1)) self.kivy_app = kivy_app
def _populate_fbo(self, fbo): with fbo: for index, texture in self._texture_bindings.values(): BindTexture(index = index, texture = texture) Callback(self._set_blend_mode) self._rectangle = Rectangle(size = self._fbo.size) Callback(self._unset_blend_mode)
def _update(self, *pargs): '''Updates the drawling of the textures on screen The function mirror repeats the mask 3 times in the top left, top right and bottom left quadrant to increase efficiency. Also it repeats the sin wave, created in the _calc_color function to fill the rectangle with the sin wave based grating.''' # clear (or else we get gratings all over) self.canvas.clear() # set up the blending with self.canvas.before: Callback(self._set_blend_func) # Draw the two textures in rectangles with self.canvas: # draw the mask mask = Rectangle(size=self.size, pos=self.pos, texture=self._mask_texture) # repeats 4 times to fill the created texture rectangle mask.tex_coords = 0, 0, 2, 0, 2, 2, 0, 2 # draw the grating grating = Rectangle(size=self.size, pos=self.pos, texture=self._texture) # repeats the grating to fill the texture rectangle grating.tex_coords = (0, 0, self.width / self._period, 0, self.width / self._period, self.height, 0, self.height) # clean up the blending with self.canvas.after: Callback(self._reset_blend_func)
def __init__(self, **kwargs): self.canvas = Canvas() with self.canvas.before: Callback(self._set_blend_func) #self.size self.fbo_texture = Texture.create(size=self.size, colorfmt='rgba') self.fbo_texture.mag_filter = 'linear' self.fbo_texture.min_filter = 'linear' with self.canvas: #self.cbs = Callback(self.prepare_canvas) self.fbo = Fbo(size=self.size, texture=self.fbo_texture) #Color(1, 1, 1, 0) #self.fbo_rect = Rectangle() with self.fbo: ClearColor(0.0, 0.0, 0.0, 0.0) ClearBuffers() self.fbo_rect = Rectangle(size=self.size) #self.fbo.shader.source = resource_find('./kivy3dgui/gles2.0/shaders/invert.glsl') #with self.fbo.after: # self.cbr = Callback(self.reset_gl_context) # PopMatrix() with self.canvas.before: Callback(self._set_blend_func) # wait that all the instructions are in the canvas to set texture self.texture = self.fbo.texture super(FboFloatLayout, self).__init__(**kwargs)
def render(self, obj_file): self.canvas.clear() self.scene = ObjFile(obj_file) with self.canvas: self.cb = Callback(lambda args: glEnable(GL_DEPTH_TEST)) PushMatrix() self._setup_scene() PopMatrix() self.cb = Callback(lambda args: glDisable(GL_DEPTH_TEST)) Clock.schedule_interval(self._update_glsl, 1 / 60.)
def __init__(self, **kwargs): super(RenderWidget, self).__init__(**kwargs) self.size = 608, 608 self.tile_size = 32 self.atlas = Atlas(ATLAS_FILE) self.atlas_trees = Atlas(ATLAS_TREE_FILE) self.char_atlas = Atlas(ATLAS_CHAR_FILE) self.map_width = 50 self.map_height = 50 # Load Particle Textures self.particle_tex = CoreImage('{}/assets/twirl_01.png'.format( os.getcwd())).texture # self.add_widget(self.kivy_particle) ind = -1 for name, tex in self.atlas.textures.items(): if '_' in name: tile_name, tile_number = name.split('_') else: tile_name, tile_number = name, '0' # tex.flip_vertical() if self.data.get(tile_name): self.data[tile_name].append(tex) else: ind += 1 self.data[tile_name] = [tex] self.data_size[tile_name] = tex.size if not self.tile_enum.get(ind): self.tile_enum[ind] = tile_name # Tree Textures ind = 1 for name, tex in self.atlas_trees.textures.items(): self.tree_data[name] = tex self.tree_enum[ind] = name ind += 1 # Entity Textures for name, tex in self.char_atlas.textures.items(): self.char_data[name] = tex with self.canvas.before: Callback(self._set_blend_func) with self.canvas.after: Callback(self._reset_blend_func) self.initialize_tiles() Window.bind(on_key_down=self._keydown) Window.bind(on_key_up=self._keyup) Clock.schedule_interval(self.check_for_keys, 60**-1) self.tile_clock = Clock.schedule_interval(self.update_tiles, 60**-1)
def init_camera(self): self._release_camera() self._android_camera = Camera.open(self._index) params = self._android_camera.getParameters() width, height = self._resolution zoom = self._zoom # edit by ableity focusmode = self._focusmode # edit by lilei params.setPreviewSize(width, height) params.setFocusMode(focusmode) #edit by lilei params.setZoom(zoom) # edit by ableity self._android_camera.setParameters(params) # self._android_camera.setDisplayOrientation() self.fps = 30. pf = params.getPreviewFormat() assert (pf == ImageFormat.NV21) # default format is NV21 self._bufsize = int( ImageFormat.getBitsPerPixel(pf) / 8. * width * height) self._camera_texture = Texture(width=width, height=height, target=GL_TEXTURE_EXTERNAL_OES, colorfmt='rgba') self._surface_texture = SurfaceTexture(int(self._camera_texture.id)) self._android_camera.setPreviewTexture(self._surface_texture) self._fbo = Fbo(size=self._resolution) self._fbo['resolution'] = (float(width), float(height)) self._fbo.shader.fs = ''' #extension GL_OES_EGL_image_external : require #ifdef GL_ES precision highp float; #endif /* Outputs from the vertex shader */ varying vec4 frag_color; varying vec2 tex_coord0; /* uniform texture samplers */ uniform sampler2D texture0; uniform samplerExternalOES texture1; uniform vec2 resolution; void main() { vec2 coord = vec2(tex_coord0.y * ( resolution.y / resolution.x), 1. -tex_coord0.x); gl_FragColor = texture2D(texture1, tex_coord0); } ''' with self._fbo: self._texture_cb = Callback( lambda instr: self._camera_texture.bind) Rectangle(size=self._resolution)
def _config_fbo(self): # set shader file here self.fbo.shader.source = self.shader_file or \ os.path.join(kivy3_path, "default.glsl") with self.fbo: Callback(self._setup_gl_context) PushMatrix() # instructions set for all instructions self._instructions = InstructionGroup() PopMatrix() Callback(self._reset_gl_context)
def __init__(self, **kwargs): self.canvas = RenderContext(compute_normal_mat=True) self.canvas.shader.source = resource_find('simple.glsl') self.scene = ObjFile(resource_find("monkey.obj")) super(Renderer, self).__init__(**kwargs) with self.canvas: self.cb = Callback(self.setup_gl_context) PushMatrix() self.setup_scene() PopMatrix() self.cb = Callback(self.reset_gl_context) Clock.schedule_interval(self.update_glsl, 1 / 60.)
def setup_canvas(self, *args): if not (self.scene and self.obj_id or self.display_all): return print 'setting up the scene' with self.fbo: self.fbo['ambiant'] = self.ambiant self.fbo['diffuse'] = self.diffuse self.fbo['specular'] = self.specular self.cb = Callback(self.setup_gl_context) PushMatrix() self.setup_scene() PopMatrix() self.cb = Callback(self.reset_gl_context)
def __init__(self, **kwargs): self.params = {} self.canvas = RenderContext() self.canvas.shader.vs = vs3d self.targetx = 0 self.targety = 0 super(View3D, self).__init__(**kwargs) Clock.schedule_interval(self.update_glsl, 0) with self.canvas: Callback(self.activate_depthtest) Color(.8, 0, .7) self.create_3dcube(pos=(0, 0, 0), size=(100, 100, 100)) Callback(self.deactivate_depthtest)
def __init__(self, **kwargs): super(CustomWidget, self).__init__(**kwargs) with self.canvas: self.ctx = ModernGL.create_context() self.prog = self.ctx.program([ self.ctx.vertex_shader(''' #version 330 uniform vec2 WindowSize; in vec2 in_vert; in vec3 in_color; out vec3 v_color; void main() { v_color = in_color; gl_Position = vec4(in_vert / WindowSize * 2.0, 0.0, 1.0); } '''), self.ctx.fragment_shader(''' #version 330 in vec3 v_color; out vec4 f_color; void main() { f_color = vec4(v_color, 1.0); } '''), ]) self.window_size = self.prog.uniforms['WindowSize'] self.vbo = self.ctx.buffer( struct.pack( '15f', 0.0, 100.0, 1.0, 0.0, 0.0, -86.0, -50.0, 0.0, 1.0, 0.0, 86.0, -50.0, 0.0, 0.0, 1.0, )) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['in_vert', 'in_color']) Callback(self.draw)
def add_screen(self, screen): self.screen_in.pos = self.screen_out.pos self.screen_in.size = self.screen_out.size self.manager.real_remove_widget(self.screen_out) self.manager.canvas.add(self.screen_out.canvas) def remove_screen_out(instr): Clock.schedule_once(self._remove_out_canvas, -1) self.render_ctx.remove(instr) self.fbo_in = self.make_screen_fbo(self.screen_in) self.fbo_out = self.make_screen_fbo(self.screen_out) self.manager.canvas.add(self.fbo_in) self.manager.canvas.add(self.fbo_out) self.render_ctx = RenderContext(fs=self.fs, vs=self.vs, use_parent_modelview=True, use_parent_projection=True) with self.render_ctx: BindTexture(texture=self.fbo_out.texture, index=1) BindTexture(texture=self.fbo_in.texture, index=2) x, y = self.screen_in.pos w, h = self.fbo_in.texture.size Rectangle(size=(w, h), pos=(x, y), tex_coords=self.fbo_in.texture.tex_coords) Callback(remove_screen_out) self.render_ctx['tex_out'] = 1 self.render_ctx['tex_in'] = 2 self.manager.canvas.add(self.render_ctx)
def __init__(self, **kwargs): super(CustomWidget, self).__init__(**kwargs) with self.canvas: self.ctx = ModernGL.create_context() self.vert = self.ctx.vertex_shader(''' #version 330 in vec2 vert; void main() { gl_Position = vec4(vert, 0.0, 1.0); } ''') self.frag = self.ctx.fragment_shader(''' #version 330 out vec4 color; void main() { color = vec4(0.30, 0.50, 1.00, 1.0); } ''') self.prog = self.ctx.program([self.vert, self.frag]) self.vbo = self.ctx.buffer(struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8)) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['vert']) self.draw() Callback(self.draw)
def __init__(self, **kwargs): super(OptionPage, self).__init__(**kwargs) self.options = load_json('options.json') self.add_background() self.back_button = Button( text='Back', background_color=self.options['button_color'], height=40) self.options_grid = GridLayout(rows=2, cols=2, col_default_width=120) self.options_grid.add_widget(Label(text='Set Background Color')) color_entry = TextInput(text=' '.join( [str(int(elem * 100)) for elem in self.options['background']]), height=30, width=100, size_hint_y=None, size_hint_x=None) self.options_grid.add_widget(color_entry) self.options_grid.add_widget(Label(text='Set Button Color')) button_color_entry = TextInput(text=' '.join( [str(int(elem * 100)) for elem in self.options['background']]), height=30, width=100, size_hint_y=None, size_hint_x=None) self.options_grid.add_widget(button_color_entry) def apply(_): background_color = color_entry.text background_color = tuple( [float(t) / 100 for t in background_color.split(' ')]) self.options['background'] = background_color button_color = button_color_entry.text button_color = tuple( [float(t) / 100 for t in button_color.split(' ')]) self.options['button_color'] = button_color save_json('options.json', self.options) self.apply_button = Button( text='Apply', background_color=self.options['button_color'], height=40) self.apply_button.bind(on_press=apply) self.add_widget(self.options_grid) self.add_widget(self.back_button) self.add_widget(self.apply_button) with self.canvas: self.options = load_json('options.json') Callback(self.resize_widgets)
def set_highlighted(self, child): if not (child == self.current_highlighted_child): if self.current_highlighted_child: # remove the canvas from the previosly highlighted child self.current_highlighted_child.canvas.after.remove(self.instruction_canvas) child.canvas.after.add(self.instruction_canvas) self.current_highlighted_child = child with child.canvas: Callback(self.redraw_canvas)
def on_selected(self, filechooser, selection): self.button.disabled = False print 'load', selection super(Renderer, self).remove_widget(self.fl) scale = 3 self.fbo.remove_group('truc') self.scene = MeshAsciiLoader(selection[0], scale) with self.fbo: #ClearBuffers(clear_depth=True) self.cb = Callback(self.setup_gl_context) PushMatrix() self.setup_scene() PopMatrix() self.cb = Callback(self.reset_gl_context)
def populate_fbo(self, fbo): Logger.info("Setting up FBO") with self.canvas: fbo.shader.source = resource_find('simple.glsl') fbo['diffuse_light'] = (1.0, 1.0, 0.8) fbo['ambient_light'] = (0.8, 0.8, 0.8) with fbo: self.cb = Callback(self.setup_gl_context) PushMatrix() BindTexture(source='testure.jpg', index=1) UpdateNormalMatrix() Translate(0, 0, -3) self.rot = Rotate(1, 0, 1, 0) # self.show_axis() self.make_pretty_dots() PopMatrix() self.cb = Callback(self.reset_gl_context) fbo['texture1'] = 1
def setupVTK(self): Clock.schedule_interval(self.updateVTK, 1 / 1.) with self.canvas: self.fbo = Fbo(size=(512, 512), clear_color=(.3, .3, .3, .8), push_viewport=True, with_depthbuffer=True) self.size = self.fbo.size Color(0, 0, 1) Rectangle(pos=self.pos, size=self.size, texture=self.fbo.texture) Callback(self.drawVTK, reset_context=True)
def __init__(self, config, **kwargs): super(ParticleSystem, self).__init__(**kwargs) self.capacity = 0 self.particles = list() self.particles_dict = dict() self.emission_time = 0.0 self.frame_time = 0.0 self.num_particles = 0 if config is not None: self._parse_config(config) self.emission_rate = self.max_num_particles / self.life_span self.initial_capacity = self.max_num_particles self.max_capacity = self.max_num_particles self._raise_capacity(self.initial_capacity) with self.canvas.before: Callback(self._set_blend_func) with self.canvas.after: Callback(self._reset_blend_func) Clock.schedule_interval(self._update, 1.0 / 60.0)
def init_camera(self): self._release_camera() self._android_camera = Camera.open(self._index) params = self._android_camera.getParameters() width, height = self._resolution params.setPreviewSize(width, height) params.setFocusMode('continuous-picture') self._android_camera.setParameters(params) # self._android_camera.setDisplayOrientation() self.fps = 30. pf = params.getPreviewFormat() assert(pf == ImageFormat.NV21) # default format is NV21 self._bufsize = int(ImageFormat.getBitsPerPixel(pf) / 8. * width * height) self._camera_texture = Texture(width=width, height=height, target=GL_TEXTURE_EXTERNAL_OES, colorfmt='rgba') self._surface_texture = SurfaceTexture(int(self._camera_texture.id)) self._android_camera.setPreviewTexture(self._surface_texture) self._fbo = Fbo(size=self._resolution) self._fbo['resolution'] = (float(width), float(height)) self._fbo.shader.fs = ''' #extension GL_OES_EGL_image_external : require #ifdef GL_ES precision highp float; #endif /* Outputs from the vertex shader */ varying vec4 frag_color; varying vec2 tex_coord0; /* uniform texture samplers */ uniform sampler2D texture0; uniform samplerExternalOES texture1; uniform vec2 resolution; void main() { vec2 coord = vec2(tex_coord0.y * ( resolution.y / resolution.x), 1. -tex_coord0.x); gl_FragColor = texture2D(texture1, tex_coord0); } ''' with self._fbo: self._texture_cb = Callback(lambda instr: self._camera_texture.bind) Rectangle(size=self._resolution)
def setup_panda(self, *largs): self.msb = ModelShowbase() self.msb.camLens.setFov(52.0) self.msb.camLens.setNearFar(1.0, 10000.0) with self.canvas: self.fbo = Fbo(size=self.size, clear_color=(.3, .3, .3, .2)) Color(1, 1, 1) self.viewport = Rectangle(pos=self.pos, size=self.size, texture=self.fbo.texture) Callback(self.draw_panda, reset_context=True) Clock.schedule_interval(self.update_panda, 1 / 60.)
def setup_scene(self, rendered_obj, opts: dict = {}): self.curr_obj = rendered_obj self._recalc_normals = True self._update_glsl() with self.canvas: self.cb = Callback(self._setup_gl_context) PushMatrix() self.trans = Translate(0, 0, -3) self.rotx = Rotate( 1, 1, 0, 0) # so that the object does not break continuity self.scale = Scale(1, 1, 1) self.yaw = Rotate(0, 0, 0, 1) self.pitch = Rotate(0, -1, 0, 0) self.roll = Rotate(0, 0, 1, 0) self.quat = euler_to_quaternion([0, 0, 0]) UpdateNormalMatrix() if rendered_obj in self._create_mesh_fn.keys(): self._create_mesh_fn[rendered_obj](**opts) # self.trans.x += 1 # move everything to the right PopMatrix() self.cb = Callback(self._reset_gl_context)
def __init__(self, config, **kwargs): """ :param config: A pex file with specifications for particle appearance and behavior. Includes specifications for properties like speed, color, position, and size. Can be exported from http://onebyonedesign.com/flash/particleeditor/ Following are a few of the many properties that can be defined in the config file. | ``emitter_x`` - The x-position of the particle source. | ``emitter_y`` - The y-position of the particle source. | ``start_color`` - The color of particles upon emission | ``end_color`` - The color of particles at the end of their lifespan. | ``speed`` - The speed of particle movement. | ``gravity_x`` - Gravity in the x direction. | ``gravity_y`` - Gravity in the y direction. """ super(ParticleSystem, self).__init__(**kwargs) self.capacity = 0 self.particles = list() self.particles_dict = dict() self.emission_time = 0.0 self.frame_time = 0.0 self.num_particles = 0 if config is not None: self._parse_config(config) self.emission_rate = self.max_num_particles / self.life_span self.initial_capacity = self.max_num_particles self.max_capacity = self.max_num_particles self._raise_capacity(self.initial_capacity) with self.canvas.before: Callback(self._set_blend_func) with self.canvas.after: Callback(self._reset_blend_func) Clock.schedule_once(self._update, self.update_interval)
def populate_fbo(self, fbo): with self.canvas: fbo.shader.source = resource_find('simple.glsl') fbo['diffuse_light'] = (1.0, 1.0, 0.8) fbo['ambient_light'] = (0.5, 0.5, 0.5) with fbo: self.cb = Callback(self.setup_gl_context) PushMatrix() if hasattr(self, 'model_texture'): BindTexture(texture=self.model_texture, index=1) Translate(0, 1, self.gl_depth + 1) self.rot = Rotate(0, 0, 1, 0) UpdateNormalMatrix() Color(1, 1, 1, 1) self.mesh = Mesh( vertices=self.mesh_data.vertices, indices=self.mesh_data.indices, fmt=self.mesh_data.vertex_format, mode=self.mesh_data.mode, ) PopMatrix() self.cb = Callback(self.reset_gl_context) fbo['texture1'] = 1
def setup_panda(self, *largs): self.msb = msb = ModelShowbase() msb.camLens.setFov(52.0) msb.camLens.setNearFar(1.0, 10000.0) self.node = Node(node=msb.render.attachNewNode('PandaView')) with self.canvas: self.fbo = Fbo(size=self.size) self.viewport = Rectangle( pos=self.pos, size=self.size, ) Callback(self.draw_panda, reset_context=True) Clock.schedule_interval(self.update_panda, 1 / 60.)
def __init__(self, **kwargs): super(CustomWidget, self).__init__(**kwargs) with self.canvas: self.ctx = ModernGL.create_context() self.prog = self.ctx.program([ self.ctx.vertex_shader(''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_color; out vec3 v_color; void main() { v_color = in_color; gl_Position = Mvp * vec4(in_vert, 1.0); } '''), self.ctx.fragment_shader(''' #version 330 in vec3 v_color; out vec4 f_color; void main() { f_color = vec4(v_color, 1.0); } '''), ]) self.mvp = self.prog.uniforms['Mvp'] grid = bytearray() for i in range(0, 32 + 1): grid += struct.pack('6f', i - 16.0, -16.0, 0.0, 0.0, 0.0, 0.0) grid += struct.pack('6f', i - 16.0, 16.0, 0.0, 0.0, 0.0, 0.0) grid += struct.pack('6f', -16.0, i - 16.0, 0.0, 0.0, 0.0, 0.0) grid += struct.pack('6f', 16.0, i - 16.0, 0.0, 0.0, 0.0, 0.0) self.vbo = self.ctx.buffer(grid) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['in_vert', 'in_color']) Callback(self.draw)
def setDest(self,x,y,scale,pile,wait): self.lock.acquire() displayLock = DisplayLock() self.dest=[x,y] self.destScale=scale self.destPile=pile #self.destLock=lock self.has_dest=True if self.destPile: self.destPile.layout.add_widget(self.scatter) #bring to the front: parent = self.destPile.layout.parent parent.remove_widget(self.destPile.layout) parent.add_widget(self.destPile.layout) increment = 2 #0.5 xdist = abs(int(self.scatter.x-x)) ydist = abs(int(self.scatter.y-y)) if xdist == 0: #avoid div by zero self.xmove=1 self.ymove = increment * Window.height / 100 print "XZERO y={0}/{1} {2}->{3}".format(self.ymove,ydist,self.scatter.y,y) elif ydist == 0: self.xmove= increment * Window.height / 100 self.ymove = 1 print "YZERO x={0}/{1} {2}->{3}".format(self.xmove,xdist,self.scatter.x,x) else: #print "DIST "+str(xdist)+" "+str(ydist) theta = math.atan2(ydist,xdist) self.xmove = increment * math.cos(theta) * Window.height / 100 self.ymove = increment * math.sin(theta) * Window.height / 100 print "DIST x={0}/{1} {2}->{3} y={4}/{5} {6}->{7} theta={8} {9}".format(self.xmove,xdist,self.scatter.x,x, self.ymove,ydist,self.scatter.y,y, theta,math.degrees(theta)) if not self.cb: with self.scatter.canvas: self.cb = Callback(self.destCallback) self.cb.ask_update() if wait: while self.has_dest: sleep(0)
def __init__(self, **kwargs): super(QueryPage, self).__init__(**kwargs) self.options = load_json('options.json') # setup vars self.parts = [] self.add_background() # Define widgets self.entry = TextInput(height=27, text='/Users/goldwin/PycharmProjects/FDM_APP/') self.label = Label(text='Enter a path to your .stl files here') self.go_button = Button(text='GO!', height=25, background_color=self.options['button_color']) self.option_page = Button( text='Set Options', height=40, width=40, background_color=self.options['button_color']) self.add_printer_page = Button( text='Add Printer', background_color=self.options['button_color']) self.add_material_page = Button( text='Add Material', background_color=self.options['button_color']) self.option_grid = GridLayout(rows=3, cols=1) self.option_grid.add_widget(self.option_page) self.option_grid.add_widget(self.add_printer_page) self.option_grid.add_widget(self.add_material_page) # set dynamic canvas options with self.canvas: Callback(self.resize_widgets) # Add widgets to self self.add_widget(self.go_button) self.add_widget(self.entry) self.add_widget(self.label) self.add_widget(self.option_grid)
def __init__(self, **kwargs): super().__init__(**kwargs) self.parts = {} self.options = load_json('options.json') self.add_background() # add background self.back_button = Button( text='go back', size=self.center, pos=(400, 400), background_color=self.options['button_color']) # Any changes to this list must be reflected in self.update_grid self.column_labels = [ 'Part Name', 'Material', 'Print vol', 'Part Thickness', 'Infill Amt', 'Print Time', 'Final Cost' ] # TODO load materials from options self.materials = { 'ASA': { 'price': 30, 'density': 1.5 }, 'PLA': { 'price': 30, 'density': 1 }, 'ULTEM': { 'price': 530, 'density': 1 } } # self.reset_all() with self.canvas: print('updating totals') Callback(self.update_totals)
def __init__(self, **kwargs): super(CustomWidget, self).__init__(**kwargs) with self.canvas: GL.Init() self.vert = GL.NewVertexShader(''' #version 330 in vec2 vert; void main() { gl_Position = vec4(vert, 0.0, 1.0); } ''') self.frag = GL.NewFragmentShader(''' #version 330 out vec4 color; void main() { color = vec4(0.30, 0.50, 1.00, 1.0); } ''') self.prog = GL.NewProgram([self.vert, self.frag]) self.vbo = GL.NewVertexBuffer( struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8)) self.vao = GL.NewVertexArray(self.prog, self.vbo, '2f', ['vert']) self.draw() Callback(self.draw)
class CameraAndroid(CameraBase): """ Implementation of CameraBase using Android API """ def __init__(self, **kwargs): self._android_camera = None self._preview_cb = PreviewCallback(self._on_preview_frame) self._buflock = threading.Lock() super(CameraAndroid, self).__init__(**kwargs) def __del__(self): self._release_camera() def init_camera(self): self._release_camera() self._android_camera = Camera.open(self._index) params = self._android_camera.getParameters() width, height = self._resolution params.setPreviewSize(width, height) self._android_camera.setParameters(params) # self._android_camera.setDisplayOrientation() self.fps = 30. pf = params.getPreviewFormat() assert(pf == ImageFormat.NV21) # default format is NV21 self._bufsize = int(ImageFormat.getBitsPerPixel(pf) / 8. * width * height) self._camera_texture = Texture(width=width, height=height, target=GL_TEXTURE_EXTERNAL_OES, colorfmt='rgba') self._surface_texture = SurfaceTexture(int(self._camera_texture.id)) self._android_camera.setPreviewTexture(self._surface_texture) self._fbo = Fbo(size=self._resolution) self._fbo.shader.fs = ''' #extension GL_OES_EGL_image_external : require #ifdef GL_ES precision highp float; #endif /* Outputs from the vertex shader */ varying vec4 frag_color; varying vec2 tex_coord0; /* uniform texture samplers */ uniform sampler2D texture0; uniform samplerExternalOES texture1; void main() { gl_FragColor = texture2D(texture1, tex_coord0); } ''' with self._fbo: self._texture_cb = Callback(lambda instr: self._camera_texture.bind) Rectangle(size=self._resolution) def _release_camera(self): if self._android_camera is None: return self.stop() self._android_camera.release() self._android_camera = None self._texture = None # clear texture and it'll be reset in `_update` pointing to new FBO del self._fbo, self._surface_texture, self._camera_texture def _on_preview_frame(self, data, camera): with self._buflock: if self._buffer is not None: self._android_camera.addCallbackBuffer(self._buffer) # add buffer back for reuse self._buffer = data # print self._buffer, len(self.frame_data) # check if frame grabbing works def _refresh_fbo(self): self._texture_cb.ask_update() self._fbo.draw() def start(self): super(CameraAndroid, self).start() with self._buflock: self._buffer = None for k in range(2): # double buffer buf = '\x00' * self._bufsize self._android_camera.addCallbackBuffer(buf) self._android_camera.setPreviewCallbackWithBuffer(self._preview_cb) self._android_camera.startPreview() Clock.unschedule(self._update) Clock.schedule_interval(self._update, 1./self.fps) def stop(self): super(CameraAndroid, self).stop() Clock.unschedule(self._update) self._android_camera.stopPreview() self._android_camera.setPreviewCallbackWithBuffer(None) # buffer queue cleared as well, to be recreated on next start with self._buflock: self._buffer = None def _update(self, dt): self._surface_texture.updateTexImage() self._refresh_fbo() if self._texture is None: self._texture = self._fbo.texture self.dispatch('on_load') self._copy_to_gpu() def _copy_to_gpu(self): """ A dummy placeholder (the image is already in GPU) to be consistent with other providers. """ self.dispatch('on_texture') def grab_frame(self): """ Grab current frame (thread-safe, minimal overhead) """ with self._buflock: if self._buffer is None: return None buf = self._buffer.tostring() return buf def decode_frame(self, buf): """ Decode image data from grabbed frame. This method depends on OpenCV and NumPy - however it is only used for fetching the current frame as a NumPy array, and not required when this :class:`CameraAndroid` provider is simply used by a :class:`~kivy.uix.camera.Camera` widget. """ import numpy as np from cv2 import cvtColor w, h = self._resolution arr = np.fromstring(buf, 'uint8').reshape((h+h/2, w)) arr = cvtColor(arr, 93) # NV21 -> BGR return arr def read_frame(self): """ Grab and decode frame in one call """ return self.decode_frame(self.grab_frame()) @staticmethod def get_camera_count(): """ Get the number of available cameras. """ return Camera.getNumberOfCameras()
class CameraAndroid(CameraBase): """ Implementation of CameraBase using Android API """ _update_ev = None def __init__(self, **kwargs): self._android_camera = None self._preview_cb = PreviewCallback(self._on_preview_frame) self._buflock = threading.Lock() super(CameraAndroid, self).__init__(**kwargs) def __del__(self): self._release_camera() def init_camera(self): self._release_camera() self._android_camera = Camera.open(self._index) params = self._android_camera.getParameters() width, height = self._resolution params.setPreviewSize(width, height) self._android_camera.setParameters(params) # self._android_camera.setDisplayOrientation() self.fps = 30. pf = params.getPreviewFormat() assert (pf == ImageFormat.NV21) # default format is NV21 self._bufsize = int( ImageFormat.getBitsPerPixel(pf) / 8. * width * height) self._camera_texture = Texture(width=width, height=height, target=GL_TEXTURE_EXTERNAL_OES, colorfmt='rgba') self._surface_texture = SurfaceTexture(int(self._camera_texture.id)) self._android_camera.setPreviewTexture(self._surface_texture) self._fbo = Fbo(size=self._resolution) self._fbo.shader.fs = ''' #extension GL_OES_EGL_image_external : require #ifdef GL_ES precision highp float; #endif /* Outputs from the vertex shader */ varying vec4 frag_color; varying vec2 tex_coord0; /* uniform texture samplers */ uniform sampler2D texture0; uniform samplerExternalOES texture1; void main() { gl_FragColor = texture2D(texture1, tex_coord0); } ''' with self._fbo: self._texture_cb = Callback( lambda instr: self._camera_texture.bind) Rectangle(size=self._resolution) def _release_camera(self): if self._android_camera is None: return self.stop() self._android_camera.release() self._android_camera = None # clear texture and it'll be reset in `_update` pointing to new FBO self._texture = None del self._fbo, self._surface_texture, self._camera_texture def _on_preview_frame(self, data, camera): with self._buflock: if self._buffer is not None: # add buffer back for reuse self._android_camera.addCallbackBuffer(self._buffer) self._buffer = data # check if frame grabbing works # print self._buffer, len(self.frame_data) def _refresh_fbo(self): self._texture_cb.ask_update() self._fbo.draw() def start(self): super(CameraAndroid, self).start() with self._buflock: self._buffer = None for k in range(2): # double buffer buf = '\x00' * self._bufsize self._android_camera.addCallbackBuffer(buf) self._android_camera.setPreviewCallbackWithBuffer(self._preview_cb) self._android_camera.startPreview() if self._update_ev is not None: self._update_ev.cancel() self._update_ev = Clock.schedule_interval(self._update, 1 / self.fps) def stop(self): super(CameraAndroid, self).stop() if self._update_ev is not None: self._update_ev.cancel() self._update_ev = None self._android_camera.stopPreview() self._android_camera.setPreviewCallbackWithBuffer(None) # buffer queue cleared as well, to be recreated on next start with self._buflock: self._buffer = None def _update(self, dt): self._surface_texture.updateTexImage() self._refresh_fbo() if self._texture is None: self._texture = self._fbo.texture self.dispatch('on_load') self._copy_to_gpu() def _copy_to_gpu(self): """ A dummy placeholder (the image is already in GPU) to be consistent with other providers. """ self.dispatch('on_texture') def grab_frame(self): """ Grab current frame (thread-safe, minimal overhead) """ with self._buflock: if self._buffer is None: return None buf = self._buffer.tostring() return buf def decode_frame(self, buf): """ Decode image data from grabbed frame. This method depends on OpenCV and NumPy - however it is only used for fetching the current frame as a NumPy array, and not required when this :class:`CameraAndroid` provider is simply used by a :class:`~kivy.uix.camera.Camera` widget. """ import numpy as np from cv2 import cvtColor w, h = self._resolution arr = np.fromstring(buf, 'uint8').reshape((h + h / 2, w)) arr = cvtColor(arr, 93) # NV21 -> BGR return arr def read_frame(self): """ Grab and decode frame in one call """ return self.decode_frame(self.grab_frame()) @staticmethod def get_camera_count(): """ Get the number of available cameras. """ return Camera.getNumberOfCameras()
class KivyCard(Card): def __init__(self,number,name,suite,ctype,cost,attack,defense,speed,scrap,upkeep,comments): super(KivyCard,self).__init__(number,name,suite,ctype,cost,attack,defense,speed,scrap,upkeep,comments) imagename=currentDir+"out/cards_{0:02}.png".format(self.number) self.image = Image(source=imagename, allow_stretch=True, keep_ratio=True) self.backImage = Image(source="back.png", allow_stretch=True, keep_ratio=True) self.image.size= (Window.height*self.image.image_ratio, Window.height) self.scatter = CardScatter() self.scatter.size=self.image.size self.scatter.size_hint= (None, None) self.scatter.scale = 0.2 self.scatter.do_translation = False self.scatter.auto_bring_to_front = False self.scatter.bind(pressed=self.clicked) self.scatter.add_widget(self.image) self.has_dest=False self.cb=False if self.suite.name == eSuiteNames.Blank: self.image.opacity=0.5 #with selfimage.canvas.before: # Color(1, 0, 0, .5, mode='rgba') self.highlighted = Image(source=currentDir+'border.png', allow_stretch=True, keep_ratio=True) self.highlighted.size= self.image.size self.scatter.pos=(int(Window.width/2),int(-self.image.height)) self.lock = threading.Lock() def highlight(self,highlighting): #WARNING: clears select state image=self.image if self.state==eCardState.turned or self.state==eCardState.good: image=self.backImage self.scatter.clickable=highlighting image.canvas.after.clear() if highlighting: with image.canvas.after: bordersize=10 Color(1, 1, 1, 1, mode='rgba') BorderImage(source=currentDir+'border.png', border = (bordersize,bordersize,bordersize,bordersize), size = (self.image.width+(bordersize*2), self.image.height+(bordersize*2)), pos = (-bordersize,-bordersize)) def select(self,selected): #WARNING: clears highlight state image=self.image if self.state==eCardState.turned or self.state==eCardState.good: image=self.backImage self.scatter.clickable=False image.canvas.after.clear() if selected: with image.canvas.after: bordersize=10 Color(1, 0, 0, 1, mode='rgba') BorderImage(source=currentDir+'border.png', border = (bordersize,bordersize,bordersize,bordersize), size = (self.image.width+(bordersize*2), self.image.height+(bordersize*2)), pos = (-bordersize,-bordersize)) def setState(self,state): if self.state==eCardState.turned or self.state==eCardState.good: #going from turned over, then restore image self.scatter.clear_widgets() self.scatter.add_widget(self.image) super(KivyCard,self).setState(state) if state==eCardState.dead: self.scatter.rotation=90 else: self.scatter.rotation=0 if state==eCardState.turned or state==eCardState.good: self.scatter.clear_widgets() self.scatter.add_widget(self.backImage) def setDest(self,x,y,scale,pile,wait): self.lock.acquire() displayLock = DisplayLock() self.dest=[x,y] self.destScale=scale self.destPile=pile #self.destLock=lock self.has_dest=True if self.destPile: self.destPile.layout.add_widget(self.scatter) #bring to the front: parent = self.destPile.layout.parent parent.remove_widget(self.destPile.layout) parent.add_widget(self.destPile.layout) increment = 2 #0.5 xdist = abs(int(self.scatter.x-x)) ydist = abs(int(self.scatter.y-y)) if xdist == 0: #avoid div by zero self.xmove=1 self.ymove = increment * Window.height / 100 print "XZERO y={0}/{1} {2}->{3}".format(self.ymove,ydist,self.scatter.y,y) elif ydist == 0: self.xmove= increment * Window.height / 100 self.ymove = 1 print "YZERO x={0}/{1} {2}->{3}".format(self.xmove,xdist,self.scatter.x,x) else: #print "DIST "+str(xdist)+" "+str(ydist) theta = math.atan2(ydist,xdist) self.xmove = increment * math.cos(theta) * Window.height / 100 self.ymove = increment * math.sin(theta) * Window.height / 100 print "DIST x={0}/{1} {2}->{3} y={4}/{5} {6}->{7} theta={8} {9}".format(self.xmove,xdist,self.scatter.x,x, self.ymove,ydist,self.scatter.y,y, theta,math.degrees(theta)) if not self.cb: with self.scatter.canvas: self.cb = Callback(self.destCallback) self.cb.ask_update() if wait: while self.has_dest: sleep(0) def destCallback(self, instr): if self.has_dest: posx=self.scatter.x posy=self.scatter.y if posx < self.dest[0]: posx = min(posx+self.xmove,self.dest[0]) elif posx > self.dest[0]: posx = max(posx-self.xmove,self.dest[0]) if posy < self.dest[1]: posy = min(posy+self.ymove,self.dest[1]) elif posy > self.dest[1]: posy = max(posy-self.ymove,self.dest[1]) self.scatter.pos=(posx,posy) if self.scatter.scale < self.destScale: self.scatter.scale = min(self.scatter.scale+0.004,self.destScale) elif self.scatter.scale > self.destScale: self.scatter.scale = max(self.scatter.scale-0.004,self.destScale) if int(posx) == int(self.dest[0]) and int(posy) == int(self.dest[1]): self.scatter.scale = self.destScale self.scatter.pos=(int(self.dest[0]),int(self.dest[1])) if self.destPile: self.destPile.updateDisplay() #DO THESE LAST... self.has_dest=False self.lock.release() ##TODO REMOVE CALLBACL WHEN REACHED!!!! #print "callback" def clicked(self, instance, pos): global looking global lookingCard if looking: if not self.isBlank(): if lookingCard == False: self.pile.bringToFront() lookingCard = self dest=0 if self.scatter.x < Window.width/2: dest=Window.width/2 self.setDest(dest,0,1,False,False) else: lookingCard = False self.pile.updateDisplay() print "looking" else: print ('Card selected: printed from root widget: {pos}'.format(pos=pos)) displayLock.release(self)