CCSprite.cpp 53.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/CCSprite.h"
#include <algorithm>
#include <stddef.h> // offsetof
#include "base/ccTypes.h"
#include "2d/CCSpriteBatchNode.h"
#include "2d/CCAnimationCache.h"
#include "2d/CCSpriteFrame.h"
#include "2d/CCSpriteFrameCache.h"
#include "renderer/CCTextureCache.h"
#include "renderer/CCTexture2D.h"
#include "renderer/CCRenderer.h"
#include "base/CCDirector.h"
#include "base/ccUTF8.h"
#include "2d/CCCamera.h"
#include "platform/CCFileUtils.h"
#include "renderer/ccShaders.h"
#include "renderer/backend/ProgramState.h"
#include "renderer/backend/Device.h"

NS_CC_BEGIN

// MARK: create, init, dealloc
Sprite* Sprite::createWithTexture(Texture2D *texture)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && sprite->initWithTexture(texture))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && sprite->initWithTexture(texture, rect, rotated))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

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

Sprite* Sprite::create(const PolygonInfo& info)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if(sprite && sprite->initWithPolygon(info))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

Sprite* Sprite::create(const std::string& filename, const Rect& rect)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && sprite->initWithFile(filename, rect))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame)
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && spriteFrame && sprite->initWithSpriteFrame(spriteFrame))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

Sprite* Sprite::createWithSpriteFrameName(const std::string& spriteFrameName)
{
    SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);

#if COCOS2D_DEBUG > 0
    char msg[256] = {0};
    sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName.c_str());
    CCASSERT(frame != nullptr, msg);
#endif

    return createWithSpriteFrame(frame);
}

Sprite* Sprite::create()
{
    Sprite *sprite = new (std::nothrow) Sprite();
    if (sprite && sprite->init())
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

bool Sprite::init()
{
    initWithTexture(nullptr, Rect::ZERO);
    return true;
}

bool Sprite::initWithTexture(Texture2D *texture)
{
    CCASSERT(texture != nullptr, "Invalid texture for sprite");

    Rect rect = Rect::ZERO;
    if (texture)
        rect.size = texture->getContentSize();

    return initWithTexture(texture, rect, false);
}

bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect)
{
    return initWithTexture(texture, rect, false);
}

bool Sprite::initWithFile(const std::string& filename)
{
    if (filename.empty())
    {
        CCLOG("Call Sprite::initWithFile with blank resource filename.");
        return false;
    }

    _fileName = filename;

    Texture2D *texture = _director->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 then a crashed program
    // this->release();
    return false;
}

bool Sprite::initWithFile(const std::string &filename, const Rect& rect)
{
    CCASSERT(!filename.empty(), "Invalid filename");
    if (filename.empty())
        return false;

    _fileName = filename;

    Texture2D *texture = _director->getTextureCache()->addImage(filename);
    if (texture)
        return initWithTexture(texture, rect);

    // don't release here.
    // when load texture failed, it's better to get a "transparent" sprite then a crashed program
    // this->release();
    return false;
}

bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName)
{
    CCASSERT(!spriteFrameName.empty(), "Invalid spriteFrameName");
    if (spriteFrameName.empty())
        return false;

    _fileName = spriteFrameName;
    _fileType = 1;

    SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
    return initWithSpriteFrame(frame);
}

bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame)
{
    CCASSERT(spriteFrame != nullptr, "spriteFrame can't be nullptr!");
    if (spriteFrame == nullptr)
        return false;

    bool ret = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect(), spriteFrame->isRotated());
    setSpriteFrame(spriteFrame);

    return ret;
}

bool Sprite::initWithPolygon(const cocos2d::PolygonInfo &info)
{
    bool ret = false;

    Texture2D *texture = _director->getTextureCache()->addImage(info.getFilename());
    if(texture && initWithTexture(texture))
    {
        _polyInfo = info;
        _renderMode = RenderMode::POLYGON;
        Node::setContentSize(_polyInfo.getRect().size / _director->getContentScaleFactor());
        ret = true;
    }

    return ret;
}

// designated initializer
bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
{
    bool result = false;
    if (Node::init())
    {
        _batchNode = nullptr;

        _recursiveDirty = false;
        setDirty(false);

        _flippedX = _flippedY = false;

        // default transform anchor: center
        setAnchorPoint(Vec2::ANCHOR_MIDDLE);

        // zwoptex default values
        _offsetPosition.setZero();

        // clean the Quad
        memset(&_quad, 0, sizeof(_quad));

        // Atlas: Color
        _quad.bl.colors = Color4B::WHITE;
        _quad.br.colors = Color4B::WHITE;
        _quad.tl.colors = Color4B::WHITE;
        _quad.tr.colors = Color4B::WHITE;

        // update texture (calls updateBlendFunc)
        setTexture(texture);
        setTextureRect(rect, rotated, rect.size);

        // by default use "Self Render".
        // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
        setBatchNode(nullptr);
        result = true;
    }

    _recursiveDirty = true;
    setDirty(true);

    return result;
}

Sprite::Sprite()
{
#if CC_SPRITE_DEBUG_DRAW
    _debugDrawNode = DrawNode::create();
    addChild(_debugDrawNode);
#endif //CC_SPRITE_DEBUG_DRAW
}

Sprite::~Sprite()
{
    CC_SAFE_FREE(_trianglesVertex);
    CC_SAFE_FREE(_trianglesIndex);
    CC_SAFE_RELEASE(_spriteFrame);
    CC_SAFE_RELEASE(_texture);
}

/*
 * Texture methods
 */

/*
 * This array is the data of a white image with 2 by 2 dimension.
 * It's used for creating a default texture when sprite's texture is set to nullptr.
 * Supposing codes as follows:
 *
 *   auto sp = new (std::nothrow) Sprite();
 *   sp->init();  // Texture was set to nullptr, in order to make opacity and color to work correctly, we need to create a 2x2 white texture.
 *
 * The test is in "TestCpp/SpriteTest/Sprite without texture".
 */
static unsigned char cc_2x2_white_image[] = {
    // RGBA8888
    0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF
};

#define CC_2x2_WHITE_IMAGE_KEY  "/cc_2x2_white_image"

// MARK: texture
void Sprite::setTexture(const std::string &filename)
{
    Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
    setTexture(texture);
    _unflippedOffsetPositionFromCenter = Vec2::ZERO;
    Rect rect = Rect::ZERO;
    if (texture)
        rect.size = texture->getContentSize();

    setTextureRect(rect);
}

