cocos2d-x3.x Sprite frame cache and Texture cache

Source: Internet
Author: User
Tags addchild


Sprite Frame Cache Introduction

Spriteframecache mainly serves the texture images of multiple pieces of broken images. This texture in a large map contains a number of small images, directly through the Texturecache reference will be a lot of inconvenience, and thus derived from the processing of the wizard frame, that is, the captured texture information stored in a sprite frame, the wizard by toggling different frame to show the different patterns.


Spriteframecache

The interior of the Spriteframecache encapsulates a map _spriteframes object. Key is the name of the frame. Spriteframecache is generally used to process plist files (this file specifies the location and size of each individual sprite in this "big Picture"), which corresponds to a large image containing multiple sprites, plist files can be made using Texturepacker.

Spriteframecache Common interface and Texturecache similar, no longer repeat, the only thing to note is to add the sprite frame of the companion file a plist file and a large texture map. Here's a list of common methods for Spriteframecache:


Gets the Spriteframecache object for the singleton. The Sharedspriteframecache method has been deprecated in 3.0:

spriteframecache* cache = Spriteframecache::getinstance ();

Destroying Spriteframecache objects:

Spriteframecache::d estroyinstance ();

Use Spriteframecache to get the specified sprite frame and create the Sprite object:

Spriteframecache *framecache = Spriteframecache::getinstance ();
Framecache->addspriteframeswithfile ("Boy.plist", "boy.png");//boy.png collection of boy1.png,boy2.png these little pictures
auto Frame _SP = Sprite::createwithspriteframename ("Boy1.png");//boy1.png This image is found in the Spriteframecache cache.
This->addchild (frame_sp,2);

Spriteframecache vs. Texturecache

Spriteframecache Wizard Frame Cache. As the name implies, this cache is the sprite frame spriteframe, which mainly serve the multiple pieces of the image of the merged texture image. This texture in a large map contains a number of small images, directly through the Texturecache reference will be a lot of inconvenience, and thus derived from the processing of the wizard frame, that is, the captured texture information stored in a sprite frame, the wizard by toggling different frame to show the different patterns.
Like the Texturecache function, the spriteframe is cached and taken directly at the next use. However, unlike Texturecache, if the image you are looking for does not exist in the memory pool, it will not be able to find it and will not load the picture locally.

Texturecache is the most efficient texture cache at the bottom, and caches the texture resources loaded into memory, which is the picture resource. Spriteframecache Sprite Frame cache, cached when Sprite frames. The Spriteframecache is based on the encapsulation on the Texturecache. The cache is a sprite frame, which is a rectangular block of the specified area of the texture. Each sprite frame is in the same texture and displays different patterns by toggling different frame frames.


Texture Caching

In the game you need to load a lot of texture pictures, these operations are very memory and resources.

When the game has an interface with a lot of pictures, the first point in the interface when the speed is very slow (because to load a lot of pictures), we can use Texturecache to load the texture ahead of time, such as loading the end, to enter the interface and then use the image speed will be very fast.

Texture2d: Texture, which is a map object that the picture loads into memory for CPU and GPU operations.
Texturecache (texture cache) for loading and managing textures. Once the texture is loaded, the next time it is used, it can be used to return the previously loaded textures, reducing the GPU and CPU memory footprint.
Common Methods

When you create a genie, you generally use Sprite::create (pszFileName). If you look at how Sprite::create (pszfilename) is implemented, you will see that it adds this image to the texture cache:

sprite* sprite::create (const std::string& filename)
{
    Sprite *sprite = new Sprite ();
    if (Sprite && sprite->initwithfile (filename))
    {
        sprite->autorelease ();
        return sprite;
    }
    _safe_delete (sprite);
    return nullptr;
}

BOOL Sprite::initwithfile (const std::string& filename)
{
    ASSERT (filename.size () >0, "Invalid FileName for Sprite ");

    Texture2d *texture = director::getinstance ()->gettexturecache ()->addimage (filename);
    if (texture)
    {
        rect rect = Rect::zero;
        Rect.size = Texture->getcontentsize ();
        return initwithtexture (texture, rect);
    }

    Don ' t release here.
    When load texture failed, it's better to get a "transparent" sprite and then a crashed program
    //This->release (); C23/>return false;
}

