U
    Pe>                     @   s(  d Z dZddlZddlmZmZmZmZ ddlm	Z	 ddl
mZ ddlmZmZmZ ddlZdaG dd	 d	e	Zed
kr$ddlZddlmZ ejdd Zeedk red ed ddiZed Zedkrded< nVedreeddd ed< n0edd dkr@ede ed nq@edd Zqed Z z:ded krte!e"eed ddZ#need Z#W n( e$k
r   ed ed Y nX dd edd D Z%ej&e e%e#feZ'e'sed ed e'\Z(Z)ede( ed ee)ee)dkrd!nd"f  dS )#a  
Atlas
=====

.. versionadded:: 1.1.0

Atlas manages texture atlases: packing multiple textures into
one. With it, you reduce the number of images loaded and speedup the
application loading. This module contains both the Atlas class and command line
processing for creating an atlas from a set of individual PNG files. The
command line section requires the Pillow library, or the defunct Python Imaging
Library (PIL), to be installed.

An Atlas is composed of 2 or more files:
    - a json file (.atlas) that contains the image file names and texture
      locations of the atlas.
    - one or multiple image files containing textures referenced by the .atlas
      file.

Definition of .atlas files
--------------------------

A file with ``<basename>.atlas`` is a json file formatted like this::

    {
        "<basename>-<index>.png": {
            "id1": [ <x>, <y>, <width>, <height> ],
            "id2": [ <x>, <y>, <width>, <height> ],
            # ...
        },
        # ...
    }

Example from the Kivy ``data/images/defaulttheme.atlas``::

    {
        "defaulttheme-0.png": {
            "progressbar_background": [431, 224, 59, 24],
            "image-missing": [253, 344, 48, 48],
            "filechooser_selected": [1, 207, 118, 118],
            "bubble_btn": [83, 174, 32, 32],
            # ... and more ...
        }
    }

In this example, "defaulttheme-0.png" is a large image, with the pixels in the
rectangle from (431, 224) to (431 + 59, 224 + 24) usable as
``atlas://data/images/defaulttheme/progressbar_background`` in
any image parameter.

How to create an Atlas
----------------------

.. warning::

    The atlas creation requires the Pillow library (or the defunct Imaging/PIL
    library). This requirement will be removed in the future when the Kivy core
    Image is able to support loading, blitting, and saving operations.

You can directly use this module to create atlas files with this command::

    $ python -m kivy.atlas <basename> <size> <list of images...>


Let's say you have a list of images that you want to put into an Atlas. The
directory is named ``images`` with lots of 64x64 png files inside::

    $ ls
    images
    $ cd images
    $ ls
    bubble.png bubble-red.png button.png button-down.png

You can combine all the png's into one and generate the atlas file with::

    $ python -m kivy.atlas myatlas 256x256 *.png
    Atlas created at myatlas.atlas
    1 image has been created
    $ ls
    bubble.png bubble-red.png button.png button-down.png myatlas.atlas
    myatlas-0.png

As you can see, we get 2 new files: ``myatlas.atlas`` and ``myatlas-0.png``.
``myatlas-0.png`` is a new 256x256 .png composed of all your images. If the
size you specify is not large enough to fit all of the source images, more
atlas images will be created as required e.g. ``myatlas-1.png``,
``myatlas-2.png`` etc.

.. note::

    When using this script, the ids referenced in the atlas are the base names
    of the images without the extension. So, if you are going to name a file
    ``../images/button.png``, the id for this image will be ``button``.

    If you need path information included, you should include ``use_path`` as
    follows::

        $ python -m kivy.atlas -- --use_path myatlas 256 *.png

    In which case the id for ``../images/button.png`` will be ``images_button``


How to use an Atlas
-------------------

Usually, you would specify the images by supplying the path::

    a = Button(background_normal='images/button.png',
               background_down='images/button_down.png')

In our previous example, we have created the atlas containing both images and
put them in ``images/myatlas.atlas``. You can use url notation to reference
them::

    a = Button(background_normal='atlas://images/myatlas/button',
               background_down='atlas://images/myatlas/button_down')

In other words, the path to the images is replaced by::

    atlas://path/to/myatlas/id
    # will search for the ``path/to/myatlas.atlas`` and get the image ``id``

.. note::

    In the atlas url, there is no need to add the ``.atlas`` extension. It will
    be automatically append to the filename.

Manual usage of the Atlas
-------------------------

::

    >>> from kivy.atlas import Atlas
    >>> atlas = Atlas('path/to/myatlas.atlas')
    >>> print(atlas.textures.keys())
    ['bubble', 'bubble-red', 'button', 'button-down']
    >>> print(atlas['button'])
    <kivy.graphics.texture.TextureRegion object at 0x2404d10>
)Atlas    N)basenamedirnamejoinsplitext)EventDispatcher)Logger)AliasPropertyDictPropertyListPropertyc                       s`   e Zd ZdZeg Zei Zdd Ze	edZ
 fddZdd Zd	d
 ZedddZ  ZS )r   zIManage texture atlas. See module documentation for more information.
    c                 C   s   | j S N)	_filename)self r   ./tmp/pip-unpacked-wheel-xzebddm3/kivy/atlas.py_get_filename   s    zAtlas._get_filenameNc                    s    || _ tt|   |   d S r   )r   superr   __init___load)r   filename	__class__r   r   r      s    zAtlas.__init__c                 C   s
   | j | S r   )textures)r   keyr   r   r   __getitem__   s    zAtlas.__getitem__c              	   C   s   t d krddlma  | j}|ds(t|dtj}t	
d|  t|d}t|}W 5 Q R X t	
dt|  t|}i }| D ]f\}}t||}t	
d|  t |}|j}	| j|	 | D ]"\}
}|\}}}}|	j| ||
< qq|| _d S )Nr   Imagez.atlas/zAtlas: Load <%s>rzAtlas: Need to load %d images)	CoreImageZkivy.core.imager   r   endswithAssertionErrorreplaceossepr   debugopenjsonloadlenr   itemsr   Ztextureoriginal_texturesappendZ
get_regionr   )r   r   fdmetadr   ZsubfilenameidsciZatlas_textureZmeta_idZmeta_coordsxywhr   r   r   r      s*    
zAtlas._load   Fc                    s  zddl m  W n  tk
r0   td  Y nX t|ttfrTttt	|\nt	| t }|D ]6}t
|d} 
|}|  |  |||f qjt|dd dd}dddfg}	d	}
g }|D ]}|d	 }|j\}}||7 }||7 }|ks|kr*td
|d ||f   dS d}|st|	D ]\}}|d |kr:|d |kr:|	|= |d |kr|	|d |d	 | |d |d | |f |d |kr|	|d |d	 |d | |d |d | f t|	dd d}	|||d |d	 | |d | || || |d f d} q2q:|s.|	|
ddf |
d	7 }
q.qtd  fddtdt	|
D }|D ]}|d |d  }}||d	  }||d |d |d f |d j\}}|d	kr||d dd|d	f||d	 f ||d d|d	 ||f||| f ||d ddd	|f|d	 |f ||d |d	 d||f|| |f qt|D ]\}}|d| |f  qi }|D ]}dt| |d	 f }||kri  }||< n|| }|r&t|d d }|d}|dddd}ntt|d d }|dd \}}}}|| | ||f||< qd|  }t
|d}t|| W 5 Q R X ||fS )aC  This method can be used to create an atlas manually from a set of
        images.

        :Parameters:
            `outname`: str
                Basename to use for ``.atlas`` creation and ``-<idx>.png``
                associated images.
            `filenames`: list
                List of filenames to put in the atlas.
            `size`: int or list (width, height)
                Size of the atlas image. If the size is not large enough to
                fit all of the source images, more atlas images will created
                as required.
            `padding`: int, defaults to 2
                Padding to put around each image.

                Be careful. If you're using a padding < 2, you might have
                issues with the borders of the images. Because of the OpenGL
                linearization, it might use the pixels of the adjacent image.

                If you're using a padding >= 2, we'll automatically generate a
                "border" of 1px around your image. If you look at
                the result, don't be scared if the image inside is not
                exactly the same as yours :).

            `use_path`: bool, defaults to False
                If True, the relative path of the source png
                file names will be included in the atlas ids rather
                that just in the file names. Leading dots and slashes will be
                excluded and all other slashes in the path will be replaced
                with underscores. For example, if `use_path` is False
                (the default) and the file name is
                ``../data/tiles/green_grass.png``, the id will be
                ``green_grass``. If `use_path` is True, it will be
                ``data_tiles_green_grass``.

            .. versionchanged:: 1.8.0
                Parameter use_path added
        r   r   zAtlas: Imaging/PIL are missingrbc                 S   s   | d j d | d j d  S )N   r   )size)imr   r   r   <lambda>%      zAtlas.create.<locals>.<lambda>T)r   reverser8   z9Atlas: image %s (%d by %d) is larger than the atlas size!NF      r6   c                 S   s   | d | d  S )Nr>   r?   r   )fbr   r   r   r;   S  r<   )r   z#Atlas: create an {0}x{1} rgba imagec                    s   g | ]}  d fqS )ZRGBA)new).0ir   Zsize_hZsize_wr   r   
<listcomp>e  s   z Atlas.create.<locals>.<listcomp>z	%s-%d.png   z./\r   _\z%s.atlasr4   )ZPILr   ImportErrorr   critical
isinstancetuplelistmapintr&   r(   closer,   sortedr9   error	enumerateinfoformatrangeZpasteZcropsaver   r   lstripr"   r'   dump)outname	filenamesr9   paddinguse_pathZimsffpr:   Z	freeboxesZnumoutimagesZ	fullboxesZ	imageinfoZimwZimhZinsertedidxr@   Z	outimagesr2   r3   outr4   r5   Zoutimager.   fnr/   uidZoutfnr-   r   rD   r   create   s    ,





 
 
   
 
 

  


&*&.

zAtlas.create)r6   F)__name__
__module____qualname____doc__r   r+   r
   r   r   r	   r   r   r   r   staticmethodrd   __classcell__r   r   r   r   r      s   	
#r   __main__globr8   r>   zqUsage: python -m kivy.atlas [-- [--use-path] [--padding=2]] <outname> <size|512x256> <img1.png> [<img2.png>, ...]r]   Fz
--use-pathTz
--padding==r\   r6   z--zUnknown option {}r2   z5Error: size must be an integer or <integer>x<integer>c                 C   s   g | ]}t |D ]}|qqS r   rl   )rB   fnamesfnamer   r   r   rE     s     
  rE   zError while creating atlas!zAtlas created atz%d image%s been createdzs havez has)*rh   __all__r'   os.pathr   r   r   r   Z
kivy.eventr   Zkivy.loggerr   Zkivy.propertiesr	   r
   r   r#   r   r   re   sysrm   argvr)   printexitoptionsoption
startswithrO   splitrU   rZ   rM   rN   r9   
ValueErrorr[   rd   retrb   r.   r   r   r   r   <module>   s^     ~