void Sprite::setVertexLayout()
{
    //set vertexLayout according to V3F_C4B_T2F structure
    //auto& vertexLayout = _trianglesCommand.getPipelineDescriptor().vertexLayout;
    auto vertexLayout = _programState->getVertexLayout();
    ///a_position
    vertexLayout->setAttribute(backend::ATTRIBUTE_NAME_POSITION,
                              _programState->getAttributeLocation(backend::Attribute::POSITION),
                              backend::VertexFormat::FLOAT3,
                              0,
                              false);
    ///a_texCoord
    vertexLayout->setAttribute(backend::ATTRIBUTE_NAME_TEXCOORD,
                              _programState->getAttributeLocation(backend::Attribute::TEXCOORD),
                              backend::VertexFormat::FLOAT2,
                              offsetof(V3F_C4B_T2F, texCoords),
                              false);
    
    ///a_color
    vertexLayout->setAttribute(backend::ATTRIBUTE_NAME_COLOR,
                              _programState->getAttributeLocation(backend::Attribute::COLOR),
                              backend::VertexFormat::UBYTE4,
                              offsetof(V3F_C4B_T2F, colors),
                              true);
    vertexLayout->setLayout(sizeof(V3F_C4B_T2F));
}

void Sprite::updateShaders(const char* vert, const char* frag)
{
    auto* program = backend::Device::getInstance()->newProgram(vert, frag);
    auto programState = new (std::nothrow) backend::ProgramState(program);
    setProgramState(programState);
    CC_SAFE_RELEASE(programState);
    CC_SAFE_RELEASE(program);
}

void Sprite::setProgramState(backend::ProgramType type)
{
    if(_programState != nullptr &&
       _programState->getProgram()->getProgramType() == type)
        return;
    
    auto* program = backend::Program::getBuiltinProgram(type);
    auto programState = new (std::nothrow) backend::ProgramState(program);
    setProgramState(programState);
    CC_SAFE_RELEASE_NULL(programState);
}

void Sprite::setProgramState(backend::ProgramState *programState)
{
    CCASSERT(programState, "argument should not be nullptr");
    auto& pipelineDescriptor = _trianglesCommand.getPipelineDescriptor();
    if (_programState != programState)
    {
        CC_SAFE_RELEASE(_programState);
        _programState = programState;
        CC_SAFE_RETAIN(programState);
    }
    pipelineDescriptor.programState = _programState;

    _mvpMatrixLocation = pipelineDescriptor.programState->getUniformLocation(backend::Uniform::MVP_MATRIX);
    _textureLocation = pipelineDescriptor.programState->getUniformLocation(backend::Uniform::TEXTURE);
    _alphaTextureLocation = pipelineDescriptor.programState->getUniformLocation(backend::Uniform::TEXTURE1);

    setVertexLayout();
    updateProgramStateTexture();
    setMVPMatrixUniform();
}

void Sprite::setTexture(Texture2D *texture)
{
    auto isETC1 = texture && texture->getAlphaTextureName();
    setProgramState((isETC1) ? backend::ProgramType::ETC1 : backend::ProgramType::POSITION_TEXTURE_COLOR);
    CCASSERT(! _batchNode || (texture &&  texture == _batchNode->getTexture()), "CCSprite: Batched sprites should use the same texture as the batchnode");
    // accept texture==nil as argument
    CCASSERT( !texture || dynamic_cast<Texture2D*>(texture), "setTexture expects a Texture2D. Invalid argument");
    
    if (texture == nullptr)
    {
        // Gets the texture by key firstly.
        texture = _director->getTextureCache()->getTextureForKey(CC_2x2_WHITE_IMAGE_KEY);

        // If texture wasn't in cache, create it from RAW data.
        if (texture == nullptr)
        {
            Image* image = new (std::nothrow) Image();
            bool CC_UNUSED isOK = image->initWithRawData(cc_2x2_white_image, sizeof(cc_2x2_white_image), 2, 2, 8);
            CCASSERT(isOK, "The 2x2 empty texture was created unsuccessfully.");

            texture = _director->getTextureCache()->addImage(image, CC_2x2_WHITE_IMAGE_KEY);
            CC_SAFE_RELEASE(image);
        }
    }

    if (_renderMode != RenderMode::QUAD_BATCHNODE)
    {
        if (_texture != texture)
        {
            CC_SAFE_RETAIN(texture);
            CC_SAFE_RELEASE(_texture);
            _texture = texture;
        }
        updateBlendFunc();
    }
    updateProgramStateTexture();
}

void Sprite::updateProgramStateTexture()
{
    if (_texture == nullptr || _texture->getBackendTexture() == nullptr)
        return;

    auto programState = _trianglesCommand.getPipelineDescriptor().programState;
    programState->setTexture(_textureLocation, 0, _texture->getBackendTexture());
    auto alphaTexture = _texture->getAlphaTexture();
    if(alphaTexture && alphaTexture->getBackendTexture())
    {
        programState->setTexture(_alphaTextureLocation, 1, alphaTexture->getBackendTexture());
    }
}

Texture2D* Sprite::getTexture() const
{
    return _texture;
}

void Sprite::setTextureRect(const Rect& rect)
{
    setTextureRect(rect, false, rect.size);
}

void Sprite::setTextureRect(const Rect& rect, bool rotated, const Size& untrimmedSize)
{
    _rectRotated = rotated;

    Node::setContentSize(untrimmedSize);
    _originalContentSize = untrimmedSize;

    setVertexRect(rect);
    updateStretchFactor();
    updatePoly();
}

