if n_values is None:<EOL><INDENT>n_values = (<NUM_LIT:0>, <NUM_LIT:5>, <NUM_LIT:50>, <NUM_LIT>, <NUM_LIT:1000>, <NUM_LIT>, <NUM_LIT>)<EOL><DEDENT>string_tables = {n: gen_string_table(n) for n in n_values}<EOL>regexs = gen_regex_table()<EOL>data = []<EOL>for n in n_values:<EOL><INDENT>for id in xrange(len(regexs)):<EOL><INDENT>regex = regexs[id]<EOL>string = string_tables[n][id]<EOL>data.append((regex, string))<EOL><DEDENT><DEDENT>return data<EOL>

Initialize the strings we'll run the regexes against.

    The strings used in the benchmark are prefixed and suffixed by
    strings that are repeated n times.

    The sequence n_values contains the values for n.
    If n_values is None the values of n from the original benchmark
    are used.

    The generated list of strings is cached in the string_tables
    variable, which is indexed by n.

    Returns:
    A list of string prefix/suffix lengths.


df = int(round(df))<EOL>highest_table_df = len(_T_DIST_95_CONF_LEVELS)<EOL>if df >= <NUM_LIT:200>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT:100>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT:50>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= highest_table_df:<EOL><INDENT>return _T_DIST_95_CONF_LEVELS[highest_table_df - <NUM_LIT:1>]<EOL><DEDENT>return _T_DIST_95_CONF_LEVELS[df]<EOL>

Approximate the 95% confidence interval for Student's T distribution.

    Given the degrees of freedom, returns an approximation to the 95%
    confidence interval for the Student's T distribution.

    Args:
        df: An integer, the number of degrees of freedom.

    Returns:
        A float.


deg_freedom = len(sample1) + len(sample2) - <NUM_LIT:2><EOL>mean1 = statistics.mean(sample1)<EOL>squares1 = ((x - mean1) ** <NUM_LIT:2> for x in sample1)<EOL>mean2 = statistics.mean(sample2)<EOL>squares2 = ((x - mean2) ** <NUM_LIT:2> for x in sample2)<EOL>return (math.fsum(squares1) + math.fsum(squares2)) / float(deg_freedom)<EOL>

Find the pooled sample variance for two samples.

    Args:
        sample1: one sample.
        sample2: the other sample.

    Returns:
        Pooled sample variance, as a float.


if len(sample1) != len(sample2):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>error = pooled_sample_variance(sample1, sample2) / len(sample1)<EOL>diff = statistics.mean(sample1) - statistics.mean(sample2)<EOL>return diff / math.sqrt(error * <NUM_LIT:2>)<EOL>

Calculate a t-test score for the difference between two samples.

    Args:
        sample1: one sample.
        sample2: the other sample.

    Returns:
        The t-test score, as a float.


deg_freedom = len(sample1) + len(sample2) - <NUM_LIT:2><EOL>critical_value = tdist95conf_level(deg_freedom)<EOL>t_score = tscore(sample1, sample2)<EOL>return (abs(t_score) >= critical_value, t_score)<EOL>

Determine whether two samples differ significantly.

    This uses a Student's two-sample, two-tailed t-test with alpha=0.95.

    Args:
        sample1: one sample.
        sample2: the other sample.

    Returns:
        (significant, t_score) where significant is a bool indicating whether
        the two samples differ significantly; t_score is the score from the
        two-sample T test.


print("<STR_LIT>".format(url, fname))<EOL>response = urlopen(url)<EOL>download = response.read()<EOL>with open(fname, '<STR_LIT:wb>') as fh:<EOL><INDENT>fh.write(download)<EOL><DEDENT>

Download file from url and save as fname.


print("<STR_LIT>".format(zip_fname))<EOL>with zipfile.ZipFile(zip_fname) as zf:<EOL><INDENT>zf.extractall()<EOL><DEDENT>

Unzip the zip_fname in the current directory.


fname = '<STR_LIT>'<EOL>downlad_file(url, fname)<EOL>unzip_file(fname)<EOL>print("<STR_LIT>".format(fname))<EOL>os.unlink(fname)<EOL>


canvas = np.zeros((height, width, <NUM_LIT:3>), dtype=np.uint8)<EOL>return canvas.view(Canvas)<EOL>

Return a blank canvas to annotate.

        :param width: xdim (int)
        :param height: ydim (int)
        :returns: :class:`jicbioimage.illustrate.Canvas`


def draw_cross(self, position, color=(<NUM_LIT:255>, <NUM_LIT:0>, <NUM_LIT:0>), radius=<NUM_LIT:4>):

y, x = position<EOL>for xmod in np.arange(-radius, radius+<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>xpos = x + xmod<EOL>if xpos < <NUM_LIT:0>:<EOL><INDENT>continue  <EOL><DEDENT>if xpos >= self.shape[<NUM_LIT:1>]:<EOL><INDENT>continue  <EOL><DEDENT>self[int(y), int(xpos)] = color<EOL><DEDENT>for ymod in np.arange(-radius, radius+<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>ypos = y + ymod<EOL>if ypos < <NUM_LIT:0>:<EOL><INDENT>continue  <EOL><DEDENT>if ypos >= self.shape[<NUM_LIT:0>]:<EOL><INDENT>continue  <EOL><DEDENT>self[int(ypos), int(x)] = color<EOL><DEDENT>

Draw a cross on the canvas.

        :param position: (row, col) tuple
        :param color: RGB tuple
        :param radius: radius of the cross (int)


def draw_line(self, pos1, pos2, color=(<NUM_LIT:255>, <NUM_LIT:0>, <NUM_LIT:0>)):

r1, c1 = tuple([int(round(i, <NUM_LIT:0>)) for i in pos1])<EOL>r2, c2 = tuple([int(round(i, <NUM_LIT:0>)) for i in pos2])<EOL>rr, cc = skimage.draw.line(r1, c1, r2, c2)<EOL>self[rr, cc] = color<EOL>

Draw a line between pos1 and pos2 on the canvas.

        :param pos1: position 1 (row, col) tuple
        :param pos2: position 2 (row, col) tuple
        :param color: RGB tuple


def mask_region(self, region, color=(<NUM_LIT:0>, <NUM_LIT:255>, <NUM_LIT:0>)):

self[region] = color<EOL>

Mask a region with a color.

        :param region: :class:`jicbioimage.core.region.Region`
        :param color: RGB tuple


def text_at(self, text, position, color=(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>),<EOL>size=<NUM_LIT:12>, antialias=False, center=False):

def antialias_value(value, normalisation):<EOL><INDENT>return int(round(value * normalisation))<EOL><DEDENT>def antialias_rgb(color, normalisation):<EOL><INDENT>return tuple([antialias_value(v, normalisation) for v in color])<EOL><DEDENT>def set_color(xpos, ypos, color):<EOL><INDENT>try:<EOL><INDENT>self[ypos, xpos] = color<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>y, x = position<EOL>font = PIL.ImageFont.truetype(DEFAULT_FONT_PATH, size=size)<EOL>mask = font.getmask(text)<EOL>width, height = mask.size<EOL>if center:<EOL><INDENT>x = x - (width // <NUM_LIT:2>)<EOL>y = y - (height // <NUM_LIT:2>)<EOL><DEDENT>for ystep in range(height):<EOL><INDENT>for xstep in range(width):<EOL><INDENT>normalisation = mask[ystep * width + xstep] / <NUM_LIT><EOL>if antialias:<EOL><INDENT>if normalisation != <NUM_LIT:0>:<EOL><INDENT>rgb_color = antialias_rgb(color, normalisation)<EOL>set_color(x + xstep, y+ystep, rgb_color)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if normalisation > <NUM_LIT>:<EOL><INDENT>set_color(x + xstep, y + ystep, color)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Write text at x, y top left corner position.

        By default the x and y coordinates represent the top left hand corner
        of the text. The text can be centered vertically and horizontally by
        using setting the ``center`` option to ``True``.

        :param text: text to write
        :param position: (row, col) tuple
        :param color: RGB tuple
        :param size: font size
        :param antialias: whether or not the text should be antialiased
        :param center: whether or not the text should be centered on the
                       input coordinate


@staticmethod<EOL><INDENT>def from_grayscale(im, channels_on=(True, True, True)):<DEDENT>

xdim, ydim = im.shape<EOL>canvas = np.zeros((xdim, ydim, <NUM_LIT:3>), dtype=np.uint8)<EOL>for i, include in enumerate(channels_on):<EOL><INDENT>if include:<EOL><INDENT>canvas[:, :, i] = im<EOL><DEDENT><DEDENT>return canvas.view(AnnotatedImage)<EOL>

Return a canvas from a grayscale image.

        :param im: single channel image
        :channels_on: channels to populate with input image
        :returns: :class:`jicbioimage.illustrate.Canvas`


self.properties = kwargs.get('<STR_LIT>', Property())<EOL>self.interleaved = bool(kwargs.get('<STR_LIT>', True))<EOL>stream = None<EOL>basename = None<EOL>storage = None<EOL>if args:<EOL><INDENT>if isinstance(args[<NUM_LIT:0>], string_types) or isinstance(args[<NUM_LIT:0>], bytes):<EOL><INDENT>basename = args[<NUM_LIT:0>]<EOL>if len(args) > <NUM_LIT:1>:<EOL><INDENT>stream = args[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>elif isinstance(args[<NUM_LIT:0>], ICustomStorage):<EOL><INDENT>storage = args[<NUM_LIT:0>]<EOL>if len(args) > <NUM_LIT:1>:<EOL><INDENT>stream = args[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>stream = args[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if basename:<EOL><INDENT>self.properties.storage = RT_Disk<EOL>self.properties.filename = basename<EOL>f = basename + "<STR_LIT:.>" + self.properties.idx_extension<EOL>p = os.path.abspath(f)<EOL>if os.path.exists(p):<EOL><INDENT>self.properties.overwrite =bool(kwargs.get('<STR_LIT>', False))<EOL>if not self.properties.overwrite:<EOL><INDENT>try:<EOL><INDENT>self.properties.index_id<EOL><DEDENT>except core.RTreeError:<EOL><INDENT>self.properties.index_id = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>d = os.path.dirname(p)<EOL>if not os.access(d, os.W_OK):<EOL><INDENT>message = "<STR_LIT>" % f<EOL>raise OSError(message)<EOL><DEDENT><DEDENT>elif storage:<EOL><INDENT>if (major_version < <NUM_LIT:2> and minor_version < <NUM_LIT:8>):<EOL><INDENT>raise core.RTreeError(<EOL>"<STR_LIT>"<EOL>.format(__c_api_version__))<EOL><DEDENT>self.properties.storage = RT_Custom<EOL>if storage.hasData:<EOL><INDENT>self.properties.overwrite =bool(kwargs.get('<STR_LIT>', False))<EOL>if not self.properties.overwrite:<EOL><INDENT>try:<EOL><INDENT>self.properties.index_id<EOL><DEDENT>except core.RTreeError:<EOL><INDENT>self.properties.index_id = <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>storage.clear()<EOL><DEDENT><DEDENT>self.customstorage = storage<EOL>storage.registerCallbacks(self.properties)<EOL><DEDENT>else:<EOL><INDENT>self.properties.storage = RT_Memory<EOL><DEDENT>ps = kwargs.get('<STR_LIT>', None)<EOL>if ps:<EOL><INDENT>self.properties.pagesize = int(ps)<EOL><DEDENT>if stream:<EOL><INDENT>self._exception = None<EOL>self.handle = self._create_idx_from_stream(stream)<EOL>if self._exception:<EOL><INDENT>raise self._exception<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.handle = IndexHandle(self.properties.handle)<EOL><DEDENT>

Creates a new index

        :param filename:
            The first argument in the constructor is assumed to be a filename
            determining that a file-based storage for the index should be used.
            If the first argument is not of type basestring, it is then assumed
            to be an instance of ICustomStorage or derived class.
            If the first argument is neither of type basestring nor an instance
            of ICustomStorage, it is then assumed to be an input index item
            stream.

        :param stream:
            If the first argument in the constructor is not of type basestring,
            it is assumed to be an iterable stream of data that will raise a
            StopIteration.  It must be in the form defined by the
            :attr:`interleaved` attribute of the index. The following example
            would assume :attr:`interleaved` is False::

            (id, (minx, maxx, miny, maxy, minz, maxz, ..., ..., mink, maxk),
             object)

            The object can be None, but you must put a place holder of
            ``None`` there.

        :param storage:
            If the first argument in the constructor is an instance of
            ICustomStorage then the given custom storage is used.

        :param interleaved: True or False, defaults to True.
            This parameter determines the coordinate order for all methods that
            take in coordinates.

        :param properties: An :class:`index.Property` object
            This object sets both the creation and instantiation properties
            for the object and they are passed down into libspatialindex.
            A few properties are curried from instantiation parameters
            for you like ``pagesize`` and ``overwrite``
            to ensure compatibility with previous versions of the library.  All
            other properties must be set on the object.

        .. warning::
            The coordinate ordering for all functions are sensitive the
            index's :attr:`interleaved` data member.  If :attr:`interleaved`
            is False, the coordinates must be in the form
            [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If
            :attr:`interleaved` is True, the coordinates must be in the form
            [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax].

        A basic example
        ::

            >>> from rtree import index
            >>> p = index.Property()

            >>> idx = index.Index(properties=p)
            >>> idx  # doctest: +ELLIPSIS
            <rtree.index.Index object at 0x...>

        Insert an item into the index::

            >>> idx.insert(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734),
            ...            obj=42)

        Query::

            >>> hits = idx.intersection((0, 0, 60, 60), objects=True)
            >>> for i in hits:
            ...     if i.id == 4321:
            ...         i.object
            ...         i.bbox
            ... # doctest: +ELLIPSIS
            42
            [34.37768294..., 26.73758537..., 49.37768294..., 41.73758537...]

        Using custom serializers::

            >>> class JSONIndex(index.Index):
            ...     def dumps(self, obj):
            ...         # This import is nested so that the doctest doesn't
            ...         # require simplejson.
            ...         import simplejson
            ...         return simplejson.dumps(obj).encode('ascii')
            ...
            ...     def loads(self, string):
            ...         import simplejson
            ...         return simplejson.loads(string.decode('ascii'))

            >>> stored_obj = {"nums": [23, 45], "letters": "abcd"}
            >>> json_idx = JSONIndex()
            >>> try:
            ...     json_idx.insert(1, (0, 1, 0, 1), stored_obj)
            ...     list(json_idx.nearest((0, 0), 1,
            ...                           objects="raw")) == [stored_obj]
            ... except ImportError:
            ...     True
            True


if self.handle:<EOL><INDENT>self.handle.destroy()<EOL>self.handle = None<EOL><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>

Force a flush of the index to storage. Renders index
        inaccessible.


def insert(self, id, coordinates, obj=None):

p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>data = ctypes.c_ubyte(<NUM_LIT:0>)<EOL>size = <NUM_LIT:0><EOL>pyserialized = None<EOL>if obj is not None:<EOL><INDENT>size, data, pyserialized = self._serialize(obj)<EOL><DEDENT>core.rt.Index_InsertData(self.handle, id, p_mins, p_maxs,<EOL>self.properties.dimension, data, size)<EOL>

Inserts an item into the index with the given coordinates.

        :param id: long integer
            A long integer that is the identifier for this index entry.  IDs
            need not be unique to be inserted into the index, and it is up
            to the user to ensure they are unique if this is a requirement.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        :param obj: a pickleable object.  If not None, this object will be
            stored in the index with the :attr:`id`.

        The following example inserts an entry into the index with id `4321`,
        and the object it stores with that id is the number `42`.  The
        coordinate ordering in this instance is the default (interleaved=True)
        ordering::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.insert(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734),
            ...            obj=42)


p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>p_num_results = ctypes.c_uint64(<NUM_LIT:0>)<EOL>core.rt.Index_Intersects_count(self.handle,<EOL>p_mins,<EOL>p_maxs,<EOL>self.properties.dimension,<EOL>ctypes.byref(p_num_results))<EOL>return p_num_results.value<EOL>

Return number of objects that intersect the given coordinates.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        The following example queries the index for any objects any objects
        that were stored in the index intersect the bounds given in the
        coordinates::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.insert(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734),
            ...            obj=42)

            >>> print(idx.count((0, 0, 60, 60)))
            1


def intersection(self, coordinates, objects=False):

if objects:<EOL><INDENT>return self._intersection_obj(coordinates, objects)<EOL><DEDENT>p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>p_num_results = ctypes.c_uint64(<NUM_LIT:0>)<EOL>it = ctypes.pointer(ctypes.c_int64())<EOL>core.rt.Index_Intersects_id(self.handle,<EOL>p_mins,<EOL>p_maxs,<EOL>self.properties.dimension,<EOL>ctypes.byref(it),<EOL>ctypes.byref(p_num_results))<EOL>return self._get_ids(it, p_num_results.value)<EOL>

Return ids or objects in the index that intersect the given
        coordinates.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        :param objects: True or False or 'raw'
            If True, the intersection method will return index objects that
            were pickled when they were stored with each index entry, as well
            as the id and bounds of the index entries. If 'raw', the objects
            will be returned without the :class:`rtree.index.Item` wrapper.

        The following example queries the index for any objects any objects
        that were stored in the index intersect the bounds given in the
        coordinates::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.insert(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734),
            ...            obj=42)

            >>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
            >>> [(item.object, item.bbox) for item in hits if item.id == 4321]
            ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
            [(42, [34.37768294..., 26.73758537..., 49.37768294...,
                   41.73758537...])]

        If the :class:`rtree.index.Item` wrapper is not used, it is faster to
        request the 'raw' objects::

            >>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
            [42]


def nearest(self, coordinates, num_results=<NUM_LIT:1>, objects=False):

if objects:<EOL><INDENT>return self._nearest_obj(coordinates, num_results, objects)<EOL><DEDENT>p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>p_num_results = ctypes.pointer(ctypes.c_uint64(num_results))<EOL>it = ctypes.pointer(ctypes.c_int64())<EOL>core.rt.Index_NearestNeighbors_id(self.handle,<EOL>p_mins,<EOL>p_maxs,<EOL>self.properties.dimension,<EOL>ctypes.byref(it),<EOL>p_num_results)<EOL>return self._get_ids(it, p_num_results.contents.value)<EOL>

Returns the ``k``-nearest objects to the given coordinates.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        :param num_results: integer
            The number of results to return nearest to the given coordinates.
            If two index entries are equidistant, *both* are returned.
            This property means that :attr:`num_results` may return more
            items than specified

        :param objects: True / False / 'raw'
            If True, the nearest method will return index objects that
            were pickled when they were stored with each index entry, as
            well as the id and bounds of the index entries.
            If 'raw', it will return the object as entered into the database
            without the :class:`rtree.index.Item` wrapper.

        Example of finding the three items nearest to this one::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)
            >>> hits = idx.nearest((0, 0, 10, 10), 3, objects=True)


if coordinate_interleaved is None:<EOL><INDENT>coordinate_interleaved = self.interleaved<EOL><DEDENT>return _get_bounds(<EOL>self.handle, core.rt.Index_GetBounds, coordinate_interleaved)<EOL>

Returns the bounds of the index

        :param coordinate_interleaved: If True, the coordinates are turned
            in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax],
            otherwise they are returned as
            [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax].  If not specified,
            the :attr:`interleaved` member of the index is used, which
            defaults to True.


p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>core.rt.Index_DeleteData(<EOL>self.handle, id, p_mins, p_maxs, self.properties.dimension)<EOL>

Deletes items from the index with the given ``'id'`` within the
        specified coordinates.

        :param id: long integer
            A long integer that is the identifier for this index entry.  IDs
            need not be unique to be inserted into the index, and it is up
            to the user to ensure they are unique if this is a requirement.

        :param coordinates: sequence or array
            Dimension * 2 coordinate pairs, representing the min
            and max coordinates in each dimension of the item to be
            deleted from the index. Their ordering will depend on the
            index's :attr:`interleaved` data member.
            These are not the coordinates of a space containing the
            item, but those of the item itself. Together with the
            id parameter, they determine which item will be deleted.
            This may be an object that satisfies the numpy array protocol.

        Example::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.delete(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))


