SpritePacker.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. //
  2. // Copyright (c) 2008-2017 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/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. frameWidth(0),
  67. frameHeight(0),
  68. frameX(0),
  69. frameY(0)
  70. {
  71. }
  72. ~PackerInfo() override {}
  73. };
  74. void Help()
  75. {
  76. ErrorExit("Usage: SpritePacker -options <input file> <input file> <output png file>\n"
  77. "\n"
  78. "Options:\n"
  79. "-h Shows this help message.\n"
  80. "-px Adds x pixels of padding per image to width.\n"
  81. "-py Adds y pixels of padding per image to height.\n"
  82. "-ox Adds x pixels to the horizontal position per image.\n"
  83. "-oy Adds y pixels to the horizontal position per image.\n"
  84. "-frameHeight Sets a fixed height for image and centers within frame.\n"
  85. "-frameWidth Sets a fixed width for image and centers within frame.\n"
  86. "-trim Trims excess transparent space from individual images offsets by frame size.\n"
  87. "-xml \'path\' Generates an SpriteSheet xml file at path.\n"
  88. "-debug Draws allocation boxes on sprite.\n");
  89. }
  90. int main(int argc, char** argv)
  91. {
  92. Vector<String> arguments;
  93. #ifdef WIN32
  94. arguments = ParseArguments(GetCommandLineW());
  95. #else
  96. arguments = ParseArguments(argc, argv);
  97. #endif
  98. Run(arguments);
  99. return 0;
  100. }
  101. void Run(Vector<String>& arguments)
  102. {
  103. if (arguments.Size() < 2)
  104. Help();
  105. SharedPtr<Context> context(new Context());
  106. context->RegisterSubsystem(new FileSystem(context));
  107. context->RegisterSubsystem(new Log(context));
  108. FileSystem* fileSystem = context->GetSubsystem<FileSystem>();
  109. Vector<String> inputFiles;
  110. String outputFile;
  111. String spriteSheetFileName;
  112. bool debug = false;
  113. unsigned padX = 0;
  114. unsigned padY = 0;
  115. unsigned offsetX = 0;
  116. unsigned offsetY = 0;
  117. unsigned frameWidth = 0;
  118. unsigned frameHeight = 0;
  119. bool help = false;
  120. bool trim = false;
  121. while (arguments.Size() > 0)
  122. {
  123. String arg = arguments[0];
  124. arguments.Erase(0);
  125. if (arg.Empty())
  126. continue;
  127. if (arg.StartsWith("-"))
  128. {
  129. if (arg == "-px") { padX = ToUInt(arguments[0]); arguments.Erase(0); }
  130. else if (arg == "-py") { padY = ToUInt(arguments[0]); arguments.Erase(0); }
  131. else if (arg == "-ox") { offsetX = ToUInt(arguments[0]); arguments.Erase(0); }
  132. else if (arg == "-oy") { offsetY = ToUInt(arguments[0]); arguments.Erase(0); }
  133. else if (arg == "-frameWidth") { frameWidth = ToUInt(arguments[0]); arguments.Erase(0); }
  134. else if (arg == "-frameHeight") { frameHeight = ToUInt(arguments[0]); arguments.Erase(0); }
  135. else if (arg == "-trim") { trim = true; }
  136. else if (arg == "-xml") { spriteSheetFileName = arguments[0]; arguments.Erase(0); }
  137. else if (arg == "-h") { help = true; break; }
  138. else if (arg == "-debug") { debug = true; }
  139. }
  140. else
  141. inputFiles.Push(arg);
  142. }
  143. if (help)
  144. Help();
  145. if (inputFiles.Size() < 2)
  146. ErrorExit("An input and output file must be specified.");
  147. if (frameWidth ^ frameHeight)
  148. ErrorExit("Both frameHeight and frameWidth must be omitted or specified.");
  149. // take last input file as output
  150. if (inputFiles.Size() > 1)
  151. {
  152. outputFile = inputFiles[inputFiles.Size() - 1];
  153. URHO3D_LOGINFO("Output file set to " + outputFile + ".");
  154. inputFiles.Erase(inputFiles.Size() - 1);
  155. }
  156. // set spritesheet name to outputfile.xml if not specified
  157. if (spriteSheetFileName.Empty())
  158. spriteSheetFileName = ReplaceExtension(outputFile, ".xml");
  159. if (GetParentPath(spriteSheetFileName) != GetParentPath(outputFile))
  160. ErrorExit("Both output xml and png must be in the same folder");
  161. // check all input files exist
  162. for (unsigned i = 0; i < inputFiles.Size(); ++i)
  163. {
  164. URHO3D_LOGINFO("Checking " + inputFiles[i] + " to see if file exists.");
  165. if (!fileSystem->FileExists(inputFiles[i]))
  166. ErrorExit("File " + inputFiles[i] + " does not exist.");
  167. }
  168. // Set the max offset equal to padding to prevent images from going out of bounds
  169. offsetX = Min((int)offsetX, (int)padX);
  170. offsetY = Min((int)offsetY, (int)padY);
  171. Vector<SharedPtr<PackerInfo > > packerInfos;
  172. for (unsigned i = 0; i < inputFiles.Size(); ++i)
  173. {
  174. String path = inputFiles[i];
  175. String name = ReplaceExtension(GetFileName(path), "");
  176. File file(context, path);
  177. Image image(context);
  178. if (!image.Load(file))
  179. ErrorExit("Could not load image " + path + ".");
  180. if (image.IsCompressed())
  181. ErrorExit(path + " is compressed. Compressed images are not allowed.");
  182. SharedPtr<PackerInfo> packerInfo(new PackerInfo(path, name));
  183. int imageWidth = image.GetWidth();
  184. int imageHeight = image.GetHeight();
  185. int trimOffsetX = 0;
  186. int trimOffsetY = 0;
  187. int adjustedWidth = imageWidth;
  188. int adjustedHeight = imageHeight;
  189. if (trim)
  190. {
  191. int minX = imageWidth;
  192. int minY = imageHeight;
  193. int maxX = 0;
  194. int maxY = 0;
  195. for (int y = 0; y < imageHeight; ++y)
  196. {
  197. for (int x = 0; x < imageWidth; ++x)
  198. {
  199. bool found = (image.GetPixelInt(x, y) & 0x000000ff) != 0;
  200. if (found) {
  201. minX = Min(minX, x);
  202. minY = Min(minY, y);
  203. maxX = Max(maxX, x);
  204. maxY = Max(maxY, y);
  205. }
  206. }
  207. }
  208. trimOffsetX = minX;
  209. trimOffsetY = minY;
  210. adjustedWidth = maxX - minX + 1;
  211. adjustedHeight = maxY - minY + 1;
  212. }
  213. if (trim)
  214. {
  215. packerInfo->frameWidth = imageWidth;
  216. packerInfo->frameHeight = imageHeight;
  217. }
  218. else if (frameWidth || frameHeight)
  219. {
  220. packerInfo->frameWidth = frameWidth;
  221. packerInfo->frameHeight = frameHeight;
  222. }
  223. packerInfo->width = adjustedWidth;
  224. packerInfo->height = adjustedHeight;
  225. packerInfo->offsetX -= trimOffsetX;
  226. packerInfo->offsetY -= trimOffsetY;
  227. packerInfos.Push(packerInfo);
  228. }
  229. int packedWidth = MAX_TEXTURE_SIZE;
  230. int packedHeight = MAX_TEXTURE_SIZE;
  231. {
  232. // fill up an list of tries in increasing size and take the first win
  233. Vector<IntVector2> tries;
  234. for(unsigned x=2; x<11; ++x)
  235. {
  236. for(unsigned y=2; y<11; ++y)
  237. tries.Push(IntVector2((1<<x), (1<<y)));
  238. }
  239. // load rectangles
  240. stbrp_rect* packerRects = new stbrp_rect[packerInfos.Size()];
  241. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  242. {
  243. PackerInfo* packerInfo = packerInfos[i];
  244. stbrp_rect* packerRect = &packerRects[i];
  245. packerRect->id = i;
  246. packerRect->h = packerInfo->height + padY;
  247. packerRect->w = packerInfo->width + padX;
  248. }
  249. bool success = false;
  250. while (tries.Size() > 0)
  251. {
  252. IntVector2 size = tries[0];
  253. tries.Erase(0);
  254. bool fit = true;
  255. int textureHeight = size.y_;
  256. int textureWidth = size.x_;
  257. if (success && textureHeight * textureWidth > packedWidth * packedHeight)
  258. continue;
  259. stbrp_context packerContext;
  260. stbrp_node packerMemory[PACKER_NUM_NODES];
  261. stbrp_init_target(&packerContext, textureWidth, textureHeight, packerMemory, packerInfos.Size());
  262. stbrp_pack_rects(&packerContext, packerRects, packerInfos.Size());
  263. // check to see if everything fit
  264. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  265. {
  266. stbrp_rect* packerRect = &packerRects[i];
  267. if (!packerRect->was_packed)
  268. {
  269. fit = false;
  270. break;
  271. }
  272. }
  273. if (fit)
  274. {
  275. success = true;
  276. // distribute values to packer info
  277. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  278. {
  279. stbrp_rect* packerRect = &packerRects[i];
  280. PackerInfo* packerInfo = packerInfos[packerRect->id];
  281. packerInfo->x = packerRect->x;
  282. packerInfo->y = packerRect->y;
  283. }
  284. packedWidth = size.x_;
  285. packedHeight = size.y_;
  286. }
  287. }
  288. delete[] packerRects;
  289. if (!success)
  290. ErrorExit("Could not allocate for all images. The max sprite sheet texture size is " + String(MAX_TEXTURE_SIZE) + "x" + String(MAX_TEXTURE_SIZE) + ".");
  291. }
  292. // create image for spritesheet
  293. Image spriteSheetImage(context);
  294. spriteSheetImage.SetSize(packedWidth, packedHeight, 4);
  295. // zero out image
  296. spriteSheetImage.SetData((unsigned char*)calloc(sizeof(unsigned char), packedWidth * packedHeight * 4));
  297. XMLFile xml(context);
  298. XMLElement root = xml.CreateRoot("TextureAtlas");
  299. root.SetAttribute("imagePath", GetFileNameAndExtension(outputFile));
  300. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  301. {
  302. SharedPtr<PackerInfo> packerInfo = packerInfos[i];
  303. XMLElement subTexture = root.CreateChild("SubTexture");
  304. subTexture.SetString("name", packerInfo->name);
  305. subTexture.SetInt("x", packerInfo->x + offsetX);
  306. subTexture.SetInt("y", packerInfo->y + offsetY);
  307. subTexture.SetInt("width", packerInfo->width);
  308. subTexture.SetInt("height", packerInfo->height);
  309. if (packerInfo->frameWidth || packerInfo->frameHeight)
  310. {
  311. subTexture.SetInt("frameWidth", packerInfo->frameWidth);
  312. subTexture.SetInt("frameHeight", packerInfo->frameHeight);
  313. subTexture.SetInt("offsetX", packerInfo->offsetX);
  314. subTexture.SetInt("offsetY", packerInfo->offsetY);
  315. }
  316. URHO3D_LOGINFO("Transferring " + packerInfo->path + " to sprite sheet.");
  317. File file(context, packerInfo->path);
  318. Image image(context);
  319. if (!image.Load(file))
  320. ErrorExit("Could not load image " + packerInfo->path + ".");
  321. for (int y = 0; y < packerInfo->height; ++y)
  322. {
  323. for (int x = 0; x < packerInfo->width; ++x)
  324. {
  325. unsigned color = image.GetPixelInt(x - packerInfo->offsetX, y - packerInfo->offsetY);
  326. spriteSheetImage.SetPixelInt(
  327. packerInfo->x + offsetX + x,
  328. packerInfo->y + offsetY + y, color);
  329. }
  330. }
  331. }
  332. if (debug)
  333. {
  334. unsigned OUTER_BOUNDS_DEBUG_COLOR = Color::BLUE.ToUInt();
  335. unsigned INNER_BOUNDS_DEBUG_COLOR = Color::GREEN.ToUInt();
  336. URHO3D_LOGINFO("Drawing debug information.");
  337. for (unsigned i = 0; i < packerInfos.Size(); ++i)
  338. {
  339. SharedPtr<PackerInfo> packerInfo = packerInfos[i];
  340. // Draw outer bounds
  341. for (int x = 0; x < packerInfo->frameWidth; ++x)
  342. {
  343. spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y, OUTER_BOUNDS_DEBUG_COLOR);
  344. spriteSheetImage.SetPixelInt(packerInfo->x + x, packerInfo->y + packerInfo->frameHeight, OUTER_BOUNDS_DEBUG_COLOR);
  345. }
  346. for (int y = 0; y < packerInfo->frameHeight; ++y)
  347. {
  348. spriteSheetImage.SetPixelInt(packerInfo->x, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR);
  349. spriteSheetImage.SetPixelInt(packerInfo->x + packerInfo->frameWidth, packerInfo->y + y, OUTER_BOUNDS_DEBUG_COLOR);
  350. }
  351. // Draw inner bounds
  352. for (int x = 0; x < packerInfo->width; ++x)
  353. {
  354. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY, INNER_BOUNDS_DEBUG_COLOR);
  355. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + x, packerInfo->y + offsetY + packerInfo->height, INNER_BOUNDS_DEBUG_COLOR);
  356. }
  357. for (int y = 0; y < packerInfo->height; ++y)
  358. {
  359. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR);
  360. spriteSheetImage.SetPixelInt(packerInfo->x + offsetX + packerInfo->width, packerInfo->y + offsetY + y, INNER_BOUNDS_DEBUG_COLOR);
  361. }
  362. }
  363. }
  364. URHO3D_LOGINFO("Saving output image.");
  365. spriteSheetImage.SavePNG(outputFile);
  366. URHO3D_LOGINFO("Saving SpriteSheet xml file.");
  367. File spriteSheetFile(context);
  368. spriteSheetFile.Open(spriteSheetFileName, FILE_WRITE);
  369. xml.Save(spriteSheetFile);
  370. }