예제 #1
0
    def __init__(self):
        """Create a graphics batch."""
        # Mapping to find domain.
        # group -> (attributes, mode, indexed) -> domain
        self.group_map = {}

        # Mapping of group to list of children.
        self.group_children = {}

        # List of top-level groups
        self.top_groups = []

        self._draw_list = []
        self._draw_list_dirty = False

        # Each Batch encompasses one VAO
        self.vao = VertexArray()

        if _debug_graphics_batch:
            print("Batch created. VAO ID: {0}".format(self.vao.id))
예제 #2
0
class Batch:
    """Manage a collection of vertex lists for batched rendering.

    Vertex lists are added to a :py:class:`~pyglet.graphics.Batch` using the `add` and `add_indexed`
    methods.  An optional group can be specified along with the vertex list,
    which gives the OpenGL state required for its rendering.  Vertex lists
    with shared mode and group are allocated into adjacent areas of memory and
    sent to the graphics card in a single operation.

    Call `VertexList.delete` to remove a vertex list from the batch.
    """
    def __init__(self):
        """Create a graphics batch."""
        # Mapping to find domain.
        # group -> (attributes, mode, indexed) -> domain
        self.group_map = {}

        # Mapping of group to list of children.
        self.group_children = {}

        # List of top-level groups
        self.top_groups = []

        self._draw_list = []
        self._draw_list_dirty = False

        # Each Batch encompasses one VAO
        self.vao = VertexArray()

        if _debug_graphics_batch:
            print("Batch created. VAO ID: {0}".format(self.vao.id))

    def invalidate(self):
        """Force the batch to update the draw list.

        This method can be used to force the batch to re-compute the draw list
        when the ordering of groups has changed.

        .. versionadded:: 1.2
        """
        self._draw_list_dirty = True

    def add(self, count, mode, group, *data):
        """Add a vertex list to the batch.

        :Parameters:
            `count` : int
                The number of vertices in the list.
            `mode` : int
                OpenGL drawing mode enumeration; for example, one of
                ``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc.
                See the module summary for additional information.
            `group` : `~pyglet.graphics.Group`
                Group of the vertex list, or ``None`` if no group is required.
            `data` : data items
                Attribute formats and initial data for the vertex list.  See
                the module summary for details.

        :rtype: :py:class:`~pyglet.graphics.vertexdomain.VertexList`
        """
        formats, initial_arrays = _parse_data(data)
        domain = self._get_domain(False, mode, group, formats)

        # Create vertex list and initialize
        vlist = domain.create(count)
        for i, array in initial_arrays:
            vlist.set_attribute_data(i, array)

        return vlist

    def add_indexed(self, count, mode, group, indices, *data):
        """Add an indexed vertex list to the batch.

        :Parameters:
            `count` : int
                The number of vertices in the list.
            `mode` : int
                OpenGL drawing mode enumeration; for example, one of
                ``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc.
                See the module summary for additional information.
            `group` : `~pyglet.graphics.Group`
                Group of the vertex list, or ``None`` if no group is required.
            `indices` : sequence
                Sequence of integers giving indices into the vertex list.
            `data` : data items
                Attribute formats and initial data for the vertex list.  See
                the module summary for details.

        :rtype: `IndexedVertexList`
        """
        formats, initial_arrays = _parse_data(data)
        domain = self._get_domain(True, mode, group, formats)

        # Create vertex list and initialize
        vlist = domain.create(count, len(indices))
        start = vlist.start
        vlist.set_index_data([i + start for i in indices])
        for i, array in initial_arrays:
            vlist.set_attribute_data(i, array)

        return vlist

    def migrate(self, vertex_list, mode, group, batch):
        """Migrate a vertex list to another batch and/or group.

        `vertex_list` and `mode` together identify the vertex list to migrate.
        `group` and `batch` are new owners of the vertex list after migration.  

        The results are undefined if `mode` is not correct or if `vertex_list`
        does not belong to this batch (they are not checked and will not
        necessarily throw an exception immediately).

        `batch` can remain unchanged if only a group change is desired.
        
        :Parameters:
            `vertex_list` : `~pyglet.graphics.vertexdomain.VertexList`
                A vertex list currently belonging to this batch.
            `mode` : int
                The current GL drawing mode of the vertex list.
            `group` : `~pyglet.graphics.Group`
                The new group to migrate to.
            `batch` : `~pyglet.graphics.Batch`
                The batch to migrate to (or the current batch).

        """
        formats = vertex_list.domain.__formats
        if isinstance(vertex_list, vertexdomain.IndexedVertexList):
            domain = batch._get_domain(True, mode, group, formats)
        else:
            domain = batch._get_domain(False, mode, group, formats)
        vertex_list.migrate(domain)

    def _get_domain(self, indexed, mode, group, formats):
        if group is None:
            group = get_default_group()

        # Batch group
        if group not in self.group_map:
            self._add_group(group)

        # If not a ShaderGroup, use the default ShaderProgram
        shader_program = getattr(group, 'program', get_default_shader())

        # Find domain given formats, indices and mode
        domain_map = self.group_map[group]
        key = (formats, mode, indexed, shader_program.id)
        try:
            domain = domain_map[key]
        except KeyError:
            # Create domain
            if indexed:
                domain = vertexdomain.create_indexed_domain(
                    shader_program.id, *formats)
            else:
                domain = vertexdomain.create_domain(shader_program.id,
                                                    *formats)
            domain.__formats = formats
            domain_map[key] = domain
            self._draw_list_dirty = True

        return domain

    def _add_group(self, group):
        self.group_map[group] = {}
        if group.parent is None:
            self.top_groups.append(group)
        else:
            if group.parent not in self.group_map:
                self._add_group(group.parent)
            if group.parent not in self.group_children:
                self.group_children[group.parent] = []
            self.group_children[group.parent].append(group)
        self._draw_list_dirty = True

    def _update_draw_list(self):
        """Visit group tree in preorder and create a list of bound methods
        to call.
        """
        def visit(group):
            draw_list = []

            # Draw domains using this group
            domain_map = self.group_map[group]
            for (formats, mode, indexed,
                 program_id), domain in list(domain_map.items()):
                # Remove unused domains from batch
                if domain.is_empty:
                    del domain_map[(formats, mode, indexed, program_id)]
                    continue
                draw_list.append((lambda d, m: lambda: d.draw(m))(domain,
                                                                  mode))

            # Sort and visit child groups of this group
            children = self.group_children.get(group)
            if children:
                children.sort()
                for child in list(children):
                    draw_list.extend(visit(child))

            if children or domain_map:
                return [group.set_state] + draw_list + [group.unset_state]
            else:
                # Remove unused group from batch
                del self.group_map[group]
                if group.parent:
                    self.group_children[group.parent].remove(group)
                try:
                    del self.group_children[group]
                except KeyError:
                    pass
                try:
                    self.top_groups.remove(group)
                except ValueError:
                    pass
                return []

        self._draw_list = []

        self.top_groups.sort()
        for group in list(self.top_groups):
            self._draw_list.extend(visit(group))

        self._draw_list_dirty = False

        if _debug_graphics_batch:
            self._dump_draw_list()

    def _dump_draw_list(self):
        def dump(group, indent=''):
            print(indent, 'Begin group', group)
            domain_map = self.group_map[group]
            for _, domain in domain_map.items():
                print(indent, '  ', domain)
                for start, size in zip(
                        *domain.allocator.get_allocated_regions()):
                    print(indent, '    ', 'Region %d size %d:' % (start, size))
                    for key, attribute in domain.attribute_names.items():
                        print(indent, '      ', end=' ')
                        try:
                            region = attribute.get_region(
                                attribute.buffer, start, size)
                            print(key, region.array[:])
                        except:
                            print(key, '(unmappable)')
            for child in self.group_children.get(group, ()):
                dump(child, indent + '  ')
            print(indent, 'End group', group)

        print('Draw list for %r:' % self)
        for group in self.top_groups:
            dump(group)

    def draw(self):
        """Draw the batch."""
        self.vao.bind()

        if self._draw_list_dirty:
            self._update_draw_list()

        for func in self._draw_list:
            func()

    def draw_subset(self, vertex_lists):
        """Draw only some vertex lists in the batch.

        The use of this method is highly discouraged, as it is quite
        inefficient.  Usually an application can be redesigned so that batches
        can always be drawn in their entirety, using `draw`.

        The given vertex lists must belong to this batch; behaviour is
        undefined if this condition is not met.

        :Parameters:
            `vertex_lists` : sequence of `VertexList` or `IndexedVertexList`
                Vertex lists to draw.

        """

        self.vao.bind()

        # Horrendously inefficient.
        def visit(group):
            group.set_state()

            # Draw domains using this group
            domain_map = self.group_map[group]
            for (_, mode, _, _), domain in domain_map.items():
                for alist in vertex_lists:
                    if alist.domain is domain:
                        alist.draw(mode)

            # Sort and visit child groups of this group
            children = self.group_children.get(group)
            if children:
                children.sort()
                for child in children:
                    visit(child)

            group.unset_state()

        self.top_groups.sort()
        for group in self.top_groups:
            visit(group)