assert len(interleaved) % <NUM_LIT:2> == <NUM_LIT:0>, ("<STR_LIT>")<EOL>dimension = len(interleaved) // <NUM_LIT:2><EOL>di = []<EOL>for i in range(dimension):<EOL><INDENT>di.extend([interleaved[i], interleaved[i + dimension]])<EOL><DEDENT>return di<EOL>


assert len(deinterleaved) % <NUM_LIT:2> == <NUM_LIT:0>, ("<STR_LIT>")<EOL>interleaved = []<EOL>for i in range(<NUM_LIT:2>):<EOL><INDENT>interleaved.extend([deinterleaved[i + j]<EOL>for j in range(<NUM_LIT:0>, len(deinterleaved), <NUM_LIT:2>)])<EOL><DEDENT>return interleaved<EOL>


stream_iter = iter(stream)<EOL>dimension = self.properties.dimension<EOL>darray = ctypes.c_double * dimension<EOL>mins = darray()<EOL>maxs = darray()<EOL>no_data = ctypes.cast(ctypes.pointer(ctypes.c_ubyte(<NUM_LIT:0>)),<EOL>ctypes.POINTER(ctypes.c_ubyte))<EOL>def py_next_item(p_id, p_mins, p_maxs, p_dimension, p_data, p_length):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>p_id[<NUM_LIT:0>], coordinates, obj = next(stream_iter)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>except Exception as exc:<EOL><INDENT>self._exception = exc<EOL>return -<NUM_LIT:1><EOL><DEDENT>if self.interleaved:<EOL><INDENT>coordinates = Index.deinterleave(coordinates)<EOL><DEDENT>for i in range(dimension):<EOL><INDENT>mins[i] = coordinates[i*<NUM_LIT:2>]<EOL>maxs[i] = coordinates[(i*<NUM_LIT:2>)+<NUM_LIT:1>]<EOL><DEDENT>p_mins[<NUM_LIT:0>] = ctypes.cast(mins, ctypes.POINTER(ctypes.c_double))<EOL>p_maxs[<NUM_LIT:0>] = ctypes.cast(maxs, ctypes.POINTER(ctypes.c_double))<EOL>p_dimension[<NUM_LIT:0>] = dimension<EOL>if obj is None:<EOL><INDENT>p_data[<NUM_LIT:0>] = no_data<EOL>p_length[<NUM_LIT:0>] = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>p_length[<NUM_LIT:0>], data, _ = self._serialize(obj)<EOL>p_data[<NUM_LIT:0>] = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte))<EOL><DEDENT>return <NUM_LIT:0><EOL><DEDENT>stream = core.NEXTFUNC(py_next_item)<EOL>return IndexStreamHandle(self.properties.handle, stream)<EOL>

This function is used to instantiate the index given an
        iterable stream of data.


def __init__(self, loads, handle, owned=False):

if handle:<EOL><INDENT>self.handle = handle<EOL><DEDENT>self.owned = owned<EOL>self.id = core.rt.IndexItem_GetID(self.handle)<EOL>self.object = None<EOL>self.object = self.get_object(loads)<EOL>self.bounds = _get_bounds(<EOL>self.handle, core.rt.IndexItem_GetBounds, False)<EOL>

There should be no reason to instantiate these yourself. Items are
        created automatically when you call
        :meth:`rtree.index.Index.intersection` (or other index querying
        methods) with objects=True given the parameters of the function.


return Index.interleave(self.bounds)<EOL>

Returns the bounding box of the index entry


def destroy(self, context, returnError):

returnError.contents.value = self.IllegalStateError<EOL>raise NotImplementedError("<STR_LIT>")<EOL>


def loadByteArray(self, context, page, resultLen, resultData, returnError):


def storeByteArray(self, context, page, len, data, returnError):


def deleteByteArray(self, context, page, returnError):


def loadByteArray(self, page, returnError):

returnError.contents.value = self.IllegalStateError<EOL>raise NotImplementedError("<STR_LIT>")<EOL>return '<STR_LIT>'<EOL>

Must be overridden. Must return a string with the loaded data.


def storeByteArray(self, page, data, returnError):

returnError.contents.value = self.IllegalStateError<EOL>raise NotImplementedError("<STR_LIT>")<EOL>return <NUM_LIT:0><EOL>

Must be overridden. Must return the new 64-bit page ID of the stored
        data if a new page had to be created (i.e. page is not NewPage).


def deleteByteArray(self, page, returnError):


if args:<EOL><INDENT>if isinstance(args[<NUM_LIT:0>], rtree.index.string_types)or isinstance(args[<NUM_LIT:0>], bytes)or isinstance(args[<NUM_LIT:0>], rtree.index.ICustomStorage):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% self.__class__)<EOL><DEDENT><DEDENT>self._objects = {}<EOL>return super(RtreeContainer, self).__init__(*args, **kwargs)<EOL>