void Sprite::updatePoly()
{
    // There are 3 cases:
    //
    // A) a non 9-sliced, non stretched
    //    contentsize doesn't not affect the stretching, since there is no stretching
    //    this was the original behavior, and we keep it for backwards compatibility reasons
    //    When non-stretching is enabled, we have to change the offset in order to "fill the empty" space at the
    //    left-top of the texture
    // B) non 9-sliced, stretched
    //    the texture is stretched to the content size
    // C) 9-sliced, stretched
    //    the sprite is 9-sliced and stretched.
    if (_renderMode == RenderMode::QUAD || _renderMode == RenderMode::QUAD_BATCHNODE)
    {
        Rect copyRect;
        if (_stretchEnabled)
            // case B)
            copyRect = Rect(0, 0, _rect.size.width * _stretchFactor.x, _rect.size.height * _stretchFactor.y);
        else
            // case A)
            // modify origin to put the sprite in the correct offset
            copyRect = Rect((_contentSize.width - _originalContentSize.width) / 2.0f,
                            (_contentSize.height - _originalContentSize.height) / 2.0f,
                            _rect.size.width,
                            _rect.size.height);

        setTextureCoords(_rect, &_quad);
        setVertexCoords(copyRect, &_quad);
        _polyInfo.setQuad(&_quad);

    }
    else if (_renderMode == RenderMode::SLICE9)
    {
        // case C)

        // How the texture is split
        //
        //  u,v: are the texture coordinates
        //  w,h: are the width and heights
        //
        //      w0    w1   w2
        // v2 +----+------+--+
        //    |    |      |  |
        //    |    |      |  |
        //    | 6  |   7  | 8|  h2
        //    |    |      |  |
        // v1 +----+------+--|
        //    |    |      |  |
        //    | 3  |   4  | 5|  h1
        // v0 +----+------+--|
        //    |    |      |  |
        //    | 0  |   1  | 2|  h0
        //    |    |      |  |
        //    +----+------+--+
        //    u0   u1    u2
        //
        //
        //  and when the texture is rotated, it will get transformed.
        //  not only the rects have a different position, but also u,v
        //  points to the bottom-left and not top-right of the texture
        //  so some swaping/origin/reordering needs to be done in order
        //  to support rotated slice-9 correctly
        //
        //       w0    w1     w2
        // v2 +------+----+--------+
        //    |      |    |        |
        //    |   0  |  3 |    6   | h2
        // v1 +------+----+--------+
        //    |      |    |        |
        //    |   1  |  4 |    7   | h1
        //    |      |    |        |
        // v0 +------+----+--------+
        //    |   2  |  5 |    8   | h0
        //    +------+----+--------+
        //    u0      u1     u2


        // center rect
        float cx1 = _centerRectNormalized.origin.x;
        float cy1 = _centerRectNormalized.origin.y;
        float cx2 = _centerRectNormalized.origin.x + _centerRectNormalized.size.width;
        float cy2 = _centerRectNormalized.origin.y + _centerRectNormalized.size.height;

        // "O"riginal rect
        const float oox = _rect.origin.x;
        const float ooy = _rect.origin.y;
        float osw = _rect.size.width;
        float osh = _rect.size.height;

        if (_rectRotated)
        {
            std::swap(cx1, cy1);
            std::swap(cx2, cy2);

            // when the texture is rotated, then the centerRect starts from the "bottom" (left)
            // but when it is not rotated, it starts from the top, so invert it
            cy2 = 1 - cy2;
            cy1 = 1 - cy1;
            std::swap(cy1, cy2);
            std::swap(osw, osh);
        }

        //
        // textCoords Data: Y must be inverted.
        //
        const float w0 = osw * cx1;
        const float w1 = osw * (cx2-cx1);
        const float w2 = osw * (1-cx2);
        const float h0 = osh * cy1;
        const float h1 = osh * (cy2-cy1);
        const float h2 = osh * (1-cy2);

        const float u0 = oox;
        const float u1 = u0 + w0;
        const float u2 = u1 + w1;
        const float v2 = ooy;
        const float v1 = v2 + h2;
        const float v0 = v1 + h1;


        const Rect texRects_normal[9] = {
            Rect(u0, v0,    w0, h0),   // bottom-left
            Rect(u1, v0,    w1, h0),   // bottom
            Rect(u2, v0,    w2, h0),   // bottom-right

            Rect(u0, v1,    w0, h1),   // left
            Rect(u1, v1,    w1, h1),   // center
            Rect(u2, v1,    w2, h1),   // right

            Rect(u0, v2,    w0, h2),   // top-left
            Rect(u1, v2,    w1, h2),   // top
            Rect(u2, v2,    w2, h2),   // top-right
        };

        // swap width and height because setTextureCoords()
        // will expects the hight and width to be swapped
        const Rect texRects_rotated[9] = {
            Rect(u0, v2,    h2, w0),        // top-left
            Rect(u0, v1,    h1, w0),        // left
            Rect(u0, v0,    h0, w0),        // bottom-left

            Rect(u1, v2,    h2, w1),        // top
            Rect(u1, v1,    h1, w1),        // center
            Rect(u1, v0,    h0, w1),        // bottom

            Rect(u2, v2,    h2, w2),        // top-right
            Rect(u2, v1,    h1, w2),        // right
            Rect(u2, v0,    h0, w2),        // bottom-right
        };

        const Rect* texRects = _rectRotated ? texRects_rotated : texRects_normal;

        //
        // vertex Data.
        //

        // reset center rect since it is altered when when the texture
        // is rotated
        cx1 = _centerRectNormalized.origin.x;
        cy1 = _centerRectNormalized.origin.y;
        cx2 = _centerRectNormalized.origin.x + _centerRectNormalized.size.width;
        cy2 = _centerRectNormalized.origin.y + _centerRectNormalized.size.height;
        if (_rectRotated)
            std::swap(osw, osh);

        // sizes
        float x0_s = osw * cx1;
        float x1_s = osw * (cx2-cx1) * _stretchFactor.x;
        float x2_s = osw * (1-cx2);
        float y0_s = osh * cy1;
        float y1_s = osh * (cy2-cy1) * _stretchFactor.y;
        float y2_s = osh * (1-cy2);


        // avoid negative size:
        if (_contentSize.width < x0_s + x2_s)
            x2_s = x0_s = _contentSize.width / 2;

        if  (_contentSize.height < y0_s + y2_s)
            y2_s = y0_s = _contentSize.height / 2;


        // is it flipped?
        // swap sizes to calculate offset correctly
        if (_flippedX)
            std::swap(x0_s, x2_s);
        if (_flippedY)
            std::swap(y0_s, y2_s);

        // origins
        float x0 = 0;
        float x1 = x0 + x0_s;
        float x2 = x1 + x1_s;
        float y0 = 0;
        float y1 = y0 + y0_s;
        float y2 = y1 + y1_s;

        // swap origin, but restore size to its original value
        if (_flippedX)
        {
            std::swap(x0, x2);
            std::swap(x0_s, x2_s);
        }
        if (_flippedY)
        {
            std::swap(y0, y2);
            std::swap(y0_s, y2_s);
        }

        const Rect verticesRects[9] = {
            Rect(x0, y0,  x0_s, y0_s),      // bottom-left
            Rect(x1, y0,  x1_s, y0_s),      // bottom
            Rect(x2, y0,  x2_s, y0_s),      // bottom-right

            Rect(x0, y1,  x0_s, y1_s),      // left
            Rect(x1, y1,  x1_s, y1_s),      // center
            Rect(x2, y1,  x2_s, y1_s),      // right

            Rect(x0, y2,  x0_s, y2_s),      // top-left
            Rect(x1, y2,  x1_s, y2_s),      // top
            Rect(x2, y2,  x2_s, y2_s),      // top-right
        };

        // needed in order to get color from "_quad"
        V3F_C4B_T2F_Quad tmpQuad = _quad;

        for (int i=0; i<9; ++i)
        {
            setTextureCoords(texRects[i], &tmpQuad);
            setVertexCoords(verticesRects[i], &tmpQuad);
            populateTriangle(i, tmpQuad);
        }
        TrianglesCommand::Triangles triangles;
        triangles.verts = _trianglesVertex;
        triangles.vertCount = 16;
        triangles.indices = _trianglesIndex;
        triangles.indexCount = 6 * 9;   // 9 quads, each needs 6 vertices

        // probably we can update the _trianglesCommand directly
        // to avoid memcpy'ing stuff
        _polyInfo.setTriangles(triangles);
    }
}

