public bool Insert(ImagePacker.ImagePackRect insert, int padding) { int insertWidth = insert.rect.width + padding * 2; int insertHeight = insert.rect.height + padding * 2; if (insertWidth > rect.width || insertHeight > rect.height) { return(false); } if (imageId == -1) { imageId = insert.index; imageWidth = new Vector2Int(insertWidth, insertHeight); } else { if (left == null && !SplitRects(this, insert, padding, out left, out right)) { return(false); } // We assign to the node that has a better fit for the image Vector2Int spaceLeft, spaceRight; bool insertLeft, insertRight; insertLeft = left.TryInsert(insert, padding, out spaceLeft); insertRight = right.TryInsert(insert, padding, out spaceRight); if (insertLeft && insertRight) { if (spaceLeft.sqrMagnitude < spaceRight.sqrMagnitude) { left.Insert(insert, padding); } else { right.Insert(insert, padding); } } else if (insertLeft) { left.Insert(insert, padding); } else if (insertRight) { right.Insert(insert, padding); } else { return(false); } } return(true); }
static ImagePackNode InternalPack(RectInt[] rects, int padding) { if (rects == null || rects.Length == 0) { return new ImagePackNode() { rect = new RectInt(0, 0, 0, 0) } } ; var sortedRects = new ImagePackRect[rects.Length]; for (int i = 0; i < rects.Length; ++i) { sortedRects[i] = new ImagePackRect(); sortedRects[i].rect = rects[i]; sortedRects[i].index = i; } Array.Sort <ImagePackRect>(sortedRects); var root = new ImagePackNode(); root.rect = new RectInt(0, 0, (int)NextPowerOfTwo((ulong)rects[0].width), (int)NextPowerOfTwo((ulong)rects[0].height)); for (int i = 0; i < rects.Length; ++i) { if (!root.Insert(sortedRects[i], padding)) // we can't fit { int newWidth = root.rect.width, newHeight = root.rect.height; if (root.rect.width < root.rect.height) { newWidth = (int)NextPowerOfTwo((ulong)root.rect.width + 1); } else { newHeight = (int)NextPowerOfTwo((ulong)root.rect.height + 1); } // Reset all packing and try again root = new ImagePackNode(); root.rect = new RectInt(0, 0, newWidth, newHeight); i = -1; } } return(root); }