Creates a new index

        :param stream:
            If the first argument in the constructor is not of type basestring,
            it is assumed to be an iterable stream of data that will raise a
            StopIteration.  It must be in the form defined by the
            :attr:`interleaved` attribute of the index. The following example
            would assume :attr:`interleaved` is False::

            (obj, (minx, maxx, miny, maxy, minz, maxz, ..., ..., mink, maxk))

        :param interleaved: True or False, defaults to True.
            This parameter determines the coordinate order for all methods that
            take in coordinates.

        :param properties: An :class:`index.Property` object
            This object sets both the creation and instantiation properties
            for the object and they are passed down into libspatialindex.
            A few properties are curried from instantiation parameters
            for you like ``pagesize`` to ensure compatibility with previous
            versions of the library.  All other properties must be set on the
            object.

        .. warning::
            The coordinate ordering for all functions are sensitive the
            index's :attr:`interleaved` data member.  If :attr:`interleaved`
            is False, the coordinates must be in the form
            [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If
            :attr:`interleaved` is True, the coordinates must be in the form
            [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax].

        A basic example
        ::

            >>> from rtree import index
            >>> p = index.Property()

            >>> idx = index.RtreeContainer(properties=p)
            >>> idx  # doctest: +ELLIPSIS
            <rtree.index.RtreeContainer object at 0x...>

        Insert an item into the index::

            >>> idx.insert(object(),
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))

        Query::

            >>> hits = idx.intersection((0, 0, 60, 60), bbox=True)
            >>> for obj in hits:
            ...     obj.object
            ...     obj.bbox  # doctest: +ELLIPSIS
            <object object at 0x...>
            [34.37768294..., 26.73758537..., 49.37768294..., 41.73758537...]


try:<EOL><INDENT>count = self._objects[id(obj)] + <NUM_LIT:1><EOL><DEDENT>except KeyError:<EOL><INDENT>count = <NUM_LIT:1><EOL><DEDENT>self._objects[id(obj)] = (count, obj)<EOL>return super(RtreeContainer, self).insert(id(obj), coordinates, None)<EOL>

Inserts an item into the index with the given coordinates.

        :param obj: object
            Any object.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        The following example inserts a simple object into the container.
        The coordinate ordering in this instance is the default
        (interleaved=True) ordering::

            >>> from rtree import index
            >>> idx = index.RtreeContainer()
            >>> idx.insert(object(),
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))


def intersection(self, coordinates, bbox=False):

if bbox == False:<EOL><INDENT>for id in super(RtreeContainer,<EOL>self).intersection(coordinates, bbox):<EOL><INDENT>yield self._objects[id][<NUM_LIT:1>]<EOL><DEDENT><DEDENT>elif bbox == True:<EOL><INDENT>for value in super(RtreeContainer,<EOL>self).intersection(coordinates, bbox):<EOL><INDENT>value.object = self._objects[value.id][<NUM_LIT:1>]<EOL>value.id = None<EOL>yield value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>

Return ids or objects in the index that intersect the given
        coordinates.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        :param bbox: True or False
            If True, the intersection method will return the stored objects,
            as well as the bounds of the entry.

        The following example queries the container for any stored objects that
        intersect the bounds given in the coordinates::

            >>> from rtree import index
            >>> idx = index.RtreeContainer()
            >>> idx.insert(object(),
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))

            >>> hits = list(idx.intersection((0, 0, 60, 60), bbox=True))
            >>> [(item.object, item.bbox) for item in hits]
            ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
            [(<object object at 0x...>, [34.3776829412, 26.7375853734,
            49.3776829412, 41.7375853734])]

        If the :class:`rtree.index.Item` wrapper is not used, it is faster to
        request only the stored objects::

            >>> list(idx.intersection((0, 0, 60, 60)))   # doctest: +ELLIPSIS
            [<object object at 0x...>]


def nearest(self, coordinates, num_results = <NUM_LIT:1>, bbox=False):

if bbox == False:<EOL><INDENT>for id in super(RtreeContainer,<EOL>self).nearest(coordinates, num_results, bbox):<EOL><INDENT>yield self._objects[id][<NUM_LIT:1>]<EOL><DEDENT><DEDENT>elif bbox == True:<EOL><INDENT>for value in super(RtreeContainer,<EOL>self).nearest(coordinates, num_results, bbox):<EOL><INDENT>value.object = self._objects[value.id][<NUM_LIT:1>]<EOL>value.id = None<EOL>yield value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>

Returns the ``k``-nearest objects to the given coordinates.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        :param num_results: integer
            The number of results to return nearest to the given coordinates.
            If two entries are equidistant, *both* are returned.
            This property means that :attr:`num_results` may return more
            items than specified.

        :param bbox: True or False
            If True, the nearest method will return the stored objects, as
            well as the bounds of the entry.

        Example of finding the three items nearest to this one::

            >>> from rtree import index
            >>> idx = index.RtreeContainer()
            >>> idx.insert(object(), (34.37, 26.73, 49.37, 41.73))
            >>> hits = idx.nearest((0, 0, 10, 10), 3, bbox=True)


try:<EOL><INDENT>count = self._objects[id(obj)] - <NUM_LIT:1><EOL><DEDENT>except KeyError:<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>if count == <NUM_LIT:0>:<EOL><INDENT>del self._objects[obj]<EOL><DEDENT>else:<EOL><INDENT>self._objects[id(obj)] = (count, obj)<EOL><DEDENT>return super(RtreeContainer, self).delete(id, coordinates)<EOL>

Deletes the item from the container within the specified
        coordinates.

        :param obj: object
            Any object.

        :param coordinates: sequence or array
            Dimension * 2 coordinate pairs, representing the min
            and max coordinates in each dimension of the item to be
            deleted from the index. Their ordering will depend on the
            index's :attr:`interleaved` data member.
            These are not the coordinates of a space containing the
            item, but those of the item itself. Together with the
            id parameter, they determine which item will be deleted.
            This may be an object that satisfies the numpy array protocol.

        Example::

            >>> from rtree import index
            >>> idx = index.RtreeContainer()
            >>> idx.delete(object(),
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))
            Traceback (most recent call last):
             ...
            IndexError: object is not in the index


if result != <NUM_LIT:0>:<EOL><INDENT>s = rt.Error_GetLastErrorMsg().decode()<EOL>msg = '<STR_LIT>' %(func.__name__, s)<EOL>rt.Error_Reset()<EOL>raise RTreeError(msg)<EOL><DEDENT>return True<EOL>


if not bool(result):<EOL><INDENT>s = rt.Error_GetLastErrorMsg().decode()<EOL>msg = '<STR_LIT>' % (func.__name__, s)<EOL>rt.Error_Reset()<EOL>raise RTreeError(msg)<EOL><DEDENT>return result<EOL>


def check_void_done(result, func, cargs):

if rt.Error_GetErrorCount():<EOL><INDENT>s = rt.Error_GetLastErrorMsg().decode()<EOL>msg = '<STR_LIT>' % (func.__name__, s)<EOL>rt.Error_Reset()<EOL>raise RTreeError(msg)<EOL><DEDENT>return result<EOL>

Error checking for void* returns that might be empty with no error


count = rt.Error_GetErrorCount()<EOL>if count != <NUM_LIT:0>:<EOL><INDENT>s = rt.Error_GetLastErrorMsg().decode()<EOL>msg = '<STR_LIT>' % (func.__name__, s)<EOL>rt.Error_Reset()<EOL>raise RTreeError(msg)<EOL><DEDENT>return result<EOL>


def check_value_free(result, func, cargs):


failure_description = None<EOL>if self.interactive:<EOL><INDENT>failure_description = _ask_user_to_verify(description)<EOL>if failure_description is not None:<EOL><INDENT>self.fail(failure_description)<EOL><DEDENT><DEDENT>

Ask a question to verify the current test result. Uses the console or an external gui
        as no window is available.


screenshot_name = self._get_next_screenshot_name()<EOL>screenshot_file_name = self._get_screenshot_session_file_name(screenshot_name)<EOL>if window is not None:<EOL><INDENT>window.switch_to()<EOL><DEDENT>get_buffer_manager().get_color_buffer().image_data.save(screenshot_file_name)<EOL>self.screenshots.append(screenshot_name)<EOL>self._schedule_commit()<EOL>return screenshot_name<EOL>

Take a screenshot to allow visual verification.


return '<STR_LIT>'.format(self.testname,<EOL>len(self.screenshots)+<NUM_LIT:1>)<EOL>

Get the unique name for the next screenshot.


Store the screenshots for reference if the test case is successful.


def ask_question(self, description=None, screenshot=True):

if self.window is None:<EOL><INDENT>self.create_window()<EOL><DEDENT>self.add_text('<STR_LIT>')<EOL>if description:<EOL><INDENT>self.add_text(description)<EOL><DEDENT>self.add_text(self.question)<EOL>self.answer = None<EOL>caught_exception = None<EOL>try:<EOL><INDENT>if self.interactive:<EOL><INDENT>self.run_event_loop()<EOL>self.handle_answer()<EOL><DEDENT>else:<EOL><INDENT>self.run_event_loop(<NUM_LIT:0.1>)<EOL><DEDENT><DEDENT>except Exception as ex:<EOL><INDENT>import traceback<EOL>traceback.print_exc()<EOL>caught_exception = ex<EOL><DEDENT>finally:<EOL><INDENT>if screenshot:<EOL><INDENT>try:<EOL><INDENT>screenshot_name = self._take_screenshot(self.window)<EOL>if caught_exception is None and not self.interactive:<EOL><INDENT>self._check_screenshot(screenshot_name)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>if not caught_exception:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>if caught_exception:<EOL><INDENT>raise caught_exception<EOL><DEDENT><DEDENT>

Ask a question inside the test window. By default takes a screenshot and validates
        that too.


super(EventLoopFixture, self).ask_question(description)<EOL>


if not isinstance(camera,Camera):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.cameras[camera.name]=camera<EOL>

Add the camera to the internal registry.

Each camera name must be unique, or else only the most recent version will be used. This behavior should not be relied on because some objects may cache objects.

Additionally, only instances of :py:class:`Camera() <peng3d.camera.Camera>` may be used, everything else raises a :py:exc:`TypeError`\ .


if not isinstance(view,WorldView):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.views[view.name]=view<EOL>

Adds the supplied :py:class:`WorldView()` object to the internal registry.

The same restrictions as for cameras apply, e.g. no duplicate names.

Additionally, only instances of :py:class:`WorldView()` may be used, everything else raises a :py:exc:`TypeError`\ .


self.actors[actor.uuid]=actor<EOL>

Adds the given actor to the internal registry.

Note that this actors :py:attr:`uuid` attribute must be unique, else it will override any actors previously registered with its UUID.


if name not in self.views:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return self.views[name]<EOL>

Returns the view with name ``name``\ .

Raises a :py:exc:`ValueError` if the view does not exist.


for actor in self.actors.values():<EOL><INDENT>actor.render(view)<EOL><DEDENT>

Renders the world in 3d-mode.

If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may not be rendered.


super(StaticWorld,self).render3d(view)<EOL>self.batch3d.draw()<EOL>


if name == self.activeCamera:<EOL><INDENT>return <EOL><DEDENT>if name not in self.world.cameras:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>old = self.activeCamera<EOL>self.activeCamera = name<EOL>self.cam.on_activate(old)<EOL>

Sets the active camera.

This method also calls the :py:meth:`Camera.on_activate() <peng3d.camera.Camera.on_activate>` event handler if the camera is not already active.


self.world.peng.window.push_handlers(self)<EOL>

Fake event handler called by :py:meth:`Layer.on_menu_enter() <peng3d.layer.Layer.on_menu_enter>` when the containing menu is entered.


self.world.peng.window.pop_handlers()<EOL>

Fake event handler, same as :py:meth:`on_menu_enter()` but for exiting menus instead.


return self.world.cameras[self.activeCamera]<EOL>

Property for getting the currently active camera.

Always equals ``self.cameras[self.activeCamera]``\ .


return self.world.cameras[self.activeCamera].rot<EOL>

Property for accessing the current rotation of the active camera.

This property can also be written to.


return self.world.cameras[self.activeCamera].pos<EOL>

Property for accessing the current position of the active camera.

The value of this property will always be a list of length 3.

This property can also be written to.


super(WorldViewMouseRotatable,self).on_menu_enter(old)<EOL>self.world.peng.window.toggle_exclusivity(True)<EOL>

Fake event handler, same as :py:meth:`WorldView.on_menu_enter()` but forces mouse exclusivity.


super(WorldViewMouseRotatable,self).on_menu_exit(new)<EOL>self.world.peng.window.toggle_exclusivity(False)<EOL>

Fake event handler, same as :py:meth:`WorldView.on_menu_exit()` but force-disables mouse exclusivity.


if symbol == key.ESCAPE:<EOL><INDENT>self.world.peng.window.toggle_exclusivity()<EOL>return pyglet.event.EVENT_HANDLED<EOL><DEDENT>