void Sprite::setCenterRectNormalized(const cocos2d::Rect &rectTopLeft)
{
    if (_renderMode != RenderMode::QUAD && _renderMode != RenderMode::SLICE9) {
        CCLOGWARN("Warning: Sprite::setCenterRectNormalized() only works with QUAD and SLICE9 render modes");
        return;
    }

    // FIMXE: Rect is has origin on top-left (like text coordinate).
    // but all the logic has been done using bottom-left as origin. So it is easier to invert Y
    // here, than in the rest of the places... but it is not as clean.
    Rect rect(rectTopLeft.origin.x, 1 - rectTopLeft.origin.y - rectTopLeft.size.height, rectTopLeft.size.width, rectTopLeft.size.height);
    if (!_centerRectNormalized.equals(rect))
    {
        _centerRectNormalized = rect;

        // convert it to 1-slice when the centerRect is not present.
        if (rect.equals(Rect(0,0,1,1)))
        {
            _renderMode = RenderMode::QUAD;
            free(_trianglesVertex);
            free(_trianglesIndex);
            _trianglesVertex = nullptr;
            _trianglesIndex = nullptr;
        }
        else
        {
            // convert it to 9-slice if it isn't already
            if (_renderMode != RenderMode::SLICE9)
            {
                _renderMode = RenderMode::SLICE9;
                // 9 quads + 7 exterior points = 16
                _trianglesVertex = (V3F_C4B_T2F*) malloc(sizeof(*_trianglesVertex) * (9 + 3 + 4));
                // 9 quads, each needs 6 vertices = 54
                _trianglesIndex = (unsigned short*) malloc(sizeof(*_trianglesIndex) * 6 * 9);

                // populate indices in CCW direction
                for (int i=0; i<9; ++i)
                {
                    _trianglesIndex[i * 6 + 0] = (i * 4 / 3) + 4;
                    _trianglesIndex[i * 6 + 1] = (i * 4 / 3) + 0;
                    _trianglesIndex[i * 6 + 2] = (i * 4 / 3) + 5;
                    _trianglesIndex[i * 6 + 3] = (i * 4 / 3) + 1;
                    _trianglesIndex[i * 6 + 4] = (i * 4 / 3) + 5;
                    _trianglesIndex[i * 6 + 5] = (i * 4 / 3) + 0;
                }
            }
        }

        updateStretchFactor();
        updatePoly();
        updateColor();
    }
}

void Sprite::setCenterRect(const cocos2d::Rect &rectInPoints)
{
    if (_renderMode != RenderMode::QUAD && _renderMode != RenderMode::SLICE9)
    {
        CCLOGWARN("Warning: Sprite::setCenterRect() only works with QUAD and SLICE9 render modes");
        return;
    }

    if (!_originalContentSize.equals(Size::ZERO))
    {
        Rect rect = rectInPoints;

        const float x = rect.origin.x / _rect.size.width;
        const float y = rect.origin.y / _rect.size.height;
        const float w = rect.size.width / _rect.size.width;
        const float h = rect.size.height / _rect.size.height;
        setCenterRectNormalized(Rect(x,y,w,h));
    }
}

Rect Sprite::getCenterRectNormalized() const
{
    // FIXME: _centerRectNormalized is in bottom-left coords, but should converted to top-left
    Rect ret(_centerRectNormalized.origin.x,
             1 - _centerRectNormalized.origin.y - _centerRectNormalized.size.height,
             _centerRectNormalized.size.width,
             _centerRectNormalized.size.height);
    return ret;
}

Rect Sprite::getCenterRect() const
{
    Rect rect = getCenterRectNormalized();
    rect.origin.x *= _rect.size.width;
    rect.origin.y *= _rect.size.height;
    rect.size.width *= _rect.size.width;
    rect.size.height *= _rect.size.height;
    return rect;
}

// override this method to generate "double scale" sprites
void Sprite::setVertexRect(const Rect& rect)
{
    _rect = rect;
}

void Sprite::setTextureCoords(const Rect& rectInPoints)
{
    setTextureCoords(rectInPoints, &_quad);
}

void Sprite::setTextureCoords(const Rect& rectInPoints, V3F_C4B_T2F_Quad* outQuad)
{
    Texture2D *tex = (_renderMode == RenderMode::QUAD_BATCHNODE) ? _textureAtlas->getTexture() : _texture;
    
    if (tex == nullptr)
        return;

    const auto rectInPixels = CC_RECT_POINTS_TO_PIXELS(rectInPoints);

    const float atlasWidth = (float)tex->getPixelsWide();
    const float atlasHeight = (float)tex->getPixelsHigh();
   
    float rw = rectInPixels.size.width;
    float rh = rectInPixels.size.height;

    // if the rect is rotated, it means that the frame is rotated 90 degrees (clockwise) and:
    //  - rectInpoints: origin will be the bottom-left of the frame (and not the top-right)
    //  - size: represents the unrotated texture size
    //
    // so what we have to do is:
    //  - swap texture width and height
    //  - take into account the origin
    //  - flip X instead of Y when flipY is enabled
    //  - flip Y instead of X when flipX is enabled

    if (_rectRotated)
        std::swap(rw, rh);

#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
    float left    = (2*rectInPixels.origin.x+1) / (2*atlasWidth);
    float right   = left+(rw*2-2) / (2*atlasWidth);
    float top     = (2*rectInPixels.origin.y+1) / (2*atlasHeight);
    float bottom  = top+(rh*2-2) / (2*atlasHeight);
#else
    float left    = rectInPixels.origin.x / atlasWidth;
    float right   = (rectInPixels.origin.x + rw) / atlasWidth;
    float top     = rectInPixels.origin.y / atlasHeight;
    float bottom  = (rectInPixels.origin.y + rh) / atlasHeight;
#endif // CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL


    if ((!_rectRotated && _flippedX) || (_rectRotated && _flippedY))
        std::swap(left, right);

    if ((!_rectRotated && _flippedY) || (_rectRotated && _flippedX))
        std::swap(top, bottom);

    if (_rectRotated)
    {
        outQuad->bl.texCoords.u = left;
        outQuad->bl.texCoords.v = top;
        outQuad->br.texCoords.u = left;
        outQuad->br.texCoords.v = bottom;
        outQuad->tl.texCoords.u = right;
        outQuad->tl.texCoords.v = top;
        outQuad->tr.texCoords.u = right;
        outQuad->tr.texCoords.v = bottom;
    }
    else
    {
        outQuad->bl.texCoords.u = left;
        outQuad->bl.texCoords.v = bottom;
        outQuad->br.texCoords.u = right;
        outQuad->br.texCoords.v = bottom;
        outQuad->tl.texCoords.u = left;
        outQuad->tl.texCoords.v = top;
        outQuad->tr.texCoords.u = right;
        outQuad->tr.texCoords.v = top;
    }
}