The above code shows the loading texture in the control. Once the texture is loaded, the texture reference that was loaded before will be returned at the next moment, and the memory added in the moment of loading is reduced.


Get Texturecache

In version 3.0, Texturecache is no longer used as a singleton mode. As a member variable for a director, it is obtained in the following ways:

Director::getinstance ()->gettexturecache ();

Get Textures

If the file name was not previously loaded, it creates a new Texture2d object, which returns it. It will use the file name as key otherwise it will return a reference to the previously loaded image.
Texturecache masks Many details of loading textures;
The AddImage function returns a reference to the texture texture2d, and if the texture does not exist, a new one is created, otherwise it is returned:

Texture2d *texture = director::getinstance ()->gettexturecache ()->addimage (filename);

You can also use the Gettextureforkey method to get the texture cache for this key, and if the key corresponding to the texture does not exist, then return null:

Texture2d *texture = director::getinstance ()->gettexturecache ()->gettextureforkey (textureKeyName);

Loading Textures asynchronously

The Texturecache class also supports the ability to load resources asynchronously, using the Addimageasync method. You can add a callback method to the Addimageasync method in a way that can be notified when the texture is loaded asynchronously.

You can choose the asynchronous load mode so you can add a progress bar to the loading scene. The key code is as follows:

Texturecachetest::texturecachetest (): _numberofsprites ($), _numberofloadedsprites (0) {Auto size = Director::getins

    Tance ()->getwinsize ();
    _labelloading = Label::createwithttf ("Loading ...", "Fonts/arial.ttf", 15);

    _labelpercent = Label::createwithttf ("%0", "Fonts/arial.ttf", 15);
    _labelloading->setposition (Point (SIZE.WIDTH/2, SIZE.HEIGHT/2-20));

    _labelpercent->setposition (Point (SIZE.WIDTH/2, SIZE.HEIGHT/2 + 20));
    This->addchild (_labelloading);

    This->addchild (_labelpercent); Load Textrues director::getinstance ()->gettexturecache ()->addimageasync ("Images/helloworld.png", _
    Callback_1 (Texturecachetest::loadingcallback, this)); Director::getinstance ()->gettexturecache ()->addimageasync ("Images/grossini.png", _CALLBACK_1 (
    Texturecachetest::loadingcallback, this)); Director::getinstance ()->gettexturecache ()->addimageasync ("Images/grossini_dance_01.png", _CALLBACK_1 ( Texturecachetest::loadingcallback,This));

....

}
    void Texturecachetest::loadingcallback (Cocos2d::texture2d *texture) {++_numberofloadedsprites;
    Char tmp[10];
    sprintf (tmp, "%%%d", (int) (((float) _numberofloadedsprites/_numberofsprites) * 100));

    _labelpercent->setstring (TMP);
        if (_numberofloadedsprites = = _numberofsprites) {this->removechild (_labelloading, true);
        This->removechild (_labelpercent, true);
    Addsprite (); }
}

clean up the cache

Removeunusedtextures releases all current textures that have a reference count of 1, which is not currently in use. For example, when a new scene is created, it is convenient to use this method to release unused textures:

Director::getinstance ()->gettexturecache ()->removeunusedtextures ();

Textures still exist between memory when no other object (such as a sprite) holds a reference to the texture. Based on this, we can immediately remove from the cache, so that when the texture is not needed, it will be released from memory immediately. As shown in the following code:

Director::getinstance ()->gettexturecache ()->removetextureforkey ("Images/grossinis_sister2.png");

The Removealltextures () method can be called when "Memory Warning" is received. In the short term: it will also release some resources to prevent your application from being killed; Medium: It will allocate more resources; In the long run: it will be the same:

Director::getinstance ()->gettexturecache ()->removealltextures ();



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.