Keyboard event handler handling only the escape key.

If an escape key press is detected, mouse exclusivity is toggled via :py:meth:`PengWindow.toggle_exclusivity()`\ .


def on_mouse_motion(self, x, y, dx, dy):

if not self.world.peng.window.exclusive:<EOL><INDENT>return<EOL><DEDENT>m = self.world.peng.cfg["<STR_LIT>"]<EOL>x, y = self.rot<EOL>x, y = x + dx * m, y + dy * m<EOL>y = max(-<NUM_LIT>, min(<NUM_LIT>, y))<EOL>x %= <NUM_LIT><EOL>newrot = (x,y)<EOL>self.rot= newrot<EOL>

Handles mouse motion and rotates the attached camera accordingly.

For more information about how to customize mouse movement, see the class documentation here :py:class:`WorldViewMouseRotatable()`\ .


Handler used to still enable mouse movement while a button is pressed.


def grouper(iterable, n, fillvalue=None):

args = [iter(iterable)] * n<EOL>return zip_longest(*args, fillvalue=fillvalue)<EOL>

Allows for iteration over multiple elements of a iterable at once.

``iterable`` may be any iterable, its values will be returned. Note that this may be iterated over more than once.

``n`` is the size of each group. May be any positive integer.

``fillvalue`` is optionally used to fill any groups that do not have enough items, for example if the length of the iterable is not divisible by n.

Example::

    >>> for i in grouper("foobarbaz",2,fillvalue=" "):
    ...     print(i)
    fo
    ob
    ar
    ba
    z  # Note the extra space after the z


<EOL>phi,theta = rot<EOL>phi+=<NUM_LIT> <EOL>phi,theta = math.radians(phi),math.radians(theta)<EOL>x = pos[<NUM_LIT:0>]+radius * math.sin(phi) * math.cos(theta)<EOL>y = pos[<NUM_LIT:1>]+radius * math.sin(phi) * math.sin(theta)<EOL>z = pos[<NUM_LIT:2>]+radius * math.cos(phi)<EOL>return x,y,z<EOL>

Calculates the Cartesian coordinates from spherical coordinates.

``pos`` is a simple offset to offset the result with.

``radius`` is the radius of the input.

``rot`` is a 2-tuple of ``(azimuth,polar)`` angles.

Angles are given in degrees. Most directions in this game use the same convention.

The azimuth ranges from 0 to 360 degrees with 0 degrees pointing directly to the x-axis.

The polar angle ranges from -90 to 90 with -90 degrees pointing straight down and 90 degrees straight up.

A visualization of the angles required is given in the source code of this function.


return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))<EOL>

Simple vector helper function returning the length of a vector.

``v`` may be any vector, with any number of dimensions


vmag = v_magnitude(v)<EOL>return [ v[i]/vmag  for i in range(len(v)) ]<EOL>

Normalizes the given vector.

The vector given may have any number of dimensions.


return self.rsrcMgr.getTex(self.texname,self.texcat)[<NUM_LIT:0>]<EOL>

Read-only property storing the OpenGL constant representing the target of the texture of this material.

Commonly :py:const:`GL_TEXTURE_2D` or :py:const:`GL_TEXTURE_3D`\ .

Used in texture manipulation and activation, e.g. ``glEnable(material.target)``\ .


return self.rsrcMgr.getTex(self.texname,self.texcat)[<NUM_LIT:1>]<EOL>

Read-only property storing the numerical ID of the texture of this material.

Used to manipulate the texture behind this material.

Commonly used in binding the texture: ``glBindTexture(material.target,material.id)``\ .


return self.rsrcMgr.getTex(self.texname,self.texcat)[<NUM_LIT:2>]<EOL>

Read-only property storing the texture coordinates to use when drawing with this texture.

Should not be used directly, see :py:meth:`transformTexCoords()`\ .

Enables substitution of pyglet :py:class:`pyglet.graphics.Texture` objects with Materials in many places, e.g. in :py:class:`pyglet.graphics.TextureGroup`\ .


return self.rsrcMgr.getTex(self,texname,self.texcat)<EOL>

Read-only property equivalent to a 3-tuple containing :py:attr:`target`\ , :py:attr:`id` and :py:attr:`tex_coords`\ .

Should be faster than getting each value directly. Useful if all of these values are needed.


assert dims==<NUM_LIT:2> <EOL>out = []<EOL>origcoords = self.tex_coords<EOL>min_u,min_v = origcoords[<NUM_LIT:0>],origcoords[<NUM_LIT:1>]<EOL>max_u,max_v = origcoords[<NUM_LIT:6>],origcoords[<NUM_LIT:7>]<EOL>diff_u,diff_v = max_u-min_u, max_v-min_v<EOL>itexcoords = iter(texcoords)<EOL>for u,v in zip(itexcoords,itexcoords): <EOL><INDENT>out_u = min_u+(diff_u*u)<EOL>out_v = min_v+(diff_v*v)<EOL>out.extend((out_u,out_v,<NUM_LIT:0>))<EOL><DEDENT>return out<EOL>

Transforms the given texture coordinates using the internal texture coordinates.

Currently, the dimensionality of the input texture coordinates must always be 2 and the output is 3-dimensional with the last coordinate always being zero.

The given texture coordinates are fitted to the internal texture coordinates. Note that values higher than 1 or lower than 0 may result in unexpected visual glitches.

The length of the given texture coordinates should be divisible by the dimensionality.


if "<STR_LIT>" not in data:<EOL><INDENT>data["<STR_LIT>"]={}<EOL><DEDENT>if self.name not in data["<STR_LIT>"]:<EOL><INDENT>data["<STR_LIT>"][self.name]={"<STR_LIT>":self.start_rot[:],"<STR_LIT>":self.blength}<EOL><DEDENT>

Helper method ensuring per-entity bone data has been properly initialized.

Should be called at the start of every method accessing per-entity data.

``data`` is the entity to check in dictionary form.


self.ensureBones(data)<EOL>rot = rot[<NUM_LIT:0>]%<NUM_LIT>,max(-<NUM_LIT>, min(<NUM_LIT>, rot[<NUM_LIT:1>]))<EOL>data["<STR_LIT>"][self.name]["<STR_LIT>"]=rot<EOL>

Sets the rotation of this bone on the given entity.

``data`` is the entity to modify in dictionary form.

``rot`` is the rotation of the bone in the format used in :py:func:`calcSphereCoordinates()`\ .


self.ensureBones(data)<EOL>return data["<STR_LIT>"][self.name]["<STR_LIT>"]<EOL>

Returns the rotation of this bone in the given entity.

``data`` is the entity to query in dictionary form.


self.ensureBones(data)<EOL>data["<STR_LIT>"][self.name]["<STR_LIT>"]=blength<EOL>

Sets the length of this bone on the given entity.

``data`` is the entity to modify in dictionary form.

``blength`` is the new length of the bone.


Returns the length of this bone in the given entity.

``data`` is the entity to query in dictionary form.


self.parent = parent<EOL>self.parent.child_bones[self.name]=self<EOL>

Sets the parent of this bone for all entities.

Note that this method must be called before many other methods to ensure internal state has been initialized.

This method also registers this bone as a child of its parent.


self.parent.setRotate(data)<EOL>glPushMatrix()<EOL>x,y = self.getRot(data)<EOL>pivot = self.getPivotPoint(data)<EOL>px,py,pz = pivot<EOL>normx = [<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:0>] <EOL>normy = [<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>]<EOL>glTranslatef(px,py,pz)<EOL>glRotatef(x-self.start_rot[<NUM_LIT:0>], normx[<NUM_LIT:0>],normx[<NUM_LIT:1>],normx[<NUM_LIT:2>])<EOL>glRotatef(y-self.start_rot[<NUM_LIT:1>], normy[<NUM_LIT:0>],normy[<NUM_LIT:1>],normy[<NUM_LIT:2>])<EOL>glTranslatef(-px,-py,-pz)<EOL>

Sets the OpenGL state required for proper drawing of the model.

Mostly rotates and translates the camera.

It is important to call :py:meth:`unsetRotate()` after calling this method to properly unset state and avoid OpenGL errors.


glPopMatrix()<EOL>self.parent.unsetRotate(data)<EOL>

Unsets the OpenGL state that was set before calling :py:meth:`setRotate()`\ .

Note that this method may cause various OpenGL errors if called without :py:meth:`setRotate()` having been called.


ppos = self.parent.getPivotPoint(data)<EOL>rot = self.parent.getRot(data)<EOL>length = self.parent.getLength(data)<EOL>out = calcSphereCoordinates(ppos,length,rot)<EOL>return out<EOL>

Returns the point this bone pivots around on the given entity.

This method works recursively by calling its parent and then adding its own offset.

The resulting coordinate is relative to the entity, not the world.


assert dims==<NUM_LIT:3><EOL>return vertices<EOL>

Currently unused method that transforms the given vertices according to the rotation of the bone.

Currently just returns the vertices unmodified, will be implemented in the future.


self.regions[region.name]=region<EOL>

Register a vertex Region as a dependent of this bone.

``region`` must be an instance of :py:class:`Region`\ .


return self.bone.transformVertices(data,self.vertices,self.dims)<EOL>

Returns the vertices of this region already transformed and ready-to-use.

Internally uses :py:meth:`Bone.transformVertices()`\ .


return self.geometry_type<EOL>

Returns the OpenGL constant representing the type of primitives used by this region.

May be one of :py:data:`GL_QUADS`\ , :py:data:`GL_TRIANGLES`\ , :py:data:`GL_LINES` or :py:data:`GL_POINTS`\ .


return self.material.transformTexCoords(data,self.tex_coords,self.tex_dims)<EOL>

Returns the texture coordinates, if any, to accompany the vertices of this region already transformed.

Note that it is recommended to check the :py:attr:`enable_tex` flag first.

Internally uses :py:meth:`Material.transformTexCoords()`\ .


return self.material.texdata<EOL>

Returns informations about the texture of this region.

Internally uses :py:attr:`Material.texdata`\ , exact specification available there.


self.bones = bones<EOL>

Sets the internal dictionary of bones in the parent model.

Must be a dictionary, else errors may appear later on.


data["<STR_LIT>"]={}<EOL>adata = data["<STR_LIT>"]<EOL>adata["<STR_LIT>"]=<NUM_LIT:0><EOL>adata["<STR_LIT>"]=time.time()<EOL>adata["<STR_LIT>"]=jumptype<EOL>adata["<STR_LIT>"]="<STR_LIT>"<EOL>

Callback that is called to initialize this animation on a specific actor.

Internally sets the ``_anidata`` key of the given dict ``data``\ .

``jumptype`` is either ``jump`` or ``animate`` to define how to switch to this animation.