void Sprite::setVertexCoords(const Rect& rect, V3F_C4B_T2F_Quad* outQuad)
{
    float relativeOffsetX = _unflippedOffsetPositionFromCenter.x;
    float relativeOffsetY = _unflippedOffsetPositionFromCenter.y;

    // issue #732
    if (_flippedX)
        relativeOffsetX = -relativeOffsetX;
    if (_flippedY)
        relativeOffsetY = -relativeOffsetY;

    _offsetPosition.x = relativeOffsetX + (_originalContentSize.width - _rect.size.width) / 2;
    _offsetPosition.y = relativeOffsetY + (_originalContentSize.height - _rect.size.height) / 2;

    // FIXME: Stretching should be applied to the "offset" as well
    // but probably it should be calculated in the caller function. It will be tidier
    if (_renderMode == RenderMode::QUAD)
    {
        _offsetPosition.x *= _stretchFactor.x;
        _offsetPosition.y *= _stretchFactor.y;
    }

    // rendering using batch node
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
    {
        // update dirty_, don't update recursiveDirty_
        setDirty(true);
    }
    else
    {
        // self rendering

        // Atlas: Vertex
        const float x1 = 0.0f + _offsetPosition.x + rect.origin.x;
        const float y1 = 0.0f + _offsetPosition.y + rect.origin.y;
        const float x2 = x1 + rect.size.width;
        const float y2 = y1 + rect.size.height;

        // Don't update Z.
        outQuad->bl.vertices.set(x1, y1, 0.0f);
        outQuad->br.vertices.set(x2, y1, 0.0f);
        outQuad->tl.vertices.set(x1, y2, 0.0f);
        outQuad->tr.vertices.set(x2, y2, 0.0f);
    }
}

void Sprite::populateTriangle(int quadIndex, const V3F_C4B_T2F_Quad& quad)
{
    CCASSERT(quadIndex < 9, "Invalid quadIndex");
    // convert Quad intro Triangle since it takes less memory

    // Triangles are ordered like the following:
    //   Numbers: Quad Index
    //   Letters: triangles' vertices
    //
    //  M-----N-----O-----P
    //  |     |     |     |
    //  |  6  |  7  |  8  |
    //  |     |     |     |
    //  I-----J-----K-----L
    //  |     |     |     |
    //  |  3  |  4  |  5  |
    //  |     |     |     |
    //  E-----F-----G-----H
    //  |     |     |     |
    //  |  0  |  1  |  2  |
    //  |     |     |     |
    //  A-----B-----C-----D
    //
    // So, if QuadIndex == 4, then it should update vertices J,K,F,G

    // Optimization: I don't need to copy all the vertices all the time. just the 4 "quads" from the corners.
    if (quadIndex == 0 || quadIndex == 2 || quadIndex == 6 || quadIndex == 8)
    {
        if (_flippedX)
        {
            if (quadIndex % 3 == 0)
                quadIndex += 2;
            else
                quadIndex -= 2;
        }

        if (_flippedY)
        {
            if (quadIndex <= 2)
                quadIndex += 6;
            else
                quadIndex -= 6;
        }

        const int index_bl = quadIndex * 4 / 3;
        const int index_br = index_bl + 1;
        const int index_tl = index_bl + 4;
        const int index_tr = index_bl + 5;

        _trianglesVertex[index_tr] = quad.tr;
        _trianglesVertex[index_br] = quad.br;
        _trianglesVertex[index_tl] = quad.tl;
        _trianglesVertex[index_bl] = quad.bl;
    }
}


// MARK: visit, draw, transform

void Sprite::updateTransform()
{
    CCASSERT(_renderMode == RenderMode::QUAD_BATCHNODE, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode");

    // recalculate matrix only if it is dirty
    if(isDirty() )
    {
        // If it is not visible, or one of its ancestors is not visible, then do nothing:
        if( !_visible || ( _parent && _parent != _batchNode && static_cast<Sprite*>(_parent)->_shouldBeHidden) )
        {
            _quad.br.vertices.setZero();
            _quad.tl.vertices.setZero();
            _quad.tr.vertices.setZero();
            _quad.bl.vertices.setZero();
            _shouldBeHidden = true;
        }
        else
        {
            _shouldBeHidden = false;

            if( ! _parent || _parent == _batchNode )
                _transformToBatch = getNodeToParentTransform();
            else
            {
                CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite");
                const Mat4 &nodeToParent = getNodeToParentTransform();
                Mat4 &parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch;
                _transformToBatch = parentTransform * nodeToParent;
            }

            //
            // calculate the Quad based on the Affine Matrix
            //

            Size &size = _rect.size;

            float x1 = _offsetPosition.x;
            float y1 = _offsetPosition.y;

            float x2 = x1 + size.width;
            float y2 = y1 + size.height;

            float x = _transformToBatch.m[12];
            float y = _transformToBatch.m[13];

            float cr = _transformToBatch.m[0];
            float sr = _transformToBatch.m[1];
            float cr2 = _transformToBatch.m[5];
            float sr2 = -_transformToBatch.m[4];
            float ax = x1 * cr - y1 * sr2 + x;
            float ay = x1 * sr + y1 * cr2 + y;

            float bx = x2 * cr - y1 * sr2 + x;
            float by = x2 * sr + y1 * cr2 + y;

            float cx = x2 * cr - y2 * sr2 + x;
            float cy = x2 * sr + y2 * cr2 + y;

            float dx = x1 * cr - y2 * sr2 + x;
            float dy = x1 * sr + y2 * cr2 + y;

            _quad.bl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(ax), SPRITE_RENDER_IN_SUBPIXEL(ay), _positionZ);
            _quad.br.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(bx), SPRITE_RENDER_IN_SUBPIXEL(by), _positionZ);
            _quad.tl.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(dx), SPRITE_RENDER_IN_SUBPIXEL(dy), _positionZ);
            _quad.tr.vertices.set(SPRITE_RENDER_IN_SUBPIXEL(cx), SPRITE_RENDER_IN_SUBPIXEL(cy), _positionZ);
            setTextureCoords(_rect);
        }

        // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS
        if (_textureAtlas)
            _textureAtlas->updateQuad(&_quad, _atlasIndex);

        _recursiveDirty = false;
        setDirty(false);
    }

    Node::updateTransform();
}

