SpritePacker.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/Context.h>
  23. #include <Urho3D/Core/ProcessUtils.h>
  24. #include <Urho3D/Core/StringUtils.h>
  25. #include <Urho3D/IO/File.h>
  26. #include <Urho3D/IO/FileSystem.h>
  27. #include <Urho3D/IO/Log.h>
  28. #include <Urho3D/Resource/Image.h>
  29. #include <Urho3D/Resource/XMLElement.h>
  30. #include <Urho3D/Resource/XMLFile.h>
  31. #ifdef WIN32
  32. #include <windows.h>
  33. #endif
  34. #define STBRP_LARGE_RECTS
  35. #define STB_RECT_PACK_IMPLEMENTATION
  36. #include "stb_rect_pack.h"
  37. #include <Urho3D/DebugNew.h>
  38. using namespace Urho3D;
  39. // number of nodes allocated to each packer info. since this packer is not suited for real time purposes we can over allocate.
  40. const int PACKER_NUM_NODES = 4096;
  41. const int MAX_TEXTURE_SIZE = 2048;
  42. int main(int argc, char** argv);
  43. void Run(Vector<String>& arguments);
  44. class PackerInfo : public RefCounted
  45. {
  46. public:
  47. String path;
  48. String name;
  49. int x;
  50. int y;
  51. int offsetX;
  52. int offsetY;
  53. int width;
  54. int height;
  55. int frameWidth;
  56. int frameHeight;
  57. int frameX;
  58. int frameY;
  59. PackerInfo(String path_, String name_) :
  60. path(path_),
  61. name(name_),
  62. x(0),
  63. y(0),
  64. offsetX(0),
  65. offsetY(0),
  66. frameX(0),
  67. frameY(0)
  68. {
  69. }
  70. ~PackerInfo() {}
  71. };
  72. void Help()
  73. {
  74. ErrorExit("Usage: SpritePacker -options <input file> <input file> <output png file>\n"
  75. "\n"
  76. "Options:\n"
  77. "-h Shows this help message.\n"
  78. "-px Adds x pixels of padding per image to width.\n"
  79. "-py Adds y pixels of padding per image to height.\n"
  80. "-ox Adds x pixels to the horizontal position per image.\n"
  81. "-oy Adds y pixels to the horizontal position per image.\n"
  82. "-frameHeight Sets a fixed height for image and centers within frame.\n"
  83. "-frameWidth Sets a fixed width for image and centers within frame.\n"
  84. "-trim Trims excess transparent space from individual images offsets by frame size.\n"
  85. "-xml \'path\' Generates an SpriteSheet xml file at path.\n"
  86. "-debug Draws allocation boxes on sprite.\n");
  87. }
  88. int main(int argc, char** argv)
  89. {
  90. Vector<String> arguments;
  91. #ifdef WIN32
  92. arguments = ParseArguments(GetCommandLineW());
  93. #else
  94. arguments = ParseArguments(argc, argv);
  95. #endif
  96. Run(arguments);
  97. return 0;
  98. }
  99. void Run(Vector<String>& arguments)
  100. {
  101. if (arguments.Size() < 2)
  102. Help();
  103. SharedPtr<Context> context(new Context());
  104. context->RegisterSubsystem(new FileSystem(context));
  105. context->RegisterSubsystem(new Log(context));
  106. FileSystem* fileSystem = context->GetSubsystem<FileSystem>();
  107. Vector<String> inputFiles;
  108. String outputFile;
  109. String spriteSheetFileName;
  110. bool debug = false;
  111. unsigned padX = 0;
  112. unsigned padY = 0;
  113. unsigned offsetX = 0;
  114. unsigned offsetY = 0;
  115. unsigned frameWidth = 0;
  116. unsigned frameHeight = 0;
  117. bool help = false;
  118. bool trim = false;
  119. while (arguments.Size() > 0)
  120. {
  121. String arg = arguments[0];
  122. arguments.Erase(0);
  123. if (arg.Empty())
  124. continue;
  125. if (arg.StartsWith("-"))
  126. {
  127. if (arg == "-px") { padX = ToUInt(arguments[0]); arguments.Erase(0); }
  128. else if (arg == "-py") { padY = ToUInt(arguments[0]); arguments.Erase(0); }
  129. else if (arg == "-ox") { offsetX = ToUInt(arguments[0]); arguments.Erase(0); }
  130. else if (arg == "-oy") { offsetY = ToUInt(arguments[0]); arguments.Erase(0); }
  131. else if (arg == "-frameWidth") { frameWidth = ToUInt(arguments[0]); arguments.Erase(0); }
  132. else if (arg == "-frameHeight") { frameHeight = ToUInt(arguments[0]); arguments.Erase(0); }
  133. else if (arg == "-trim") { trim = true; }
  134. else if (arg == "-xml") { spriteSheetFileName = arguments[0]; arguments.Erase(0); }
  135. else if (arg == "-h") { help = true; break; }
  136. else if (arg == "-debug") { debug = true; }
  137. }
  138. else
  139. inputFiles.Push(arg);
  140. }
  141. if (help)
  142. Help();
  143. if (inputFiles.Size() < 2)
  144. ErrorExit("An input and output file must be specified.");
  145. if (frameWidth ^ frameHeight)
  146. ErrorExit("Both frameHeight and frameWidth must be ommited or specified.");
  147. // take last input file as output
  148. if (inputFiles.Size() > 1)
  149. {
  150. outputFile = inputFiles[inputFiles.Size() - 1];
  151. LOGINFO("Output file set to " + outputFile + ".");
  152. inputFiles.Erase(inputFiles.Size() - 1);
  153. }
  154. // set spritesheet name to outputfile.xml if not specified
  155. if (spriteSheetFileName.Empty())
  156. spriteSheetFileName = ReplaceExtension(outputFile, ".xml");
  157. if (GetParentPath(spriteSheetFileName) != GetParentPath(outputFile))
  158. ErrorExit("Both output xml and png must be in the same folder");
  159. // check all input files exist
  160. for (unsigned i = 0; i < inputFiles.Size(); ++i)
  161. {
  162. LOGINFO("Checking " + inputFiles[i] + " to see if file exists.");
  163. if (!fileSystem->FileExists(inputFiles[i]))
  164. ErrorExit("File " + inputFiles[i] + " does not exist.");
  165. }
  166. // Set the max offset equal to padding to prevent images from going out of bounds
  167. offsetX = Min((int)offsetX, (int)padX);
  168. offsetY = Min((int)offsetY, (int)padY);
  169. Vector<SharedPtr<PackerInfo > > packerInfos;
  170. for (unsigned i = 0; i < inputFiles.Size(); ++i)
  171. {
  172. String path = inputFiles[i];
  173. String name = ReplaceExtension(GetFileName(path), "");
  174. File file(context, path);
  175. Image image(context);
  176. if (!image.Load(file))
  177. ErrorExit("Could not load image " + path + ".");
  178. if (image.IsCompressed())
  179. ErrorExit(path + " is compressed. Compressed images are not allowed.");
  180. SharedPtr<PackerInfo> packerInfo(new PackerInfo(path, name));
  181. int imageWidth = image.GetWidth();
  182. int imageHeight = image.GetHeight();
  183. int trimOffsetX = 0;
  184. int trimOffsetY = 0;
  185. int adjustedWidth = imageWidth;
  186. int adjustedHeight = imageHeight;
  187. if (trim)
  188. {
  189. int minX = imageWidth;
  190. int minY = imageHeight;
  191. int maxX = 0;
  192. int maxY = 0;
  193. for (int y = 0; y < imageHeight; ++y)
  194. {
  195. for (int x = 0; x < imageWidth; ++x)
  196. {
  197. bool found = (image.GetPixelInt(x, y) & 0x000000ff) != 0;
  198. if (found) {
  199. minX = Min(minX, x);
  200. minY = Min(minY, y);
  201. maxX = Max(maxX, x);
  202. maxY = Max(maxY, y);
  203. }
  204. }
  205. }
  206. trimOffsetX = minX;
  207. trimOffsetY = minY;
  208. adjustedWidth = maxX - minX + 1;
  209. adjustedHeight = maxY - minY + 1;
  210. }
  211. if (trim)
  212. {
  213. packerInfo->frameWidth = imageWidth;
  214. packerInfo->frameHeight = imageHeight;
  215. }
  216. else if (frameWidth || frameHeight)
  217. {
  218. packerInfo->frameWidth = frameWidth;
  219. packerInfo->frameHeight = frameHeight;
  220. }
  221. packerInfo->width = adjustedWidth;
  222. packerInfo->height = adjustedHeight;
  223. packerInfo->offsetX -= trimOffsetX;
  224. packerInfo->offsetY -= trimOffsetY;
  225. packerInfos.Push(packerInfo);
  226. }
  227. int packedWidth = MAX_TEXTURE_SIZE;
  228. int packedHeight = MAX_TEXTURE_SIZE;
  229. {
  230. // fill up an list of tries in increasing size and take the first win
  231. Vector<IntVector2> tries;
  232. for(unsigned x=2; x<11; ++x)
  233. {
  234. for(unsigned y=2; y<11; ++y)
  235. tries.Push(IntVector2((1<<x), (1<<y)));
  236. }
  237. // load rectangles
  238. stbrp_rect* packerRects = new stbrp_rect[packerInfos.Size()];
  239. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  240. {
  241. PackerInfo* packerInfo = packerInfos[i];
  242. stbrp_rect* packerRect = &packerRects[i];
  243. packerRect->id = i;
  244. packerRect->h = packerInfo->height + padY;
  245. packerRect->w = packerInfo->width + padX;
  246. }
  247. bool success = false;
  248. while (tries.Size() > 0)
  249. {
  250. IntVector2 size = tries[0];
  251. tries.Erase(0);
  252. bool fit = true;
  253. int textureHeight = size.y_;
  254. int textureWidth = size.x_;
  255. if (success && textureHeight * textureWidth > packedWidth * packedHeight)
  256. continue;
  257. stbrp_context packerContext;
  258. stbrp_node packerMemory[PACKER_NUM_NODES];
  259. stbrp_init_target(&packerContext, textureWidth, textureHeight, packerMemory, packerInfos.Size());
  260. stbrp_pack_rects(&packerContext, packerRects, packerInfos.Size());
  261. // check to see if everything fit
  262. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  263. {
  264. stbrp_rect* packerRect = &packerRects[i];
  265. if (!packerRect->was_packed)
  266. {
  267. fit = false;
  268. break;
  269. }
  270. }
  271. if (fit)
  272. {
  273. success = true;
  274. // distribute values to packer info
  275. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  276. {
  277. stbrp_rect* packerRect = &packerRects[i];
  278. PackerInfo* packerInfo = packerInfos[packerRect->id];
  279. packerInfo->x = packerRect->x;
  280. packerInfo->y = packerRect->y;
  281. }
  282. packedWidth = size.x_;
  283. packedHeight = size.y_;
  284. }
  285. }
  286. delete packerRects;
  287. if (!success)
  288. ErrorExit("Could not allocate for all images. The max sprite sheet texture size is " + String(MAX_TEXTURE_SIZE) + "x" + String(MAX_TEXTURE_SIZE) + ".");
  289. }
  290. // create image for spritesheet
  291. Image spriteSheetImage(context);
  292. spriteSheetImage.SetSize(packedWidth, packedHeight, 4);
  293. // zero out image
  294. spriteSheetImage.SetData((unsigned char*)calloc(sizeof(unsigned char), packedWidth * packedHeight * 4));
  295. XMLFile xml(context);
  296. XMLElement root = xml.CreateRoot("TextureAtlas");
  297. root.SetAttribute("imagePath", GetFileNameAndExtension(outputFile));
  298. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  299. {
  300. SharedPtr<PackerInfo> packerInfo = packerInfos[i];
  301. XMLElement subTexture = root.CreateChild("SubTexture");
  302. subTexture.SetString("name", packerInfo->name);
  303. subTexture.SetInt("x", packerInfo->x + offsetX);
  304. subTexture.SetInt("y", packerInfo->y + offsetY);
  305. subTexture.SetInt("width", packerInfo->width);
  306. subTexture.SetInt("height", packerInfo->height);
  307. if (packerInfo->frameWidth || packerInfo->frameHeight)
  308. {
  309. subTexture.SetInt("frameWidth", packerInfo->frameWidth);
  310. subTexture.SetInt("frameHeight", packerInfo->frameHeight);
  311. subTexture.SetInt("offsetX", packerInfo->offsetX);
  312. subTexture.SetInt("offsetY", packerInfo->offsetY);
  313. }
  314. LOGINFO("Transfering " + packerInfo->path + " to sprite sheet.");
  315. File file(context, packerInfo->path);
  316. Image image(context);
  317. if (!image.Load(file))
  318. ErrorExit("Could not load image " + packerInfo->path + ".");
  319. for (int y = 0; y < packerInfo->height; ++y)
  320. {
  321. for (int x = 0; x < packerInfo->width; ++x)
  322. {
  323. unsigned color = image.GetPixelInt(x - packerInfo->offsetX, y - packerInfo->offsetY);
  324. spriteSheetImage.SetPixelInt(
  325. packerInfo->x + offsetX + x,
  326. packerInfo->y + offsetY + y, color);
  327. }
  328. }
  329. }
  330. if (debug)
  331. {
  332. unsigned OUTER_BOUNDS_DEBUG_COLOR = Color::BLUE.ToUInt();
  333. unsigned INNER_BOUNDS_DEBUG_COLOR = Color::GREEN.ToUInt();
  334. LOGINFO("Drawing debug information.");
  335. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  336. {
  337. SharedPtr<PackerInfo> packerInfo = packerInfos[i];
  338. // Draw outer bounds
  339. for (int x = 0; x < packerInfo->frameWidth; ++x)
  340. {
  341. spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y, OUTER_BOUNDS_DEBUG_COLOR);
  342. spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y + packerInfo->frameHeight, OUTER_BOUNDS_DEBUG_COLOR);
  343. }
  344. for (int y = 0; y < packerInfo->frameHeight; ++y)
  345. {
  346. spriteSheetImage.SetPixelInt(packerInfo->x, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR);
  347. spriteSheetImage.SetPixelInt(packerInfo->x + packerInfo->frameWidth, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR);
  348. }
  349. // Draw inner bounds
  350. for (int x = 0; x < packerInfo->width; ++x)
  351. {
  352. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY, INNER_BOUNDS_DEBUG_COLOR);
  353. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY + packerInfo->height, INNER_BOUNDS_DEBUG_COLOR);
  354. }
  355. for (int y = 0; y < packerInfo->height; ++y)
  356. {
  357. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR);
  358. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + packerInfo->width, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR);
  359. }
  360. }
  361. }
  362. LOGINFO("Saving output image.");
  363. spriteSheetImage.SavePNG(outputFile);
  364. LOGINFO("Saving SpriteSheet xml file.");
  365. File spriteSheetFile(context);
  366. spriteSheetFile.Open(spriteSheetFileName, FILE_WRITE);
  367. xml.Save(spriteSheetFile);
  368. }