adata = data["<STR_LIT>"]<EOL>if adata.get("<STR_LIT>",self.name)!=self.name:<EOL><INDENT>return <EOL><DEDENT>dt = time.time()-adata.get("<STR_LIT>",time.time())<EOL>adata["<STR_LIT>"]=time.time()<EOL>if adata.get("<STR_LIT>","<STR_LIT>")=="<STR_LIT>":<EOL><INDENT>if adata.get("<STR_LIT>",self.default_jt)=="<STR_LIT>":<EOL><INDENT>for bone,dat in self.start_frame.get("<STR_LIT>",{}).items():<EOL><INDENT>if "<STR_LIT>" in dat:<EOL><INDENT>self.bones[bone].setRot(data,dat["<STR_LIT>"])<EOL><DEDENT>if "<STR_LIT>" in dat:<EOL><INDENT>self.bones[bone].setLength(data,dat["<STR_LIT>"])<EOL><DEDENT><DEDENT>adata["<STR_LIT>"]="<STR_LIT>"<EOL>if self.atype=="<STR_LIT>":<EOL><INDENT>adata["<STR_LIT>"]=self.start_frame.get("<STR_LIT>",<NUM_LIT:0>)<EOL><DEDENT><DEDENT>elif adata.get("<STR_LIT>",self.default_jt)=="<STR_LIT>":<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL>if "<STR_LIT>" not in adata:<EOL><INDENT>adata["<STR_LIT>"] = <NUM_LIT:0><EOL><DEDENT>tlen = self.anidata.get("<STR_LIT>",self.anidata.get("<STR_LIT>",<NUM_LIT>)/<NUM_LIT:3>)<EOL>tspeed = self.anidata.get("<STR_LIT>",self.anidata.get("<STR_LIT>",<NUM_LIT>))<EOL>framediff=int(dt/(<NUM_LIT:1.>/tspeed)) <EOL>overhang = dt-(framediff*(<NUM_LIT:1.>/tspeed)) <EOL>adata["<STR_LIT>"]-=overhang <EOL>if framediff == <NUM_LIT:0>:<EOL><INDENT>return <EOL><DEDENT>frame1 = adata["<STR_LIT>"]<EOL>adata["<STR_LIT>"]+=framediff<EOL>if adata["<STR_LIT>"]>tlen:<EOL><INDENT>adata["<STR_LIT>"]="<STR_LIT>"<EOL>if self.atype=="<STR_LIT>":<EOL><INDENT>adata["<STR_LIT>"]=self.start_frame.get("<STR_LIT>",<NUM_LIT:0>)<EOL><DEDENT>return<EOL><DEDENT>frame2 = adata["<STR_LIT>"]<EOL>if "<STR_LIT>" not in adata:<EOL><INDENT>frombones = {}<EOL>for bname,bone in self.bones.items():<EOL><INDENT>frombones[bname]={"<STR_LIT>":bone.getRot(data),"<STR_LIT>":bone.getLength(data)}<EOL><DEDENT>adata["<STR_LIT>"] = frombones<EOL><DEDENT>if "<STR_LIT>" not in adata:<EOL><INDENT>tobones = {}<EOL>for bname,bone in self.start_frame["<STR_LIT>"].items():<EOL><INDENT>tobones[bname]=bone<EOL><DEDENT>adata["<STR_LIT>"] = tobones<EOL><DEDENT>frombones = adata["<STR_LIT>"]<EOL>tobones = adata["<STR_LIT>"]<EOL>from_frame = <NUM_LIT:0><EOL>to_frame = tlen<EOL>for bname,bone in self.bones.items():<EOL><INDENT>if bname not in frombones or bname not in tobones:<EOL><INDENT>continue<EOL><DEDENT>from_rot = frombones[bname]["<STR_LIT>"]<EOL>to_rot = tobones[bname]["<STR_LIT>"]<EOL>from_x,from_y=from_rot<EOL>to_x,to_y=to_rot<EOL>delta_per_frame_x = (to_x-from_x)/(to_frame-from_frame)<EOL>delta_per_frame_y = (to_y-from_y)/(to_frame-from_frame)<EOL>delta_x = delta_per_frame_x*(frame2-frame1)<EOL>delta_y = delta_per_frame_y*(frame2-frame1)<EOL>rot = bone.getRot(data)<EOL>new_rot = [rot[<NUM_LIT:0>]+delta_x,rot[<NUM_LIT:1>]+delta_y]<EOL>bone.setRot(data,new_rot)<EOL><DEDENT><DEDENT><DEDENT>elif adata["<STR_LIT>"]=="<STR_LIT>":<EOL><INDENT>if self.atype == "<STR_LIT>":<EOL><INDENT>pass <EOL><DEDENT>elif self.atype == "<STR_LIT>":<EOL><INDENT>framediff=int(dt/(<NUM_LIT:1.>/self.kps)) <EOL>overhang = dt-(framediff*(<NUM_LIT:1.>/self.kps)) <EOL>adata["<STR_LIT>"]-=overhang <EOL>if framediff == <NUM_LIT:0>:<EOL><INDENT>return <EOL><DEDENT>frame1 = adata["<STR_LIT>"]<EOL>adata["<STR_LIT>"]+=framediff<EOL>if adata["<STR_LIT>"]>self.anilength:<EOL><INDENT>repeat = True<EOL>adata["<STR_LIT>"]%=self.anilength<EOL><DEDENT>else:<EOL><INDENT>repeat = False<EOL><DEDENT>frame2 = adata["<STR_LIT>"]<EOL>if repeat:<EOL><INDENT>frame1 = frame2<EOL>frame2+=<NUM_LIT:1><EOL><DEDENT>for bname,bone in self.bones.items():<EOL><INDENT>if bname in self.rframes_per_bone:<EOL><INDENT>from_frame = None<EOL>to_frame = None<EOL>for framenum,rot in self.rframes_per_bone[bname].items():<EOL><INDENT>if (from_frame is None or framenum>from_frame) and framenum<=frame1:<EOL><INDENT>from_frame = framenum<EOL><DEDENT>if (to_frame is None or framenum<to_frame) and framenum>=frame2:<EOL><INDENT>to_frame = framenum<EOL><DEDENT><DEDENT>if from_frame is None or to_frame is None:<EOL><INDENT>raise ValueError("<STR_LIT>"%(bname,self.name))<EOL><DEDENT>if from_frame==to_frame or repeat:<EOL><INDENT>if self.anidata.get("<STR_LIT>","<STR_LIT>")=="<STR_LIT>":<EOL><INDENT>for b,dat in self.start_frame.get("<STR_LIT>",{}).items():<EOL><INDENT>if "<STR_LIT>" in dat:<EOL><INDENT>self.bones[b].setRot(data,dat["<STR_LIT>"])<EOL><DEDENT>if "<STR_LIT>" in dat:<EOL><INDENT>self.bones[b].setLength(data,dat["<STR_LIT>"])<EOL><DEDENT><DEDENT><DEDENT>elif self.anidata.get("<STR_LIT>","<STR_LIT>")=="<STR_LIT>":<EOL><INDENT>from_frame = adata["<STR_LIT>"]<EOL><DEDENT><DEDENT>adata["<STR_LIT>"]=from_frame<EOL>adata["<STR_LIT>"]=to_frame<EOL>from_rot = self.rframes_per_bone[bname][from_frame]<EOL>to_rot = self.rframes_per_bone[bname][to_frame]<EOL>from_x,from_y=from_rot<EOL>to_x,to_y=to_rot<EOL>if self.anidata.get("<STR_LIT>","<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>delta_per_frame_x = (to_x-from_x)/(to_frame-from_frame)<EOL>delta_per_frame_y = (to_y-from_y)/(to_frame-from_frame)<EOL>delta_x = delta_per_frame_x*(frame2-frame1)<EOL>delta_y = delta_per_frame_y*(frame2-frame1)<EOL>rot = bone.getRot(data)<EOL>new_rot = [rot[<NUM_LIT:0>]+delta_x,rot[<NUM_LIT:1>]+delta_y]<EOL><DEDENT>elif self.anidata["<STR_LIT>"] == "<STR_LIT>":<EOL><INDENT>new_rot = to_x,to_y<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.anidata["<STR_LIT>"],self.name))<EOL><DEDENT>bone.setRot(data,new_rot)<EOL><DEDENT>if bname in self.lframes_per_bone:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"%(self.atype,name))<EOL><DEDENT><DEDENT>

Callback that should be called regularly to update the animation.

It is recommended to call this method about 60 times a second for smooth animations. Irregular calling of this method will be automatically adjusted.

This method sets all the bones in the given actor to the next state of the animation.

Note that :py:meth:`startAnimation()` must have been called before calling this method.


x,y,z = self.obj.pos<EOL>glTranslatef(x,y,z)<EOL>

Sets the state required for this actor.

Currently translates the matrix to the position of the actor.


x,y,z = self.obj.pos<EOL>glTranslatef(-x,-y,-z)<EOL>

Resets the state required for this actor to the default state.

Currently resets the matrix to its previous translation.


glEnable(self.region.material.target)<EOL>glBindTexture(self.region.material.target, self.region.material.id)<EOL>self.region.bone.setRotate(self.data)<EOL>

Sets the state required for this vertex region.

Currently binds and enables the texture of the material of the region.


glDisable(self.region.material.target)<EOL>self.region.bone.unsetRotate(self.data)<EOL>

Resets the state required for this actor to the default state.

Currently only disables the target of the texture of the material, it may still be bound.


if not hasattr(obj,"<STR_LIT>"):<EOL><INDENT>self.create(obj,cache=True)<EOL><DEDENT>if "<STR_LIT>" not in obj._modeldata:<EOL><INDENT>self.create(obj,cache=True)<EOL><DEDENT>

Ensures that the given ``obj`` has been initialized to be used with this model.

If the object is found to not be initialized, it will be initialized.


obj._modeldata = {}<EOL>data = obj._modeldata<EOL>data["<STR_LIT>"]=self<EOL>data["<STR_LIT>"] = {}<EOL>moddata = data["<STR_LIT>"]<EOL>moddata["<STR_LIT>"] = JSONModelGroup(self,data,obj)<EOL>modgroup = moddata["<STR_LIT>"]<EOL>if not hasattr(obj,"<STR_LIT>"):<EOL><INDENT>obj.batch3d = pyglet.graphics.Batch()<EOL>data["<STR_LIT>"]=True<EOL><DEDENT>moddata["<STR_LIT>"] = {}<EOL>for name,region in self.modeldata["<STR_LIT>"].items():<EOL><INDENT>v = region.getVertices(data)<EOL>vlistlen = int(len(v)/region.dims)<EOL>if region.enable_tex:<EOL><INDENT>vlist = obj.batch3d.add(vlistlen,region.getGeometryType(data),JSONRegionGroup(self,data,region,modgroup),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>)<EOL><DEDENT>else:<EOL><INDENT>vlist = obj.batch3d.add(vlistlen,region.getGeometryType(data),modgroup,<EOL>"<STR_LIT>",<EOL>)<EOL><DEDENT>moddata["<STR_LIT>"][name]=vlist<EOL><DEDENT>self.setAnimation(obj,self.modeldata["<STR_LIT>"].name,transition="<STR_LIT>")<EOL>self.data = data<EOL>if not cache:<EOL><INDENT>self.redraw(obj)<EOL><DEDENT>

Initializes per-actor data on the given object for this model.

If ``cache`` is set to True, the entity will not be redrawn after initialization.

Note that this method may set several attributes on the given object, most of them starting with underscores.

During initialization of vertex regions, several vertex lists will be created.
If the given object has an attribute called ``batch3d`` it will be used, else it will be created.

If the batch already existed, the :py:meth:`draw()` method will do nothing, else it will draw the batch.

Memory leaks may occur if this is called more than once on the same object without calling :py:meth:`cleanup()` first.