// draw
void Sprite::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
    if (_texture == nullptr || _texture->getBackendTexture() == nullptr)
        return;
    
    //TODO: arnold: current camera can be a non-default one.
    setMVPMatrixUniform();

#if CC_USE_CULLING
    // Don't calculate the culling if the transform was not updated
    auto visitingCamera = Camera::getVisitingCamera();
    auto defaultCamera = Camera::getDefaultCamera();
    if (visitingCamera == nullptr)
        _insideBounds = true;
    else if (visitingCamera == defaultCamera)
        _insideBounds = ((flags & FLAGS_TRANSFORM_DIRTY) || visitingCamera->isViewProjectionUpdated()) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
    else
        // XXX: this always return true since
        _insideBounds = renderer->checkVisibility(transform, _contentSize);

    if(_insideBounds)
#endif
    {
        _trianglesCommand.init(_globalZOrder,
                               _texture,
                               _blendFunc,
                               _polyInfo.triangles,
                               transform,
                               flags);
        renderer->addCommand(&_trianglesCommand);
        
#if CC_SPRITE_DEBUG_DRAW
            _debugDrawNode->clear();
            auto count = _polyInfo.triangles.indexCount / 3;
            auto indices = _polyInfo.triangles.indices;
            auto verts = _polyInfo.triangles.verts;
            for(unsigned int i = 0; i < count; i++)
            {
                //draw 3 lines
                Vec3 from =verts[indices[i*3]].vertices;
                Vec3 to = verts[indices[i*3+1]].vertices;
                _debugDrawNode->drawLine(Vec2(from.x, from.y), Vec2(to.x,to.y), Color4F::WHITE);
                
                from =verts[indices[i*3+1]].vertices;
                to = verts[indices[i*3+2]].vertices;
                _debugDrawNode->drawLine(Vec2(from.x, from.y), Vec2(to.x,to.y), Color4F::WHITE);
                
                from =verts[indices[i*3+2]].vertices;
                to = verts[indices[i*3]].vertices;
                _debugDrawNode->drawLine(Vec2(from.x, from.y), Vec2(to.x,to.y), Color4F::WHITE);
            }
#endif //CC_SPRITE_DEBUG_DRAW
    }
}

// MARK: visit, draw, transform

void Sprite::addChild(Node *child, int zOrder, int tag)
{
    CCASSERT(child != nullptr, "Argument must be non-nullptr");
    if (child == nullptr)
        return;

    if (_renderMode == RenderMode::QUAD_BATCHNODE)
    {
        Sprite* childSprite = dynamic_cast<Sprite*>(child);
        CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
        CCASSERT(childSprite->getTexture() == _textureAtlas->getTexture(), "childSprite's texture name should be equal to _textureAtlas's texture name!");
        //put it in descendants array of batch node
        _batchNode->appendChild(childSprite);

        if (!_reorderChildDirty)
        {
            setReorderChildDirtyRecursively();
        }
    }
    //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
    Node::addChild(child, zOrder, tag);
}

void Sprite::addChild(Node *child, int zOrder, const std::string &name)
{
    CCASSERT(child != nullptr, "Argument must be non-nullptr");
    if (child == nullptr)
        return;

    if (_renderMode == RenderMode::QUAD_BATCHNODE)
    {
        Sprite* childSprite = dynamic_cast<Sprite*>(child);
        CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode");
        CCASSERT(childSprite->getTexture() == _textureAtlas->getTexture(),
                 "childSprite's texture name should be equal to _textureAtlas's texture name.");
        //put it in descendants array of batch node
        _batchNode->appendChild(childSprite);

        if (!_reorderChildDirty)
        {
            setReorderChildDirtyRecursively();
        }
    }
    //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check
    Node::addChild(child, zOrder, name);
}

void Sprite::reorderChild(Node *child, int zOrder)
{
    CCASSERT(child != nullptr, "child must be non null");
    CCASSERT(_children.contains(child), "child does not belong to this");

    if ((_renderMode == RenderMode::QUAD_BATCHNODE) && ! _reorderChildDirty)
    {
        setReorderChildDirtyRecursively();
        _batchNode->reorderBatch(true);
    }

    Node::reorderChild(child, zOrder);
}

void Sprite::removeChild(Node *child, bool cleanup)
{
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
        _batchNode->removeSpriteFromAtlas((Sprite*)(child));

    Node::removeChild(child, cleanup);
}

void Sprite::removeAllChildrenWithCleanup(bool cleanup)
{
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
    {
        for(const auto &child : _children)
        {
            Sprite* sprite = dynamic_cast<Sprite*>(child);
            if (sprite)
                _batchNode->removeSpriteFromAtlas(sprite);
        }
    }

    Node::removeAllChildrenWithCleanup(cleanup);
}

void Sprite::sortAllChildren()
{
    if (_reorderChildDirty)
    {
        sortNodes(_children);

        if (_renderMode == RenderMode::QUAD_BATCHNODE)
        {
            for(const auto &child : _children)
                child->sortAllChildren();
        }

        _reorderChildDirty = false;
    }
}

//
// Node property overloads
// used only when parent is SpriteBatchNode
//

void Sprite::setReorderChildDirtyRecursively()
{
    //only set parents flag the first time
    if ( ! _reorderChildDirty )
    {
        _reorderChildDirty = true;
        Node* node = static_cast<Node*>(_parent);
        while (node && node != _batchNode)
        {
            static_cast<Sprite*>(node)->setReorderChildDirtyRecursively();
            node=node->getParent();
        }
    }
}

void Sprite::setDirtyRecursively(bool bValue)
{
    _recursiveDirty = bValue;
    setDirty(bValue);

    for(const auto &child: _children)
    {
        Sprite* sp = dynamic_cast<Sprite*>(child);
        if (sp)
            sp->setDirtyRecursively(true);
    }
}

