text
stringlengths
81
112k
Classmethod to create a quaternion given the euler angles. def create_from_euler_angles(cls, rx, ry, rz, degrees=False): """ Classmethod to create a quaternion given the euler angles. """ if degrees: rx, ry, rz = np.radians([rx, ry, rz]) # Obtain quaternions qx = Qua...
Turn a possibly string enum into an integer enum. def as_enum(enum): """ Turn a possibly string enum into an integer enum. """ if isinstance(enum, string_types): try: enum = getattr(gl, 'GL_' + enum.upper()) except AttributeError: try: enum = _interna...
Modify shading code so that we can write code once and make it run "everywhere". def convert_shaders(convert, shaders): """ Modify shading code so that we can write code once and make it run "everywhere". """ # New version of the shaders out = [] if convert == 'es2': for isfragme...
Modify a desktop command so it works on es2. def as_es2_command(command): """ Modify a desktop command so it works on es2. """ if command[0] == 'FUNC': return (command[0], re.sub(r'^gl([A-Z])', lambda m: m.group(1).lower(), command[1])) + command[2:] if command[0] == 'SHADERS':...
Helper to ensure users have OpenGL for 3D texture support (for now) def _check_pyopengl_3D(): """Helper to ensure users have OpenGL for 3D texture support (for now)""" global USE_TEX_3D USE_TEX_3D = True try: import OpenGL.GL as _gl except ImportError: raise ImportError('PyOpenGL is...
Print the list of commands currently in the queue. If filter is given, print only commands that match the filter. def show(self, filter=None): """ Print the list of commands currently in the queue. If filter is given, print only commands that match the filter. """ for command in...
Flush all current commands to the GLIR interpreter. def flush(self, parser): """ Flush all current commands to the GLIR interpreter. """ if self._verbose: show = self._verbose if isinstance(self._verbose, str) else None self.show(show) parser.parse(self._filter(s...
Filter DATA/SIZE commands that are overridden by a SIZE command. def _filter(self, commands, parser): """ Filter DATA/SIZE commands that are overridden by a SIZE command. """ resized = set() commands2 = [] for command in reversed(commands): if command...
Merge this queue with another. Both queues will use a shared command list and either one can be used to fill or flush the shared queue. def associate(self, queue): """Merge this queue with another. Both queues will use a shared command list and either one can be used to fill o...
Parse a single command. def _parse(self, command): """ Parse a single command. """ cmd, id_, args = command[0], command[1], command[2:] if cmd == 'CURRENT': # This context is made current self.env.clear() self._gl_initialize() self.env['f...
Parse a list of commands. def parse(self, commands): """ Parse a list of commands. """ # Get rid of dummy objects that represented deleted objects in # the last parsing round. to_delete = [] for id_, val in self._objects.items(): if val == JUST_DELETED: ...
Deal with compatibility; desktop does not have sprites enabled by default. ES has. def _gl_initialize(self): """ Deal with compatibility; desktop does not have sprites enabled by default. ES has. """ if '.es' in gl.current_backend.__name__: pass # ES2: no action req...
Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram is used somewhere else. Per context we keep track of one current program. def activate(self): """ Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram...
Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgram is used somewhere else. Per context we keep track of one current program. def deactivate(self): """ Avoid overhead in calling glUseProgram with same arg. Warning: this will break if glUseProgr...
This function takes care of setting the shading code and compiling+linking it into a working program object that is ready to use. def set_shaders(self, vert, frag): """ This function takes care of setting the shading code and compiling+linking it into a working program object that is re...
Retrieve active attributes and uniforms to be able to check that all uniforms/attributes are set by the user. Other GLIR implementations may omit this. def _get_active_attributes_and_uniforms(self): """ Retrieve active attributes and uniforms to be able to check that all uniforms/attrib...
Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this. def _parse_error(self, error): """ Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this. """ error = str(error) ...
Get error and show the faulty line + some context Other GLIR implementations may omit this. def _get_error(self, code, errors, indentation=0): """Get error and show the faulty line + some context Other GLIR implementations may omit this. """ # Init results = [] l...
Set a texture sampler. Value is the id of the texture to link. def set_texture(self, name, value): """ Set a texture sampler. Value is the id of the texture to link. """ if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for t...
Set a uniform value. Value is assumed to have been checked. def set_uniform(self, name, type_, value): """ Set a uniform value. Value is assumed to have been checked. """ if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for ...
Set an attribute value. Value is assumed to have been checked. def set_attribute(self, name, type_, value): """ Set an attribute value. Value is assumed to have been checked. """ if not self._linked: raise RuntimeError('Cannot set attribute when program has no code') # Get h...
Draw program in given mode, with given selection (IndexBuffer or first, count). def draw(self, mode, selection): """ Draw program in given mode, with given selection (IndexBuffer or first, count). """ if not self._linked: raise RuntimeError('Cannot draw program if co...
Simplify a transform to a single matrix transform, which makes it a lot faster to compute transformations. Raises a TypeError if the transform cannot be simplified. def as_matrix_transform(transform): """ Simplify a transform to a single matrix transform, which makes it a lot faster to compute tra...
Places all nodes on a single circle. Parameters ---------- adjacency_mat : matrix or sparse The graph adjacency matrix directed : bool Whether the graph is directed. If this is True, is will also generate the vertices for arrows, which can be passed to an ArrowVisual. ...
Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices positions of the path(s) to be added closed: bool Whether path(s...
Draw collection def draw(self, mode="triangles"): """ Draw collection """ gl.glDepthMask(0) Collection.draw(self, mode) gl.glDepthMask(1)
Set the data used to display this visual. Parameters ---------- pos : array The array of locations to display each symbol. symbol : str The style of symbol to draw (see Notes). size : float or array The symbol size in px. edge_width : ...
Handle a hook upate. def hook_changed(self, hook_name, widget, new_data): """Handle a hook upate.""" if hook_name == 'song': self.song_changed(widget, new_data) elif hook_name == 'state': self.state_changed(widget, new_data) elif hook_name == 'elapsed_and_total':...
Update the signature of func with the data in self def update(self, func, **kw): "Update the signature of func with the data in self" func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.__defaults__ = getattr(self, '...
Make a new function from a given template and update the signature def make(self, src_templ, evaldict=None, addsource=False, **attrs): "Make a new function from a given template and update the signature" src = src_templ % vars(self) # expand name and signature evaldict = evaldict or {} ...
Create a function from the strings name, signature and body. evaldict is the evaluation dictionary. If addsource is true an attribute __source__ is added to the result. The attributes attrs are added, if any. def create(cls, obj, body, evaldict, defaults=None, doc=None, module=No...
Set the scalar array data Parameters ---------- data : ndarray A 3D array of scalar values. The isosurface is constructed to show all locations in the scalar field equal to ``self.level``. vertex_colors : array-like | None Colors to use for each verte...
Get the total bounds based on the visuals present in the scene Parameters ---------- dim : int | None Dimension to return. Returns ------- bounds : list | tuple If ``dim is None``, Returns a list of 3 tuples, otherwise the bounds for ...
Convert user string or hex color to color array (length 3 or 4) def _string_to_rgb(color): """Convert user string or hex color to color array (length 3 or 4)""" if not color.startswith('#'): if color.lower() not in _color_dict: raise ValueError('Color "%s" unknown' % color) color = ...
Convert color(s) from any set of fmts (str/hex/arr) to RGB(A) array def _user_to_rgba(color, expand=True, clip=False): """Convert color(s) from any set of fmts (str/hex/arr) to RGB(A) array""" if color is None: color = np.zeros(4, np.float32) if isinstance(color, string_types): color = _str...
Helper to turn val into array and clip between 0 and 1 def _array_clip_val(val): """Helper to turn val into array and clip between 0 and 1""" val = np.array(val) if val.max() > 1 or val.min() < 0: logger.warning('value will be clipped between 0 and 1') val[...] = np.clip(val, 0, 1) return v...
Extend a ColorArray with new colors Parameters ---------- colors : instance of ColorArray The new colors. def extend(self, colors): """Extend a ColorArray with new colors Parameters ---------- colors : instance of ColorArray The new colo...
Set the color using an Nx4 array of RGBA floats def rgba(self, val): """Set the color using an Nx4 array of RGBA floats""" # Note: all other attribute sets get routed here! # This method is meant to do the heavy lifting of setting data rgba = _user_to_rgba(val, expand=False) if ...
Set the color using an Nx4 array of RGBA uint8 values def RGBA(self, val): """Set the color using an Nx4 array of RGBA uint8 values""" # need to convert to normalized float val = np.atleast_1d(val).astype(np.float32) / 255 self.rgba = val
Set the color using an Nx3 array of RGB uint8 values def RGB(self, val): """Set the color using an Nx3 array of RGB uint8 values""" # need to convert to normalized float val = np.atleast_1d(val).astype(np.float32) / 255. self.rgba = val
Set the color using length-N array of (from HSV) def value(self, val): """Set the color using length-N array of (from HSV)""" hsv = self._hsv hsv[:, 2] = _array_clip_val(val) self.rgba = _hsv_to_rgb(hsv)
Produce a lighter color (if possible) Parameters ---------- dv : float Amount to increase the color value by. copy : bool If False, operation will be carried out in-place. Returns ------- color : instance of ColorArray The lig...
Produce a darker color (if possible) Parameters ---------- dv : float Amount to decrease the color value by. copy : bool If False, operation will be carried out in-place. Returns ------- color : instance of ColorArray The dark...
The ViewBox received a mouse event; update transform accordingly. Default implementation adjusts scale factor when scolling. Parameters ---------- event : instance of Event The event. def viewbox_mouse_event(self, event): """ The ViewBox received a mouse eve...
Reset the camera view using the known limits. def _set_range(self, init): """ Reset the camera view using the known limits. """ if init and (self._scale_factor is not None): return # We don't have to set our scale factor # Get window size (and store factor now to sync wit...
The viewbox received a mouse event; update transform accordingly. Parameters ---------- event : instance of Event The event. def viewbox_mouse_event(self, event): """ The viewbox received a mouse event; update transform accordingly. Paramete...
Set the camera position and orientation def _update_camera_pos(self): """ Set the camera position and orientation""" # transform will be updated several times; do not update camera # transform until we are done. ch_em = self.events.transform_change with ch_em.blocker(self._upda...
Determine if the user requested interactive mode. def is_interactive(self): """ Determine if the user requested interactive mode. """ # The Python interpreter sets sys.flags correctly, so use them! if sys.flags.interactive: return True # IPython does not set sys.fla...
Enter the native GUI event loop. Parameters ---------- allow_interactive : bool Is the application allowed to handle interactive mode for console terminals? By default, typing ``python -i main.py`` results in an interactive shell that also regularly calls th...
Select a backend by name. See class docstring for details. def _use(self, backend_name=None): """Select a backend by name. See class docstring for details. """ # See if we're in a specific testing mode, if so DONT check to see # if it's a valid backend. If it isn't, it's a good thing we...
Set gl configuration def _set_config(c): """Set gl configuration""" gl_attribs = [glcanvas.WX_GL_RGBA, glcanvas.WX_GL_DEPTH_SIZE, c['depth_size'], glcanvas.WX_GL_STENCIL_SIZE, c['stencil_size'], glcanvas.WX_GL_MIN_RED, c['red_size'], glcan...
Helper to extract list of mods from event def _get_mods(evt): """Helper to extract list of mods from event""" mods = [] mods += [keys.CONTROL] if evt.ControlDown() else [] mods += [keys.ALT] if evt.AltDown() else [] mods += [keys.SHIFT] if evt.ShiftDown() else [] mods += [keys.META] if evt.Meta...
Helper to convert from wx keycode to vispy keycode def _process_key(evt): """Helper to convert from wx keycode to vispy keycode""" key = evt.GetKeyCode() if key in KEYMAP: return KEYMAP[key], '' if 97 <= key <= 122: key -= 32 if key >= 32 and key <= 127: return keys.Key(chr(...
Check if a node is a child of the current node Parameters ---------- node : instance of Node The potential child. Returns ------- child : bool Whether or not the node is a child. def is_child(self, node): """Check if a node is a child of...
The first ancestor of this node that is a SubScene instance, or self if no such node exists. def scene_node(self): """The first ancestor of this node that is a SubScene instance, or self if no such node exists. """ if self._scene_node is None: from .subscene import S...
Emit an event to inform listeners that properties of this Node have changed. Also request a canvas update. def update(self): """ Emit an event to inform listeners that properties of this Node have changed. Also request a canvas update. """ self.events.update() c ...
Create a new transform of *type* and assign it to this node. All extra arguments are used in the construction of the transform. Parameters ---------- type_ : str The transform type. *args : tuple Arguments. **kwargs : dict Keywoard ar...
Called when has changed. This allows the node and its children to react (notably, VisualNode uses this to update its TransformSystem). Note that this method is only called when one transform is replaced by another; it is not called if an existing transform internally c...
Return the list of parents starting from this node. The chain ends at the first node with no parents. def parent_chain(self): """ Return the list of parents starting from this node. The chain ends at the first node with no parents. """ chain = [self] while True: ...
Helper function to actuall construct the tree def _describe_tree(self, prefix, with_transform): """Helper function to actuall construct the tree""" extra = ': "%s"' % self.name if self.name is not None else '' if with_transform: extra += (' [%s]' % self.transform.__class__.__name__)...
Return the common parent of two entities If the entities have no common parent, return None. Parameters ---------- node : instance of Node The other node. Returns ------- parent : instance of Node | None The parent. def common_parent(se...
Return a list describing the path from this node to a child node If *node* is not a (grand)child of this node, then raise RuntimeError. Parameters ---------- node : instance of Node The child node. Returns ------- path : list | None The ...
Return two lists describing the path from this node to another Parameters ---------- node : instance of Node The other node. Returns ------- p1 : list First path (see below). p2 : list Second path (see below). Notes ...
Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parameters ---------- node : instance of Node T...
read(fname, fmt) This classmethod is the entry point for reading OBJ files. Parameters ---------- fname : str The name of the file to read. fmt : str Can be "obj" or "gz" to specify the file format. def read(cls, fname): """ read(fname, fmt) ...
The method that reads a line and processes it. def readLine(self): """ The method that reads a line and processes it. """ # Read line line = self._f.readline().decode('ascii', 'ignore') if not line: raise EOFError() line = line.strip() if line.start...
Reads a tuple of numbers. e.g. vertices, normals or teture coords. def readTuple(self, line, n=3): """ Reads a tuple of numbers. e.g. vertices, normals or teture coords. """ numbers = [num for num in line.split(' ') if num] return [float(num) for num in numbers[1:n + 1]]
Each face consists of three or more sets of indices. Each set consists of 1, 2 or 3 indices to vertices/normals/texcords. def readFace(self, line): """ Each face consists of three or more sets of indices. Each set consists of 1, 2 or 3 indices to vertices/normals/texcords. """ ...
Converts gathere lists to numpy arrays and creates BaseMesh instance. def finish(self): """ Converts gathere lists to numpy arrays and creates BaseMesh instance. """ self._vertices = np.array(self._vertices, 'float32') if self._faces: self._faces = np.array(s...
This classmethod is the entry point for writing mesh data to OBJ. Parameters ---------- fname : string The filename to write to. Must end with ".obj" or ".gz". vertices : numpy array The vertex data faces : numpy array The face data te...
Writes a tuple of numbers (on one line). def writeTuple(self, val, what): """ Writes a tuple of numbers (on one line). """ # Limit to three values. so RGBA data drops the alpha channel # Format can handle up to 3 texcords val = val[:3] # Make string val = ' '.joi...
Write the face info to the net line. def writeFace(self, val, what='f'): """ Write the face info to the net line. """ # OBJ counts from 1 val = [v + 1 for v in val] # Make string if self._hasValues and self._hasNormals: val = ' '.join(['%i/%i/%i' % (v, v, v) ...
Write the given mesh instance. def writeMesh(self, vertices, faces, normals, values, name='', reshape_faces=True): """ Write the given mesh instance. """ # Store properties self._hasNormals = normals is not None self._hasValues = values is not None sel...
Compute cross product between list of 3D vectors Much faster than np.cross() when the number of cross products becomes large (>500). This is because np.cross() methods become less memory efficient at this stage. Parameters ---------- x : array Input array 1. y : array Input...
Efficiently compute vertex normals for triangulated surface def _calculate_normals(rr, tris): """Efficiently compute vertex normals for triangulated surface""" # ensure highest precision for our summation/vectorization "trick" rr = rr.astype(np.float64) # first, compute triangle normals r1 = rr[tri...
Resize an image Parameters ---------- image : ndarray Array of shape (N, M, ...). shape : tuple 2-element shape. kind : str Interpolation, either "linear" or "nearest". Returns ------- scaled_image : ndarray New image, will have dtype np.float64. def re...
Append a new set of segments to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices positions of the path(s) to be added closed: bool Whether path(s...
Parse the lines, and fill self.line_fields accordingly. def parse(self): """Parse the lines, and fill self.line_fields accordingly.""" for line in self.lines: # Parse the line field_defs = self.parse_line(line) fields = [] # Convert field parameters into...
Compute the relative position of the fields on a given line. Args: screen_width (int): the width of the screen line (mpdlcd.display_fields.Field list): the list of fields on the line Returns: ((int, mpdlcd.display_fields.Field) list): the positions o...
Add the pattern to a screen. Also fills self.widgets. Args: screen_width (int): the width of the screen screen (lcdprod.Screen): the screen to fill. def add_to_screen(self, screen_width, screen): """Add the pattern to a screen. Also fills self.widgets. ...
Register a field on its target hooks. def register_hooks(self, field): """Register a field on its target hooks.""" for hook, subhooks in field.register_hooks(): self.hooks[hook].append(field) self.subhooks[hook] |= set(subhooks)
Called whenever the data for a hook changed. def hook_changed(self, hook, new_data): """Called whenever the data for a hook changed.""" for field in self.hooks[hook]: widget = self.widgets[field] field.hook_changed(hook, widget, new_data)
Parse a line of text. A format contains fields, within curly brackets, and free text. Maximum one 'variable width' field is allowed per line. You cannot use the '{' or '}' characters in the various text/... fields. Format: '''{<field_kind>[ <field_option>,<field_option]} te...
Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines. def add(self, pattern_txt): """Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines. """ self.patterns[len(pattern_txt)] = patt...
Convert x,y coordinates to w,x,y,z Quaternion parameters Adapted from: linalg library Copyright (c) 2010-2015, Renaud Blanch <rndblnch at gmail dot com> Licence at your convenience: GPLv3 or higher <http://www.gnu.org/licenses/gpl.html> BSD new <http://opensource.org/licenses/BSD-3-Clause> d...
Update rotation parmeters based on mouse movement def _update_rotation(self, event): """Update rotation parmeters based on mouse movement""" p2 = event.mouse_event.pos if self._event_value is None: self._event_value = p2 wh = self._viewbox.size self._quaternion = (Qu...
Rotate the transformation matrix based on camera parameters def _rotate_tr(self): """Rotate the transformation matrix based on camera parameters""" rot, x, y, z = self._quaternion.get_axis_angle() up, forward, right = self._get_dim_vectors() self.transform.rotate(180 * rot / np.pi, (x, ...
Convert mouse x, y movement into x, y, z translations def _dist_to_trans(self, dist): """Convert mouse x, y movement into x, y, z translations""" rot, x, y, z = self._quaternion.get_axis_angle() tr = MatrixTransform() tr.rotate(180 * rot / np.pi, (x, y, z)) dx, dz, dy = np.dot(t...
Decorator to convert argument to array. Parameters ---------- func : function The function to decorate. Returns ------- func : function The decorated function. def arg_to_array(func): """ Decorator to convert argument to array. Parameters ---------- func :...
Convert `obj` to 4-element vector (numpy array with shape[-1] == 4) Parameters ---------- obj : array-like Original object. default : array-like The defaults to use if the object does not have 4 entries. Returns ------- obj : array-like The object promoted to have 4...
Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication. [x, y] => [[x, y, 0, 1]] [x, y, z] => [[x, y, z, 1]] [[x1, y1], [[x1, y1, 0, 1], [x2, y2], => [x2, y2, 0, 1], [x3, y3]] [x3, y3, 0, 1]] If 1D input is provided, then the retu...
Get a transform from the cache that maps along *path*, which must be a list of Transforms to apply in reverse order (last transform is applied first). Accessed items have their age reset to 0. def get(self, path): """ Get a transform from the cache that maps along *path*, which must ...
Increase the age of all items in the cache by 1. Items whose age is greater than self.max_age will be removed from the cache. def roll(self): """ Increase the age of all items in the cache by 1. Items whose age is greater than self.max_age will be removed from the cache. """ rem...
Calculate and show a histogram of data Parameters ---------- data : array-like Data to histogram. Currently only 1D data is supported. bins : int | array-like Number of bins, or bin edges. color : instance of Color Color of the histogram. ...
Show an image Parameters ---------- data : ndarray Should have shape (N, M), (N, M, 3) or (N, M, 4). cmap : str Colormap name. clim : str | tuple Colormap limits. Should be ``'auto'`` or a two-element tuple of min and max values. ...
Show a 3D mesh Parameters ---------- vertices : array Vertices. faces : array | None Face definitions. vertex_colors : array | None Vertex colors. face_colors : array | None Face colors. color : instance of Color ...
Plot a series of data using lines and markers Parameters ---------- data : array | two arrays Arguments can be passed as ``(Y,)``, ``(X, Y)`` or ``np.array((X, Y))``. color : instance of Color Color of the line. symbol : str Marker...
Calculate and show a spectrogram Parameters ---------- x : array-like 1D signal to operate on. ``If len(x) < n_fft``, x will be zero-padded to length ``n_fft``. n_fft : int Number of FFT points. Much faster for powers of two. step : int | None...
Show a 3D volume Parameters ---------- vol : ndarray Volume to render. clim : tuple of two floats | None The contrast limits. The values in the volume are mapped to black and white corresponding to these values. Default maps between min an...
Show a 3D surface plot. Extra keyword arguments are passed to `SurfacePlot()`. Parameters ---------- zdata : array-like A 2D array of the surface Z values. def surface(self, zdata, **kwargs): """Show a 3D surface plot. Extra keyword arguments are passed to...