if not hasattr(obj,"<STR_LIT>"):<EOL><INDENT>return <EOL><DEDENT>data = obj._modeldata<EOL>if "<STR_LIT>" in data:<EOL><INDENT>moddata = data["<STR_LIT>"]<EOL>if "<STR_LIT>" in moddata:<EOL><INDENT>for vlist in list(moddata["<STR_LIT>"].keys()):<EOL><INDENT>del moddata["<STR_LIT>"][vlist]<EOL><DEDENT>del moddata["<STR_LIT>"]<EOL><DEDENT><DEDENT>if "<STR_LIT>" in data:<EOL><INDENT>for bone in list(data["<STR_LIT>"].keys()):<EOL><INDENT>del data["<STR_LIT>"][bone]<EOL><DEDENT>del data["<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in data:<EOL><INDENT>adata = data["<STR_LIT>"]<EOL>if "<STR_LIT>" in adata:<EOL><INDENT>pyglet.clock.unschedule(adata["<STR_LIT>"])<EOL><DEDENT><DEDENT>if data.get("<STR_LIT>",False):<EOL><INDENT>del obj.batch3d<EOL><DEDENT>if "<STR_LIT>" not in data:<EOL><INDENT>return<EOL><DEDENT>moddata = data["<STR_LIT>"]<EOL>if "<STR_LIT>" in moddata:<EOL><INDENT>moddata["<STR_LIT>"].delete() <EOL><DEDENT>if "<STR_LIT>" in moddata:<EOL><INDENT>del moddata["<STR_LIT>"]<EOL><DEDENT>del data["<STR_LIT>"], moddata<EOL>

Cleans up any left over data structures, including vertex lists that reside in GPU memory.

Behaviour is undefined if it is attempted to use this model with the same object without calling :py:meth:`create()` first.

It is very important to call this method manually during deletion as this will delete references to data objects stored in global variables of third-party modules.


self.ensureModelData(obj)<EOL>data = obj._modeldata<EOL>vlists = data["<STR_LIT>"]["<STR_LIT>"]<EOL>for name,region in self.modeldata["<STR_LIT>"].items():<EOL><INDENT>vlists[name].vertices = region.getVertices(data)<EOL>if region.enable_tex:<EOL><INDENT>vlists[name].tex_coords = region.getTexCoords(data)<EOL><DEDENT><DEDENT>

Redraws the model of the given object.

Note that currently this method probably won't change any data since all movement and animation is done through pyglet groups.


self.ensureModelData(obj)<EOL>data = obj._modeldata<EOL>if data.get("<STR_LIT>",False):<EOL><INDENT>obj.batch3d.draw()<EOL><DEDENT>

Actually draws the model of the given object to the render target.

Note that if the batch used for this object already existed, drawing will be skipped as the batch should be drawn by the owner of it.


<EOL>self.cleanup(obj)<EOL>

Called if the actor is removed from the world.

Can be extended for custom features, currently calls :py:meth:`cleanup()`\ .


self.ensureModelData(obj)<EOL>data = obj._modeldata<EOL>if animation not in self.modeldata["<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>"%(animation,self.modelname))<EOL><DEDENT>if data.get("<STR_LIT>",{}).get("<STR_LIT>",None)==animation and not force:<EOL><INDENT>return <EOL><DEDENT>anim = self.modeldata["<STR_LIT>"][animation]<EOL>if transition is None:<EOL><INDENT>transition = anim.default_jt<EOL><DEDENT>anim.startAnimation(data,transition)<EOL>if "<STR_LIT>" not in data:<EOL><INDENT>data["<STR_LIT>"]={}<EOL><DEDENT>adata = data["<STR_LIT>"]<EOL>adata["<STR_LIT>"]=animation<EOL>if "<STR_LIT>" in adata:<EOL><INDENT>pyglet.clock.unschedule(adata["<STR_LIT>"])<EOL><DEDENT>def schedfunc(*args):<EOL><INDENT>anim.tickEntity(data)<EOL><DEDENT>pyglet.clock.schedule_interval(schedfunc,<NUM_LIT:1.>/(anim.kps if anim.atype=="<STR_LIT>" else <NUM_LIT>))<EOL>adata["<STR_LIT>"] = schedfunc<EOL>

Sets the animation to be used by the object.

See :py:meth:`Actor.setAnimation()` for more information.


pass<EOL>

Fake event handler called when this camera is made current by a :py:class:`WorldView()` object.


pass<EOL>

Fake event handler called when this camera is rotated.

The ``old`` and ``new`` parameters are both rotations and are not equal. Each parameter is a 2-tuple of ``(yaw,pitch)``\ .


pass<EOL>

Fake event handler called when this camera moves.

The ``old`` and ``new`` parameters are both 3D Locations and are not equal. Each parameter is a 3-tuple of ``(x,y,z)`` in world coordinates.


return self._pos<EOL>

Property for accessing the position of the camera.

This property uses a setter to call the :py:meth:`on_move()` method if set and the new location is not equal to the old location.


return self._rot<EOL>

Property for accessing the rotation of the camera.

This property uses a setter to call the :py:meth:`on_rotate()` method if set and the new location is not equal to the old location.


return self.actor.pos<EOL>

This property always equals the value of ``self.actor.pos``\ .

This property may also be written to.


return self.actor.rot<EOL>

This property always equals the value of ``self.actor.rot``\ .

This property may also be written to.


if self._setup:<EOL><INDENT>return<EOL><DEDENT>self._setup = True<EOL>if self.cfg["<STR_LIT>"] is not None:<EOL><INDENT>self.set_minimum_size(*self.cfg["<STR_LIT>"])<EOL><DEDENT>if self.cfg["<STR_LIT>"] is not None:<EOL><INDENT>self.set_maximum_size(*self.cfg["<STR_LIT>"])<EOL><DEDENT>glClearColor(*self.cfg["<STR_LIT>"])<EOL>glEnable(GL_DEPTH_TEST)<EOL>glEnable(GL_BLEND)<EOL>glShadeModel(GL_SMOOTH)<EOL>if self.cfg["<STR_LIT>"]["<STR_LIT>"]:<EOL><INDENT>self.setupFog()<EOL><DEDENT>if self.cfg["<STR_LIT>"]["<STR_LIT>"]:<EOL><INDENT>self.setupLight()<EOL><DEDENT>

Sets up the OpenGL state.

This method should be called once after the config has been created and before the main loop is started.
You should not need to manually call this method, as it is automatically called by :py:meth:`run()`\ .

Repeatedly calling this method has no effects.


fogcfg = self.cfg["<STR_LIT>"]<EOL>if not fogcfg["<STR_LIT>"]:<EOL><INDENT>return<EOL><DEDENT>glEnable(GL_FOG)<EOL>if fogcfg["<STR_LIT>"] is None:<EOL><INDENT>fogcfg["<STR_LIT>"] = self.cfg["<STR_LIT>"]<EOL><DEDENT>glFogfv(GL_FOG_COLOR, (GLfloat * <NUM_LIT:4>)(*fogcfg["<STR_LIT>"]))<EOL>glHint(GL_FOG_HINT, GL_DONT_CARE) <EOL>glFogi(GL_FOG_MODE, GL_LINEAR)<EOL>glFogf(GL_FOG_START, fogcfg["<STR_LIT:start>"])<EOL>glFogf(GL_FOG_END, fogcfg["<STR_LIT:end>"])<EOL>

Sets the fog system up.

The specific options available are documented under :confval:`graphics.fogSettings`\ .


raise NotImplementedError("<STR_LIT>")<EOL>

Sets the light system up.

The specific options available are documented under :confval:`graphics.lightSettings`\ .

Note that this feature is currently not implemented.


self.setup()<EOL>if evloop is not None:<EOL><INDENT>pyglet.app.event_loop = evloop<EOL><DEDENT>pyglet.app.run() <EOL>

Runs the application in the current thread.

This method should not be called directly, especially when using multiple windows, use :py:meth:`Peng.run()` instead.

Note that this method is blocking as rendering needs to happen in the main thread.
It is thus recommendable to run your game logic in another thread that should be started before calling this method.

``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.


if menu not in self.menus:<EOL><INDENT>raise ValueError("<STR_LIT>"%menu)<EOL><DEDENT>elif menu == self.activeMenu:<EOL><INDENT>return <EOL><DEDENT>old = self.activeMenu<EOL>self.activeMenu = menu<EOL>if old is not None:<EOL><INDENT>self.menus[old].on_exit(menu)<EOL>self.menus[old].doAction("<STR_LIT>")<EOL><DEDENT>self.menu.on_enter(old)<EOL>self.menu.doAction("<STR_LIT>")<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT>":self,"<STR_LIT>":old,"<STR_LIT>":menu})<EOL>

Changes to the given menu.

``menu`` must be a valid menu name that is currently known.

.. versionchanged:: 1.2a1

   The push/pop handlers have been deprecated in favor of the new :py:meth:`Menu.on_enter() <peng3d.menu.Menu.on_enter>`\ , :py:meth:`Menu.on_exit() <peng3d.menu.Menu.on_exit>`\ , etc. events.


<EOL>self.menus[menu.name]=menu<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT>":self,"<STR_LIT>":menu})<EOL>


self.clear()<EOL>self.menu.draw()<EOL>

Clears the screen and draws the currently active menu.


super(PengWindow,self).dispatch_event(event_type,*args)<EOL>try:<EOL><INDENT>p = self.peng<EOL>m = self.menu<EOL><DEDENT>except AttributeError:<EOL><INDENT>if hasattr(self,"<STR_LIT>") and self.peng.cfg["<STR_LIT>"]:<EOL><INDENT>print("<STR_LIT>")<EOL>traceback.print_exc()<EOL><DEDENT>return<EOL><DEDENT>p.handleEvent(event_type,args,self)<EOL>self.handleEvent(event_type,args)<EOL>m.handleEvent(event_type,args)<EOL>

Internal event handling method.

This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods.

By default, :py:meth:`Peng.handleEvent()`\ , :py:meth:`handleEvent()` and :py:meth:`Menu.handleEvent()` are called in this order to handle events.

Note that some events may not be handled by all handlers during early startup.


return self.menus[self.activeMenu]<EOL>

Property for accessing the currently active menu.

Always equals ``self.menus[self.activeMenu]``\ .

This property is read-only.


if override is not None:<EOL><INDENT>new = override<EOL><DEDENT>else:<EOL><INDENT>new = not self.exclusive<EOL><DEDENT>self.exclusive = new<EOL>self.set_exclusive_mouse(self.exclusive)<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT>":self,"<STR_LIT>":self.exclusive})<EOL>

Toggles mouse exclusivity via pyglet's :py:meth:`set_exclusive_mouse()` method.

If ``override`` is given, it will be used instead.

You may also read the current exclusivity state via :py:attr:`exclusive`\ .


<EOL>glDisable(GL_LIGHTING)<EOL>glPolygonMode( GL_FRONT_AND_BACK, GL_FILL)<EOL>width, height = self.get_size()<EOL>glDisable(GL_DEPTH_TEST)<EOL>glViewport(<NUM_LIT:0>, <NUM_LIT:0>, width, height)<EOL>glMatrixMode(GL_PROJECTION)<EOL>glLoadIdentity()<EOL>glOrtho(<NUM_LIT:0>, width, <NUM_LIT:0>, height, -<NUM_LIT:1>, <NUM_LIT:1>)<EOL>glMatrixMode(GL_MODELVIEW)<EOL>glLoadIdentity()<EOL>

Configures OpenGL to draw in 2D.

Note that wireframe mode is always disabled in 2D-Mode, but can be re-enabled by calling ``glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)``\ .


if not isinstance(cam,camera.Camera):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if self.cfg["<STR_LIT>"]:<EOL><INDENT>glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)<EOL><DEDENT>width, height = self.get_size()<EOL>glEnable(GL_DEPTH_TEST)<EOL>glViewport(<NUM_LIT:0>, <NUM_LIT:0>, width, height)<EOL>glMatrixMode(GL_PROJECTION)<EOL>glLoadIdentity()<EOL>gluPerspective(self.cfg["<STR_LIT>"], width / float(height), self.cfg["<STR_LIT>"], self.cfg["<STR_LIT>"]) <EOL>glMatrixMode(GL_MODELVIEW)<EOL>glLoadIdentity()<EOL>x, y = cam.rot<EOL>glRotatef(x, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>)<EOL>glRotatef(-y, math.cos(math.radians(x)), <NUM_LIT:0>, math.sin(math.radians(x)))<EOL>x, y, z = cam.pos<EOL>glTranslatef(-x, -y, -z)<EOL>

Configures OpenGL to draw in 3D.

This method also applies the correct rotation and translation as set in the supplied camera ``cam``\ .
It is discouraged to use :py:func:`glTranslatef()` or :py:func:`glRotatef()` directly as this may cause visual glitches.

If you need to configure any of the standard parameters, see the docs about :doc:`/configoption`\ .

The :confval:`graphics.wireframe` config value can be used to enable a wireframe mode, useful for debugging visual glitches.


def _get_region(self, buffer, start, count):

byte_start = self.stride * start<EOL>byte_size = self.stride * count<EOL>array_count = self.count * count<EOL>if self.stride == self.size or not array_count:<EOL><INDENT>ptr_type = ctypes.POINTER(self.c_type * array_count)<EOL>return buffer.get_region(byte_start, byte_size, ptr_type)<EOL><DEDENT>else:<EOL><INDENT>byte_start += self.offset<EOL>byte_size -= self.offset<EOL>elem_stride = self.stride // ctypes.sizeof(self.c_type)<EOL>elem_offset = self.offset // ctypes.sizeof(self.c_type)<EOL>ptr_type = ctypes.POINTER(<EOL>self.c_type * int((count * elem_stride - elem_offset)))<EOL>region = buffer.get_region(byte_start, byte_size, ptr_type)<EOL>return vertexbuffer.IndirectArrayRegion(<EOL>region, array_count, self.count, elem_stride)<EOL><DEDENT>

Map a buffer region using this attribute as an accessor.

    The returned region can be modified as if the buffer was a contiguous
    array of this attribute (though it may actually be interleaved or
    otherwise non-contiguous).

    The returned region consists of a contiguous array of component
    data elements.  For example, if this attribute uses 3 floats per
    vertex, and the `count` parameter is 4, the number of floats mapped
    will be ``3 * 4 = 12``.

    :Parameters:
        `buffer` : `AbstractMappable`
            The buffer to map.
        `start` : int
            Offset of the first vertex to map.
        `count` : int
            Number of vertices to map

    :rtype: `AbstractBufferRegion`


def _draw(self, mode, vertex_list=None):

glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)<EOL>for buffer, attributes in self.buffer_attributes:<EOL><INDENT>buffer.bind()<EOL>for attribute in attributes:<EOL><INDENT>attribute.enable()<EOL>attribute.set_pointer(attribute.buffer.ptr)<EOL><DEDENT><DEDENT>if vertexbuffer._workaround_vbo_finish:<EOL><INDENT>glFinish()<EOL><DEDENT>if vertex_list is not None:<EOL><INDENT>glDrawArrays(mode, vertex_list.start, vertex_list.count)<EOL><DEDENT>else:<EOL><INDENT>starts, sizes = self.allocator.get_allocated_regions()<EOL>primcount = len(starts)<EOL>if primcount == <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>elif primcount == <NUM_LIT:1>:<EOL><INDENT>glDrawArrays(mode, starts[<NUM_LIT:0>], int(sizes[<NUM_LIT:0>]))<EOL><DEDENT>elif gl_info.have_version(<NUM_LIT:1>, <NUM_LIT:4>):<EOL><INDENT>starts = (GLint * primcount)(*starts)<EOL>sizes = (GLsizei * primcount)(*sizes)<EOL>glMultiDrawArrays(mode, starts, sizes, primcount)<EOL><DEDENT>else:<EOL><INDENT>for start, size in zip(starts, sizes):<EOL><INDENT>glDrawArrays(mode, start, size)<EOL><DEDENT><DEDENT><DEDENT>for buffer, _ in self.buffer_attributes:<EOL><INDENT>buffer.unbind()<EOL><DEDENT>glPopClientAttrib()<EOL>