// FIXME: HACK: optimization
#define SET_DIRTY_RECURSIVELY() {                       \
                    if (! _recursiveDirty) {            \
                        _recursiveDirty = true;         \
                        setDirty(true);                 \
                        if (!_children.empty())         \
                            setDirtyRecursively(true);  \
                        }                               \
                    }

void Sprite::setPosition(const Vec2& pos)
{
    Node::setPosition(pos);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setPosition(float x, float y)
{
    Node::setPosition(x, y);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setRotation(float rotation)
{
    Node::setRotation(rotation);

    SET_DIRTY_RECURSIVELY();
}

void Sprite::setRotationSkewX(float fRotationX)
{
    Node::setRotationSkewX(fRotationX);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setRotationSkewY(float fRotationY)
{
    Node::setRotationSkewY(fRotationY);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setSkewX(float sx)
{
    Node::setSkewX(sx);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setSkewY(float sy)
{
    Node::setSkewY(sy);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setScaleX(float scaleX)
{
    Node::setScaleX(scaleX);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setScaleY(float scaleY)
{
#ifdef CC_USE_METAL
    if(_texture->isRenderTarget())
       scaleY = std::abs(scaleY);
#endif
    Node::setScaleY(scaleY);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setScale(float fScale)
{
    Node::setScale(fScale);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setScale(float scaleX, float scaleY)
{
    Node::setScale(scaleX, scaleY);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setPositionZ(float fVertexZ)
{
    Node::setPositionZ(fVertexZ);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setAnchorPoint(const Vec2& anchor)
{
    Node::setAnchorPoint(anchor);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setIgnoreAnchorPointForPosition(bool value)
{
    CCASSERT(_renderMode != RenderMode::QUAD_BATCHNODE, "setIgnoreAnchorPointForPosition is invalid in Sprite");
    Node::setIgnoreAnchorPointForPosition(value);
}

void Sprite::setVisible(bool bVisible)
{
    Node::setVisible(bVisible);
    SET_DIRTY_RECURSIVELY();
}

void Sprite::setContentSize(const Size& size)
{
    if (_renderMode == RenderMode::QUAD_BATCHNODE || _renderMode == RenderMode::POLYGON)
        CCLOGWARN("Sprite::setContentSize() doesn't stretch the sprite when using QUAD_BATCHNODE or POLYGON render modes");

    Node::setContentSize(size);

    updateStretchFactor();
    updatePoly();
}

void Sprite::setStretchEnabled(bool enabled)
{
    if (_stretchEnabled != enabled)
    {
        _stretchEnabled = enabled;

        // disabled centerrect / number of slices if disabled
        if (!enabled)
            setCenterRectNormalized(Rect(0,0,1,1));

        updateStretchFactor();
        updatePoly();
    }
}

bool Sprite::isStretchEnabled() const
{
    return _stretchEnabled;
}

void Sprite::updateStretchFactor()
{
    const Size size = getContentSize();

    if (_renderMode == RenderMode::QUAD)
    {
        // If stretch is disabled, calculate the stretch anyway
        // since it is needed to calculate the offset
        const float x_factor = size.width / _originalContentSize.width;
        const float y_factor = size.height / _originalContentSize.height;

        _stretchFactor = Vec2(std::max(0.0f, x_factor),
                              std::max(0.0f, y_factor));
    }
    else if (_renderMode == RenderMode::SLICE9)
    {
        const float x1 = _rect.size.width * _centerRectNormalized.origin.x;
        const float x2 = _rect.size.width * _centerRectNormalized.size.width;
        const float x3 = _rect.size.width * (1 - _centerRectNormalized.origin.x - _centerRectNormalized.size.width);

        const float y1 = _rect.size.height * _centerRectNormalized.origin.y;
        const float y2 = _rect.size.height * _centerRectNormalized.size.height;
        const float y3 = _rect.size.height * (1 - _centerRectNormalized.origin.y - _centerRectNormalized.size.height);

        // adjustedSize = the new _rect size
        const float adjustedWidth = size.width - (_originalContentSize.width - _rect.size.width);
        const float adjustedHeight = size.height - (_originalContentSize.height - _rect.size.height);

        const float x_factor = (adjustedWidth - x1 - x3) / x2;
        const float y_factor = (adjustedHeight - y1 - y3) / y2;

        _stretchFactor = Vec2(std::max(0.0f, x_factor),
                              std::max(0.0f, y_factor));
    }

    // else:
    // Do nothing if renderMode is Polygon
}

void Sprite::setFlippedX(bool flippedX)
{
    if (_flippedX != flippedX)
    {
        _flippedX = flippedX;
        flipX();
    }
}

bool Sprite::isFlippedX() const
{
    return _flippedX;
}

void Sprite::setFlippedY(bool flippedY)
{
#ifdef CC_USE_METAL
    if(_texture->isRenderTarget())
        flippedY = !flippedY;
#endif
    if (_flippedY != flippedY)
    {
        _flippedY = flippedY;
        flipY();
    }
}

bool Sprite::isFlippedY() const
{
    return _flippedY;
}

void Sprite::flipX()
{
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
        setDirty(true);
    else if (_renderMode == RenderMode::POLYGON)
    {
        for (unsigned int i = 0; i < _polyInfo.triangles.vertCount; i++) {
            auto& v = _polyInfo.triangles.verts[i].vertices;
            v.x = _contentSize.width -v.x;
        }
    }
    else
        // RenderMode:: Quad or Slice9
        updatePoly();
}

void Sprite::flipY()
{
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
        setDirty(true);
    else if (_renderMode == RenderMode::POLYGON)
    {
        for (unsigned int i = 0; i < _polyInfo.triangles.vertCount; i++) {
            auto& v = _polyInfo.triangles.verts[i].vertices;
            v.y = _contentSize.height -v.y;
        }
    }
    else
        // RenderMode:: Quad or Slice9
        updatePoly();
}

//
// MARK: RGBA protocol
//

void Sprite::updateColor()
{
    Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );

    // special opacity for premultiplied textures
    if (_opacityModifyRGB)
    {
        color4.r *= _displayedOpacity / 255.0f;
        color4.g *= _displayedOpacity / 255.0f;
        color4.b *= _displayedOpacity / 255.0f;
    }

    for (unsigned int i = 0; i < _polyInfo.triangles.vertCount; i++)
        _polyInfo.triangles.verts[i].colors = color4;

    // related to issue #17116
    // when switching from Quad to Slice9, the color will be obtained from _quad
    // so it is important to update _quad colors as well.
    _quad.bl.colors = _quad.tl.colors = _quad.br.colors = _quad.tr.colors = color4;

    // renders using batch node
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
    {
        if (_atlasIndex != INDEX_NOT_INITIALIZED)
            _textureAtlas->updateQuad(&_quad, _atlasIndex);
        else
            // no need to set it recursively
            // update dirty_, don't update recursiveDirty_
            setDirty(true);
    }

    // self render
    // do nothing
}

void Sprite::setOpacityModifyRGB(bool modify)
{
    if (_opacityModifyRGB != modify)
    {
        _opacityModifyRGB = modify;
        updateColor();
    }
}

bool Sprite::isOpacityModifyRGB() const
{
    return _opacityModifyRGB;
}

// MARK: Frames

void Sprite::setSpriteFrame(const std::string &spriteFrameName)
{
    CCASSERT(!spriteFrameName.empty(), "spriteFrameName must not be empty");
    if (spriteFrameName.empty())
        return;

    SpriteFrameCache *cache = SpriteFrameCache::getInstance();
    SpriteFrame *spriteFrame = cache->getSpriteFrameByName(spriteFrameName);

    CCASSERT(spriteFrame, std::string("Invalid spriteFrameName :").append(spriteFrameName).c_str());

    setSpriteFrame(spriteFrame);
}

void Sprite::setSpriteFrame(SpriteFrame *spriteFrame)
{
    // retain the sprite frame
    // do not removed by SpriteFrameCache::removeUnusedSpriteFrames
    if (_spriteFrame != spriteFrame)
    {
        CC_SAFE_RELEASE(_spriteFrame);
        _spriteFrame = spriteFrame;
        spriteFrame->retain();
    }
    _unflippedOffsetPositionFromCenter = spriteFrame->getOffset();

    Texture2D *texture = spriteFrame->getTexture();
    // update texture before updating texture rect
    if (texture != _texture)
        setTexture(texture);

    // update rect
    _rectRotated = spriteFrame->isRotated();
    setTextureRect(spriteFrame->getRect(), _rectRotated, spriteFrame->getOriginalSize());

    if (spriteFrame->hasPolygonInfo())
    {
        _polyInfo = spriteFrame->getPolygonInfo();
        _renderMode = RenderMode::POLYGON;
        if (_flippedX) flipX();
        if (_flippedY) flipY();
        updateColor();
    }
    if (spriteFrame->hasAnchorPoint())
        setAnchorPoint(spriteFrame->getAnchorPoint());
    if (spriteFrame->hasCenterRect())
        setCenterRect(spriteFrame->getCenterRect());
}

void Sprite::setDisplayFrameWithAnimationName(const std::string& animationName, unsigned int frameIndex)
{
    CCASSERT(!animationName.empty(), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be nullptr");
    if (animationName.empty())
        return;

    Animation *a = AnimationCache::getInstance()->getAnimation(animationName);

    CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found");

    AnimationFrame* frame = a->getFrames().at(frameIndex);

    CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame");

    setSpriteFrame(frame->getSpriteFrame());
}

bool Sprite::isFrameDisplayed(SpriteFrame *frame) const
{
    Rect r = frame->getRect();

    return (r.equals(_rect) &&
            frame->getTexture() == _texture &&
            frame->getOffset().equals(_unflippedOffsetPositionFromCenter));
}

SpriteFrame* Sprite::getSpriteFrame() const
{
    if (nullptr != this->_spriteFrame)
        return this->_spriteFrame;

    return SpriteFrame::createWithTexture(_texture,
                                          CC_RECT_POINTS_TO_PIXELS(_rect),
                                          _rectRotated,
                                          CC_POINT_POINTS_TO_PIXELS(_unflippedOffsetPositionFromCenter),
                                          CC_SIZE_POINTS_TO_PIXELS(_originalContentSize));
}

SpriteBatchNode* Sprite::getBatchNode() const
{
    return _batchNode;
}

void Sprite::setBatchNode(SpriteBatchNode *spriteBatchNode)
{
    _batchNode = spriteBatchNode; // weak reference

    // self render
    if (! _batchNode)
    {
        if (_renderMode != RenderMode::SLICE9)
            _renderMode = RenderMode::QUAD;

        _atlasIndex = INDEX_NOT_INITIALIZED;
        setTextureAtlas(nullptr);
        _recursiveDirty = false;
        setDirty(false);

        float x1 = _offsetPosition.x;
        float y1 = _offsetPosition.y;
        float x2 = x1 + _rect.size.width;
        float y2 = y1 + _rect.size.height;
        _quad.bl.vertices.set( x1, y1, 0 );
        _quad.br.vertices.set(x2, y1, 0);
        _quad.tl.vertices.set(x1, y2, 0);
        _quad.tr.vertices.set(x2, y2, 0);

    }
    else
    {
        // using batch
        _renderMode = RenderMode::QUAD_BATCHNODE;
        _transformToBatch = Mat4::IDENTITY;
        setTextureAtlas(_batchNode->getTextureAtlas()); // weak ref
    }
}

// MARK: Texture protocol
void Sprite::updateBlendFunc()
{
    CCASSERT(_renderMode != RenderMode::QUAD_BATCHNODE, "CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a SpriteBatchNode");
    
    // it is possible to have an untextured sprite
    backend::BlendDescriptor& blendDescriptor = _trianglesCommand.getPipelineDescriptor().blendDescriptor;
    blendDescriptor.blendEnabled = true;
    
    if (! _texture || ! _texture->hasPremultipliedAlpha())
    {
        _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
        setOpacityModifyRGB(false);
    }
    else
    {
        _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
        setOpacityModifyRGB(true);
    }
}

std::string Sprite::getDescription() const
{
    char textureDescriptor[100];
    if (_renderMode == RenderMode::QUAD_BATCHNODE)
        sprintf(textureDescriptor, "<Sprite | Tag = %d, TextureID = %p>", _tag, _batchNode->getTextureAtlas()->getTexture()->getBackendTexture());
    else
        sprintf(textureDescriptor, "<Sprite | Tag = %d, TextureID = %p>", _tag, _texture->getBackendTexture());
    
    return textureDescriptor;
}

const PolygonInfo& Sprite::getPolygonInfo() const
{
    return _polyInfo;
}

void Sprite::setPolygonInfo(const PolygonInfo& info)
{
    _polyInfo = info;
    _renderMode = RenderMode::POLYGON;
}

void Sprite::setMVPMatrixUniform()
{
    const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
    auto programState = _trianglesCommand.getPipelineDescriptor().programState;
    if (programState && _mvpMatrixLocation)
        programState->setUniform(_mvpMatrixLocation, projectionMat.m, sizeof(projectionMat.m));
}

backend::ProgramState* Sprite::getProgramState() const
{
    return _programState;
}

NS_CC_END