Draw vertices in the domain.

    If `vertex_list` is not specified, all vertices in the domain are
    drawn.  This is the most efficient way to render primitives.

    If `vertex_list` specifies a `VertexList`, only primitives in that
    list will be drawn.

    :Parameters:
        `mode` : int
            OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.
        `vertex_list` : `VertexList`
            Vertex list to draw, or ``None`` for all lists in this domain.


pyglet.graphics.vertexattribute.AbstractAttribute.get_region = _get_region<EOL>pyglet.graphics.vertexbuffer.MappableVertexBufferObject.bind = _bind<EOL>pyglet.graphics.vertexbuffer.IndirectArrayRegion.__setitem__ = _iar__setitem__<EOL>pyglet.graphics.vertexdomain.VertexDomain.draw = _draw<EOL>

Patches the :py:mod:`pyglet.graphics.vertexattribute`\ , :py:mod:`pyglet.graphics.vertexbuffer` and :py:mod:`pyglet.graphics.vertexdomain` modules.

This patch is only needed with Python 3.x and will be applied automatically when initializing :py:class:`Peng()`\ .

The patches consist of simply converting some list indices, slices and other numbers to integers from floats with .0. These patches have not been tested thoroughly, but work with at least ``test.py`` and ``test_gui.py``\ .

Can be enabled and disabled via :confval:`pyglet.patch.patch_float2int`\ .


nsplit = name.split("<STR_LIT::>")[<NUM_LIT:1>].split("<STR_LIT:.>")<EOL>return os.path.join(self.basepath,"<STR_LIT>",name.split("<STR_LIT::>")[<NUM_LIT:0>],*nsplit)+ext<EOL>

Converts the given resource name to a file path.

A resource path is of the format ``<app>:<cat1>.<cat2>.<name>`` where cat1 and cat2 can be repeated as often as desired.

``ext`` is the file extension to use, e.g. ``.png`` or similar.

As an example, the resource name ``peng3d:some.category.foo`` with the extension ``.png`` results in the path ``<basepath>/assets/peng3d/some/category/foo.png``\ .

This resource naming scheme is used by most other methods of this class.

Note that it is currently not possible to define multiple base paths to search through.


return os.path.exists(self.resourceNameToPath(name,ext))<EOL>

Returns whether or not the resource with the given name and extension exists.

This must not mean that the resource is meaningful, it simply signals that the file exists.


Adds a new texture category with the given name.

If the category already exists, it will be overridden.


if category not in self.categoriesTexCache:<EOL><INDENT>return self.getMissingTex(category)<EOL><DEDENT>if name not in self.categoriesTexCache[category]:<EOL><INDENT>self.loadTex(name,category)<EOL><DEDENT>return self.categoriesTexCache[category][name]<EOL>

Gets the texture associated with the given name and category.

``category`` must have been created using :py:meth:`addCategory()` before.

If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache.

See :py:meth:`loadTex()` for more information.


try:<EOL><INDENT>img = pyglet.image.load(self.resourceNameToPath(name,"<STR_LIT>"))<EOL><DEDENT>except FileNotFoundError:<EOL><INDENT>img = self.getMissingTexture()<EOL><DEDENT>texreg = self.categoriesTexBin[category].add(img)<EOL>self.categories[category][name]=texreg<EOL>target = texreg.target<EOL>texid = texreg.id<EOL>texcoords = texreg.tex_coords<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)<EOL>glGenerateMipmap(GL_TEXTURE_2D)<EOL>out = target,texid,texcoords<EOL>self.categoriesTexCache[category][name]=out<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT:name>":name,"<STR_LIT>":category})<EOL>return out<EOL>

Loads the texture of the given name and category.

All textures currently must be PNG files, although support for more formats may be added soon.

If the texture cannot be found, a missing texture will instead be returned. See :py:meth:`getMissingTexture()` for more information.

Currently, all texture mipmaps will be generated and the filters will be set to
:py:const:`GL_NEAREST` for the magnification filter and :py:const:`GL_NEAREST_MIPMAP_LINEAR` for the minification filter.
This results in a pixelated texture and not  a blurry one.


if self.missingTexture is None:<EOL><INDENT>if self.resourceExists(self.missingtexturename,"<STR_LIT>"):<EOL><INDENT>self.missingTexture = pyglet.image.load(self.resourceNameToPath(self.missingtexturename,"<STR_LIT>"))<EOL>return self.missingTexture<EOL><DEDENT>else: <EOL><INDENT>self.missingTexture = pyglet.image.create(<NUM_LIT:1>,<NUM_LIT:1>,pyglet.image.SolidColorImagePattern([<NUM_LIT:255>,<NUM_LIT:0>,<NUM_LIT:255>,<NUM_LIT:255>]))<EOL>return self.missingTexture<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self.missingTexture<EOL><DEDENT>

Returns a texture to be used as a placeholder for missing textures.

A default missing texture file is provided in the assets folder of the source distribution.
It consists of a simple checkerboard pattern of purple and black, this image may be copied to any project using peng3d for similar behavior.

If this texture cannot be found, a pattern is created in-memory, simply a solid square of purple.

This texture will also be cached separately from other textures.


texreg = self.categoriesTexBin[category].add(img)<EOL>self.categories[category][name]=texreg<EOL>target = texreg.target<EOL>texid = texreg.id<EOL>texcoords = texreg.tex_coords<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)<EOL>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)<EOL>glGenerateMipmap(GL_TEXTURE_2D)<EOL>out = target,texid,texcoords<EOL>self.categoriesTexCache[category][name]=out<EOL>return out<EOL>

Adds a new texture from the given image.

``img`` may be any object that supports Pyglet-style copying in form of the ``blit_to_texture()`` method.

This can be used to add textures that come from non-file sources, e.g. Render-to-texture.


if name in self.modelobjcache:<EOL><INDENT>return self.modelobjcache[name]<EOL><DEDENT>return self.loadModel(name)<EOL>

Gets the model object by the given name.

If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache.


m = model.Model(self.peng,self,name)<EOL>self.modelobjcache[name]=m<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT:name>":name})<EOL>return m<EOL>

Loads the model of the given name.

The model will also be inserted into the cache.


if name in self.modelcache:<EOL><INDENT>return self.modelcache[name]<EOL><DEDENT>return self.loadModelData(name)<EOL>

Gets the model data associated with the given name.

If it was loaded, a cached copy will be returned.
It it was not loaded, it will be loaded and cached.


path = self.resourceNameToPath(name,"<STR_LIT>")<EOL>try:<EOL><INDENT>data = json.load(open(path,"<STR_LIT:r>"))<EOL><DEDENT>except Exception:<EOL><INDENT>print("<STR_LIT>")<EOL>import traceback;traceback.print_exc()<EOL>return {}<EOL><DEDENT>out = {}<EOL>if data.get("<STR_LIT:version>",<NUM_LIT:1>)==<NUM_LIT:1>:<EOL><INDENT>out["<STR_LIT>"]={}<EOL>for name,matdata in data.get("<STR_LIT>",{}).items():<EOL><INDENT>m = model.Material(self,name,matdata)<EOL>out["<STR_LIT>"][name]=m<EOL><DEDENT>out["<STR_LIT>"]=out["<STR_LIT>"][data.get("<STR_LIT>",list(out["<STR_LIT>"].keys())[<NUM_LIT:0>])]<EOL>out["<STR_LIT>"]={"<STR_LIT>":model.RootBone(self,"<STR_LIT>",{"<STR_LIT>":[<NUM_LIT:0>,<NUM_LIT:0>],"<STR_LIT>":<NUM_LIT:0>})}<EOL>for name,bonedata in data.get("<STR_LIT>",{}).items():<EOL><INDENT>b = model.Bone(self,name,bonedata)<EOL>out["<STR_LIT>"][name]=b<EOL><DEDENT>for name,bone in out["<STR_LIT>"].items():<EOL><INDENT>if name == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>bone.setParent(out["<STR_LIT>"][bone.bonedata["<STR_LIT>"]])<EOL><DEDENT>out["<STR_LIT>"]={}<EOL>for name,regdata in data.get("<STR_LIT>",{}).items():<EOL><INDENT>r = model.Region(self,name,regdata)<EOL>r.material = out["<STR_LIT>"][regdata.get("<STR_LIT>",out["<STR_LIT>"])]<EOL>r.bone = out["<STR_LIT>"][regdata.get("<STR_LIT>","<STR_LIT>")]<EOL>out["<STR_LIT>"][regdata.get("<STR_LIT>","<STR_LIT>")].addRegion(r)<EOL>out["<STR_LIT>"][name]=r<EOL><DEDENT>out["<STR_LIT>"]={}<EOL>out["<STR_LIT>"]["<STR_LIT>"]=model.Animation(self,"<STR_LIT>",{"<STR_LIT:type>":"<STR_LIT>","<STR_LIT>":{}})<EOL>for name,anidata in data.get("<STR_LIT>",{}).items():<EOL><INDENT>a = model.Animation(self,name,anidata)<EOL>a.setBones(out["<STR_LIT>"])<EOL>out["<STR_LIT>"][name]=a<EOL><DEDENT>out["<STR_LIT>"]=out["<STR_LIT>"][data.get("<STR_LIT>",out["<STR_LIT>"]["<STR_LIT>"])]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"%(data.get("<STR_LIT:version>",<NUM_LIT:1>),name))<EOL><DEDENT>self.modelcache[name]=out<EOL>return out<EOL>

Loads the model data of the given name.

The model file must always be a .json file.


pass<EOL>

This method is called if it is time to render the menu.

Override this method in subclasses to customize behavior and actually draw stuff.


self.worlds.append(world)<EOL>

Adds the given world to the internal list.

Worlds that are registered via this method will get all events that are given to this menu passed through.

This mechanic is mainly used to implement actor controllers.


pass <EOL>

This fake event handler will be called every time this menu is entered via the :py:meth:`PengWindow.changeMenu()` method.

This handler will not be called if this menu is already active.


pass<EOL>

This fake event handler will be called every time this menu is exited via the :py:meth:`PengWindow.changeMenu()` method.

This handler will not be called if this menu is the same as the new menu.


<EOL>if not isinstance(layer,Layer):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if z==-<NUM_LIT:1>:<EOL><INDENT>self.layers.append(layer)<EOL><DEDENT>else:<EOL><INDENT>self.layers.insert(z,layer)<EOL><DEDENT>

Adds a new layer to the stack, optionally at the specified z-value.

``layer`` must be an instance of Layer or subclasses.

``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending.


<EOL>for layer in self.layers:<EOL><INDENT>if layer.enabled:<EOL><INDENT>layer._draw()<EOL><DEDENT><DEDENT>

Draws the layers in the appropriate order.

Layers that have their ``enabled`` attribute set to ``False`` are skipped.


for layer in self.layers:<EOL><INDENT>layer.on_menu_enter(old)<EOL><DEDENT>

Same as :py:meth:`BasicMenu.on_enter()`\ , but also calls :py:meth:`Layer.on_menu_enter()` on every layer.


for layer in self.layers:<EOL><INDENT>layer.on_menu_exit(new)<EOL><DEDENT>

Same as :py:meth:`BasicMenu.on_exit()`\ , but also calls :py:meth:`Layer.on_menu_exit()` on every layer.


if cls is None:<EOL><INDENT>from . import window<EOL>cls = window.PengWindow<EOL><DEDENT>if self.window is not None:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT>":cls})<EOL>if caption_t is not None:<EOL><INDENT>kwargs["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT>self.window = cls(self,*args,**kwargs)<EOL>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT>":self.window})<EOL>if self.cfg["<STR_LIT>"] and self.resourceMgr is None:<EOL><INDENT>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT>":self.cfg["<STR_LIT>"]})<EOL>self.resourceMgr = resource.ResourceManager(self,self.cfg["<STR_LIT>"])<EOL>self.rsrcMgr = self.resourceMgr<EOL>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT>":self.resourceMgr})<EOL>if self.cfg["<STR_LIT>"] and self.i18n is None:<EOL><INDENT>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self})<EOL>self.i18n = i18n.TranslationManager(self)<EOL>self._t = self.i18n.t<EOL>self._tl = self.i18n.tl<EOL>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT>":self.i18n})<EOL><DEDENT><DEDENT>if caption_t is not None:<EOL><INDENT>self.window.set_caption(self.t(caption_t))<EOL>def f():<EOL><INDENT>self.window.set_caption(self.t(caption_t))<EOL><DEDENT>self.i18n.addAction("<STR_LIT>",f)<EOL><DEDENT>return self.window<EOL>

createWindow(cls=window.PengWindow, *args, **kwargs)

Creates a new window using the supplied ``cls``\ .

If ``cls`` is not given, :py:class:`peng3d.window.PengWindow()` will be used.

Any other positional or keyword arguments are passed to the class constructor.

Note that this method currently does not support using multiple windows.

.. todo::

   Implement having multiple windows.


self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT>":self.window,"<STR_LIT>":evloop})<EOL>self.window.run(evloop)<EOL>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self})<EOL>

Runs the application main loop.

This method is blocking and needs to be called from the main thread to avoid OpenGL bugs that can occur.

``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.


args = list(args)<EOL>self.sendEvent("<STR_LIT>"%event_type,{"<STR_LIT>":self,"<STR_LIT:args>":args,"<STR_LIT>":window,"<STR_LIT:src>":self,"<STR_LIT>":event_type})<EOL>self.sendEvent("<STR_LIT>",{"<STR_LIT>":self,"<STR_LIT:args>":args,"<STR_LIT>":window,"<STR_LIT:src>":self,"<STR_LIT>":event_type})<EOL>if event_type not in ["<STR_LIT>","<STR_LIT>"] and self.cfg["<STR_LIT>"]:<EOL><INDENT>print("<STR_LIT>"%(event_type,args))<EOL><DEDENT>if event_type in self.pygletEventHandlers:<EOL><INDENT>for whandler in self.pygletEventHandlers[event_type]:<EOL><INDENT>handler = whandler()<EOL>if handler is None:<EOL><INDENT>del self.pygletEventHandlers[event_type][self.pygletEventHandlers[event_type].index(whandler)]<EOL><DEDENT>handler(*args)<EOL><DEDENT><DEDENT>

Handles a pyglet event.

This method is called by :py:meth:`PengWindow.dispatch_event()` and handles all events.

See :py:meth:`registerEventHandler()` for how to listen to these events.

This method should be used to send pyglet events.
For new code, it is recommended to use :py:meth:`sendEvent()` instead.
For "tunneling" pyglet events, use event names of the format ``pyglet:<event>``
and for the data use ``{"args":<args as list>,"window":<window object or none>,"src":<event source>,"event_type":<event type>}``

Note that you should send pyglet events only via this method, the above event will be sent automatically.

Do not use this method to send custom events, use :py:meth:`sendEvent` instead.


if self.cfg["<STR_LIT>"]:<EOL><INDENT>print("<STR_LIT>"%(event_type,handler))<EOL><DEDENT>if event_type not in self.pygletEventHandlers:<EOL><INDENT>self.pygletEventHandlers[event_type]=[]<EOL><DEDENT>if inspect.ismethod(handler):<EOL><INDENT>handler = weakref.WeakMethod(handler)<EOL><DEDENT>else:<EOL><INDENT>handler = weakref.ref(handler)<EOL><DEDENT>self.pygletEventHandlers[event_type].append(handler)<EOL>

Registers an event handler.

The specified callable handler will be called every time an event with the same ``event_type`` is encountered.

All event arguments are passed as positional arguments.

This method should be used to listen for pyglet events.
For new code, it is recommended to use :py:meth:`addEventListener()` instead.

See :py:meth:`handleEvent()` for information about tunneled pyglet events.

For custom events, use :py:meth:`addEventListener()` instead.


if self.cfg["<STR_LIT>"]!="<STR_LIT>" and event not in self.event_list:<EOL><INDENT>self.event_list.add(event)<EOL><DEDENT>if event not in self.eventHandlers:<EOL><INDENT>if event not in self.events_ignored or self.events_ignored[event]<=self.cfg["<STR_LIT>"]: <EOL><INDENT>self.events_ignored[event] = self.events_ignored.get(event,<NUM_LIT:0>)+<NUM_LIT:1><EOL><DEDENT>return<EOL><DEDENT>for handler in self.eventHandlers[event]:<EOL><INDENT>f = handler[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>f(event,data)<EOL><DEDENT>except Exception:<EOL><INDENT>if not handler[<NUM_LIT:1>]:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>if self.cfg["<STR_LIT>"]:<EOL><INDENT>self.delEventListener(event,f)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Sends an event with attached data.

``event`` should be a string of format ``<namespace>:<category1>.<subcategory2>.<name>``\ .
There may be an arbitrary amount of subcategories. Also note that this
format is not strictly enforced, but rather recommended by convention.

``data`` may be any Python Object, but it usually is a dictionary containing relevant parameters.
For example, most built-in events use a dictionary containing at least the ``peng`` key set to an instance of this class.

If there are no handlers for the event, a corresponding message will be printed to the log file.
To prevent spam, the maximum amount of ignored messages can be configured via :confval:`events.maxignore` and defaults to 3.

If the config value :confval:`debug.events.dumpfile` is a file path, the event type will be added to an internal list and be saved to the given file during program exit.


if not isinstance(event,str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if event not in self.eventHandlers:<EOL><INDENT>self.eventHandlers[event]=[]<EOL><DEDENT>self.eventHandlers[event].append([func,raiseErrors])<EOL>

Adds a handler to the given event.

A event may have an arbitrary amount of handlers, though assigning too
many handlers may slow down event processing.

For the format of ``event``\ , see :py:meth:`sendEvent()`\ .

``func`` is the handler which will be executed with two arguments, ``event_type`` and ``data``\ , as supplied to :py:meth:`sendEvent()`\ .

If ``raiseErrors`` is True, exceptions caused by the handler will be re-raised.
Defaults to ``False``\ .


if event not in self.eventHandlers:<EOL><INDENT>raise NameError("<STR_LIT>"%event)<EOL><DEDENT>if [func,True] in self.eventHandlers[event]:<EOL><INDENT>del self.eventHandlers[event][self.eventHandlers[event].index(func)]<EOL><DEDENT>elif [func,False] in self.eventHandler[event]:<EOL><INDENT>del self.eventHandlers[event][self.eventHandlers[event].index(func)]<EOL><DEDENT>else:<EOL><INDENT>raise NameError("<STR_LIT>"%event)<EOL><DEDENT>if self.eventHandlers[event] == []:<EOL><INDENT>del self.eventHandlers[event]<EOL><DEDENT>

Removes the given handler from the given event.

If the event does not exist, a :py:exc:`NameError` is thrown.

If the handler has not been registered previously, also a :py:exc:`NameError` will be thrown.


return pos[<NUM_LIT:0>]<=mpos[<NUM_LIT:0>]<=pos[<NUM_LIT:0>]+size[<NUM_LIT:0>] and pos[<NUM_LIT:1>]<=mpos[<NUM_LIT:1>]<=pos[<NUM_LIT:1>]+size[<NUM_LIT:1>]<EOL>

AABB Collision checker that can be used for most axis-aligned collisions.

Intended for use in widgets to check if the mouse is within the bounds of a particular widget.


<EOL>if points<=<NUM_LIT:8>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif points<=<NUM_LIT:10>:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>elif points<=<NUM_LIT:12>:<EOL><INDENT>return <NUM_LIT:3><EOL><DEDENT>elif points<=<NUM_LIT>:<EOL><INDENT>return <NUM_LIT:4><EOL><DEDENT>elif points<=<NUM_LIT>:<EOL><INDENT>return <NUM_LIT:5><EOL><DEDENT>elif points<=<NUM_LIT>:<EOL><INDENT>return <NUM_LIT:6><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:7><EOL><DEDENT>

Approximate font size converter, converts from Points to HTML ``<font>`` tag font sizes.

Note that this method is very inaccurate, since there are only seven possible output values that represent at least 25 input values.
When in doubt, this function always rounds down, e.g. every input value less than eight is converted to HTML size 1.


peng.addEventListener("<STR_LIT>"%event,(lambda data:func(*data["<STR_LIT:args>"])),raiseErrors)<EOL>

Registers the given pyglet-style event handler for the given pyglet event.

This function allows pyglet-style event handlers to receive events bridged
through the peng3d event system. Internally, this function creates a lambda
function that decodes the arguments and then calls the pyglet-style event handler.

The ``raiseErrors`` flag is passed through to the peng3d event system and will
cause any errors raised by this handler to be ignored.

.. seealso::
   See :py:meth:`~peng3d.peng.Peng.addEventListener()` for more information.


if not hasattr(self,"<STR_LIT>"):<EOL><INDENT>self.actions = {}<EOL><DEDENT>if action not in self.actions:<EOL><INDENT>self.actions[action] = []<EOL><DEDENT>self.actions[action].append((func,args,kwargs))<EOL>

Adds a callback to the specified action.

All other positional and keyword arguments will be stored and passed to the function upon activation.


if not hasattr(self,"<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>for f,args,kwargs in self.actions.get(action,[]):<EOL><INDENT>f(*args,**kwargs)<EOL><DEDENT>

Helper method that calls all callbacks registered for the given action.


if self.reuse_ids:<EOL><INDENT>i = self.start_id<EOL>while True:<EOL><INDENT>if i not in self._data["<STR_LIT>"]:<EOL><INDENT>assert i<=self.max_id<EOL>return i <EOL><DEDENT>i+=<NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>with self.id_lock:<EOL><INDENT>i = self._data["<STR_LIT>"]<EOL>assert i<=self.max_id<EOL>self._data["<STR_LIT>"]+=<NUM_LIT:1><EOL><DEDENT>return i<EOL><DEDENT>

Generates a new ID.

If ``reuse_ids`` was false, the new ID will be read from an internal counter
which is also automatically increased. This means that the newly generated ID is already reserved.

If ``reuse_ids`` was true, this method starts counting up from ``start_id`` until it finds an
ID that is not currently known. Note that the ID is not reserved, this means that
calling this method simultaneously from multiple threads may cause the same ID to be returned twice.

Additionally, if the ID is greater or equal to ``max_id``\ , an :py:exc:`AssertionError` is raised.


with self.registry_lock:<EOL><INDENT>if force_id is None:<EOL><INDENT>new_id = self.genNewID()<EOL><DEDENT>else:<EOL><INDENT>new_id = force_id<EOL><DEDENT>self._data["<STR_LIT>"][new_id]=name<EOL>return new_id<EOL><DEDENT>

Registers a name to the registry.

``name`` is the name of the object and must be a string.

``force_id`` can be optionally set to override the automatic ID generation
and force a specific ID.

Note that using ``force_id`` is discouraged, since it may cause problems when ``reuse_ids`` is false.


if isinstance(in_id,int):<EOL><INDENT>assert in_id in self._data["<STR_LIT>"]<EOL>return in_id<EOL><DEDENT>elif isinstance(in_id,str):<EOL><INDENT>assert in_id in self._data["<STR_LIT>"].inv<EOL>return self._data["<STR_LIT>"].inv[in_id]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>

Takes in an object and normalizes it to its ID/integer representation.

Currently, only integers and strings may be passed in, else a :py:exc:`TypeError`
will be thrown.


if isinstance(in_name,str):<EOL><INDENT>assert in_name in self._data["<STR_LIT>"].inv<EOL>return in_name<EOL><DEDENT>elif isinstance(in_name,int):<EOL><INDENT>assert in_name in self._data["<STR_LIT>"]<EOL>return self._data["<STR_LIT>"][in_name]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>

Takes in an object and normalizes it to its name/string.

Currently, only integers and strings may be passed in, else a :py:exc:`TypeError`
will be thrown.


d = self._data<EOL>d["<STR_LIT>"]=dict(d["<STR_LIT>"])<EOL>return d<EOL>

Read-only property to access the internal data.

This is a dictionary containing all information necessary to re-create the registry
via the ``data`` argument.

The returned object is fully JSON/YAML/MessagePack serializable, as it only contains
basic python data types.


pass<EOL>

Called when this layer needs to be drawn.

Override this method in subclasses to redefine behavior.


pass<EOL>

Called before the :py:meth:`draw()` method is called.

This method is used in the :py:class:`Layer2D()` and :py:class:`Layer3D()` subclasses for setting OpenGL state.

Override this method in subclasses to redefine behavior.


pass<EOL>

Called after the :py:meth:`draw()` method is called.

This method can be used to reset OpenGL state to avoid conflicts with other code.

Override this method in subclasses to redefine behavior.