Initial Implementation (#1)

pull/2/head
cosmonaut 2022-07-23 00:00:02 +00:00
parent 534f61cbb0
commit b72fc71082
10 changed files with 14042 additions and 655 deletions

View File

@ -1,8 +1,8 @@
cmake_minimum_required(VERSION 2.8.12) cmake_minimum_required(VERSION 2.8.12)
project(Cram C) project(Cram C)
option(BUILD_CLI "Build command line executable" ON)
option(BUILD_SHARED_LIBS "Build shared library" ON) option(BUILD_SHARED_LIBS "Build shared library" ON)
option(USE_SDL2 "Use SDL2" ON)
SET(LIB_MAJOR_VERSION "0") SET(LIB_MAJOR_VERSION "0")
SET(LIB_MINOR_VERSION "3") SET(LIB_MINOR_VERSION "3")
@ -38,18 +38,45 @@ if(UNIX)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE) set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
endif() endif()
if(USE_SDL2) if (WIN32)
add_definitions(-DUSE_SDL2) add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif() endif()
add_library(Cram file(GLOB SOURCE_FILES
#Public header #Public header
include/cram.h include/cram.h
#Source #Source
lib/stb_rect_pack.h lib/stb_image.h
lib/stb_ds.h
src/cram.c src/cram.c
) )
set(LINKSTYLE PRIVATE)
if(BUILD_SHARED_LIBS)
set(LINKSTYLE PUBLIC)
endif()
if(BUILD_CLI)
add_executable(cramcli
tools/cli/lib/dirent.h
tools/cli/lib/stb_image_write.h
tools/cli/json_writer.h
tools/cli/main.c
)
if(BUILD_SHARED_LIBS)
target_link_libraries(cramcli PUBLIC Cram)
else()
target_link_libraries(cramcli PRIVATE Cram)
endif()
endif()
if(BUILD_SHARED_LIBS)
add_library(Cram SHARED ${SOURCE_FILES})
else()
add_library(Cram STATIC ${SOURCE_FILES})
endif()
# Build flags # Build flags
if(NOT MSVC) if(NOT MSVC)
set_property(TARGET Cram PROPERTY COMPILE_FLAGS "-std=gnu99 -Wall -Wno-strict-aliasing -pedantic") set_property(TARGET Cram PROPERTY COMPILE_FLAGS "-std=gnu99 -Wall -Wno-strict-aliasing -pedantic")
@ -60,6 +87,7 @@ target_include_directories(Cram PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/lib> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/lib>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/tools/cli/lib>
) )
# Soname # Soname
@ -67,26 +95,3 @@ set_target_properties(Cram PROPERTIES OUTPUT_NAME "Cram"
VERSION ${LIB_VERSION} VERSION ${LIB_VERSION}
SOVERSION ${LIB_MAJOR_VERSION} SOVERSION ${LIB_MAJOR_VERSION}
) )
# SDL2 Dependency
if(USE_SDL2)
if (DEFINED SDL2_INCLUDE_DIRS AND DEFINED SDL2_LIBRARIES)
message(STATUS "using pre-defined SDL2 variables SDL2_INCLUDE_DIRS and SDL2_LIBRARIES")
target_include_directories(Cram PUBLIC "$<BUILD_INTERFACE:${SDL2_INCLUDE_DIRS}>")
target_link_libraries(Cram PUBLIC ${SDL2_LIBRARIES})
else()
# Only try to autodetect if both SDL2 variables aren't explicitly set
find_package(SDL2 CONFIG)
if (TARGET SDL2::SDL2)
message(STATUS "using TARGET SDL2::SDL2")
target_link_libraries(Cram PUBLIC SDL2::SDL2)
elseif (TARGET SDL2)
message(STATUS "using TARGET SDL2")
target_link_libraries(Cram PUBLIC SDL2)
else()
message(STATUS "no TARGET SDL2::SDL2, or SDL2, using variables")
target_include_directories(Cram PUBLIC "$<BUILD_INTERFACE:${SDL2_INCLUDE_DIRS}>")
target_link_libraries(Cram PUBLIC ${SDL2_LIBRARIES})
endif()
endif()
endif()

View File

@ -1,4 +1,4 @@
/* Cram - A texture atlas system in C /* Cram - A texture packing system in C
* *
* Copyright (c) 2022 Evan Hemsley * Copyright (c) 2022 Evan Hemsley
* *
@ -35,8 +35,36 @@
#define CRAMCALL #define CRAMCALL
#endif #endif
#ifdef USE_SDL2 #include <stdint.h>
#include <SDL.h>
#ifdef _MSC_VER
#include <assert.h>
#include <stdlib.h>
#include <search.h>
#include <string.h>
#endif /* _MSC_VER */
/* TODO: ifndefs here? */
#define Cram_assert assert
#define Cram_qsort qsort
#define Cram_malloc malloc
#define Cram_realloc realloc
#define Cram_free free
#define Cram_memcpy memcpy
#define Cram_memset memset
#define Cram_strdup strdup
#define Cram_abs abs
#define Cram_min min
#define Cram_max max
#ifdef _WIN32
#define SEPARATOR '\\'
#endif
#ifdef __unix__
#define SEPARATOR '/'
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
@ -48,7 +76,7 @@ extern "C"
#define CRAM_MINOR_VERSION 1 #define CRAM_MINOR_VERSION 1
#define CRAM_PATCH_VERSION 0 #define CRAM_PATCH_VERSION 0
#define WELLSPRING_COMPILED_VERSION ( \ #define CRAM_COMPILED_VERSION ( \
(CRAM_MAJOR_VERSION * 100 * 100) + \ (CRAM_MAJOR_VERSION * 100 * 100) + \
(CRAM_MINOR_VERSION * 100) + \ (CRAM_MINOR_VERSION * 100) + \
(CRAM_PATCH_VERSION) \ (CRAM_PATCH_VERSION) \
@ -56,6 +84,46 @@ extern "C"
CRAMAPI uint32_t Cram_LinkedVersion(void); CRAMAPI uint32_t Cram_LinkedVersion(void);
/* Type definitions */
typedef struct Cram_Context Cram_Context;
typedef struct Cram_ContextCreateInfo
{
const char *name;
uint32_t maxDimension;
int32_t padding;
uint8_t trim;
} Cram_ContextCreateInfo;
typedef struct Cram_ImageData
{
char *name;
int32_t x;
int32_t y;
int32_t width;
int32_t height;
int32_t trimOffsetX;
int32_t trimOffsetY;
int32_t untrimmedWidth;
int32_t untrimmedHeight;
} Cram_ImageData;
/* API definition */
CRAMAPI Cram_Context* Cram_Init(Cram_ContextCreateInfo *createInfo);
CRAMAPI void Cram_AddFile(Cram_Context *context, const char *path);
CRAMAPI int8_t Cram_Pack(Cram_Context *context);
CRAMAPI void Cram_GetPixelData(Cram_Context *context, uint8_t **pPixelData, uint32_t *pWidth, uint32_t *pHeight);
CRAMAPI void Cram_GetMetadata(Cram_Context *context, Cram_ImageData **pImage, uint32_t *pImageCount);
CRAMAPI void Cram_Destroy(Cram_Context *context);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif /* __cplusplus */ #endif /* __cplusplus */

1895
lib/stb_ds.h Normal file

File diff suppressed because it is too large Load Diff

7897
lib/stb_image.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,623 +0,0 @@
// stb_rect_pack.h - v1.01 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Before #including,
//
// #define STB_RECT_PACK_IMPLEMENTATION
//
// in the file that you want to have the implementation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
typedef int stbrp_coord;
#define STBRP__MAXVAL 0x7fffffff
// Mostly for internal use, but this is the maximum supported coordinate value.
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
context->extra[1].y = (1<<30);
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
// if it can't possibly fit, bail immediately
if (width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height <= c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
STBRP_ASSERT(y <= best_y);
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
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.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
*/

View File

@ -0,0 +1,805 @@
/* Cram - A texture packing system in C
*
* Copyright (c) 2022 Evan Hemsley
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in a
* product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* Evan "cosmonaut" Hemsley <evan@moonside.games>
*
*/
#include "cram.h"
#define STBI_ASSERT Cram_assert
#define STBI_MALLOC Cram_malloc
#define STBI_REALLOC Cram_realloc
#define STBI_FREE Cram_free
#define STBI_ONLY_PNG
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_DS_IMPLEMENTATION
#include "stb_ds.h"
#define INITIAL_DATA_CAPACITY 8
#define INITIAL_FREE_RECTANGLE_CAPACITY 16
#define STBDS_SIZE_T_BITS ((sizeof (size_t)) * 8)
#define STBDS_ROTATE_LEFT(val, n) (((val) << (n)) | ((val) >> (STBDS_SIZE_T_BITS - (n))))
#define STBDS_ROTATE_RIGHT(val, n) (((val) >> (n)) | ((val) << (STBDS_SIZE_T_BITS - (n))))
/* Structures */
typedef struct Rect
{
int32_t x, y;
int32_t w, h;
} Rect;
typedef struct Cram_Image Cram_Image;
struct Cram_Image
{
char *name;
Rect originalRect;
Rect trimmedRect;
Rect packedRect;
Cram_Image *duplicateOf;
uint8_t *pixels; /* Will be NULL if duplicateOf is not NULL! */
size_t hash;
};
typedef struct Cram_Internal_Context
{
const char *name;
uint32_t width;
uint32_t height;
int32_t padding;
uint8_t trim;
uint8_t *pixels;
Cram_Image **images;
uint32_t imageCount;
uint32_t imageCapacity;
Cram_ImageData *imageDatas;
uint32_t imageDataCount;
} Cram_Internal_Context;
typedef struct RectPackContext
{
uint32_t width;
uint32_t height;
Rect *freeRectangles;
int32_t freeRectangleCount;
int32_t freeRectangleCapacity;
Rect *newFreeRectangles;
int32_t newFreeRectangleCount;
int32_t newFreeRectangleCapacity;
} RectPackContext;
typedef struct PackScoreInfo
{
int32_t score;
int32_t secondaryScore;
int32_t x;
int32_t y;
} PackScoreInfo;
/* Pixel data functions */
/* https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */
static uint32_t Cram_Internal_NextPowerOfTwo(uint32_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
static uint8_t Cram_Internal_IsImageEqual(Cram_Image *a, Cram_Image *b)
{
int32_t i;
if (a->hash == b->hash && a->trimmedRect.w == b->trimmedRect.w && a->trimmedRect.h == b->trimmedRect.h)
{
for (i = 0; i < a->trimmedRect.w * a->trimmedRect.h * 4; i += 1)
{
if (a->pixels[i] != b->pixels[i])
{
return 0;
}
}
return 1;
}
return 0;
}
static inline uint32_t Cram_Internal_GetPixelIndex(uint32_t x, uint32_t y, uint32_t width)
{
return x + y * width;
}
static uint8_t Cram_Internal_IsRowClear(uint32_t* pixels, uint32_t rowIndex, uint32_t width)
{
int32_t i;
for (i = 0; i < width; i += 1)
{
if ((pixels[Cram_Internal_GetPixelIndex(i, rowIndex, width)] & 0xFF) > 0)
{
return 0;
}
}
return 1;
}
static uint8_t Cram_Internal_IsColumnClear(uint32_t* pixels, uint32_t columnIndex, uint32_t width, uint32_t height)
{
int32_t i;
for (i = 0; i < height; i += 1)
{
if ((pixels[Cram_Internal_GetPixelIndex(columnIndex, i, width)] & 0xFF) > 0)
{
return 0;
}
}
return 1;
}
/* width and height of source and destination rects must be the same! */
static int8_t Cram_Internal_CopyPixels(
uint32_t *dstPixels,
uint32_t dstPixelWidth,
uint32_t *srcPixels,
uint32_t srcPixelWidth,
Rect *dstRect,
Rect *srcRect
) {
int32_t i, j;
int32_t dstPixelIndex, srcPixelIndex;
if (dstRect->w != srcRect->w || dstRect->h != srcRect->h)
{
return -1;
}
for (i = 0; i < dstRect->w; i += 1)
{
for (j = 0; j < dstRect->h; j += 1)
{
dstPixelIndex = Cram_Internal_GetPixelIndex(i + dstRect->x, j + dstRect->y, dstPixelWidth);
srcPixelIndex = Cram_Internal_GetPixelIndex(i + srcRect->x, j + srcRect->y, srcPixelWidth);
dstPixels[dstPixelIndex] = srcPixels[srcPixelIndex];
}
}
return 0;
}
/* Packing functions */
RectPackContext* Cram_Internal_InitRectPacker(uint32_t width, uint32_t height)
{
RectPackContext *context = Cram_malloc(sizeof(RectPackContext));
context->width = width;
context->height = height;
context->freeRectangleCapacity = INITIAL_FREE_RECTANGLE_CAPACITY;
context->freeRectangles = Cram_malloc(sizeof(Rect) * context->freeRectangleCapacity);
context->freeRectangles[0].x = 0;
context->freeRectangles[0].y = 0;
context->freeRectangles[0].w = width;
context->freeRectangles[0].h = height;
context->freeRectangleCount = 1;
context->newFreeRectangleCapacity = INITIAL_FREE_RECTANGLE_CAPACITY;
context->newFreeRectangles = Cram_malloc(sizeof(Rect) * context->freeRectangleCapacity);
context->newFreeRectangleCount = 0;
return context;
}
/* Uses the best area fit heuristic. */
/* TODO: make the heuristic configurable? */
void Cram_Internal_Score(
RectPackContext *context,
int32_t width,
int32_t height,
PackScoreInfo *scoreInfo
) {
Rect *freeRect;
int32_t areaFit;
int32_t shortestSide;
int32_t i;
scoreInfo->score = INT32_MAX;
scoreInfo->secondaryScore = INT32_MAX;
for (i = 0; i < context->freeRectangleCount; i += 1)
{
freeRect = &context->freeRectangles[i];
if (freeRect->w >= width && freeRect->h >= height)
{
areaFit = freeRect->w * freeRect->h - width * height;
shortestSide = Cram_min(freeRect->w - width, freeRect->h - height);
if (areaFit < scoreInfo->score || (areaFit == scoreInfo->score && shortestSide < scoreInfo->secondaryScore))
{
scoreInfo->score = areaFit;
scoreInfo->secondaryScore = shortestSide;
scoreInfo->x = freeRect->x;
scoreInfo->y = freeRect->y;
}
}
}
}
/* Check if a contains b */
static inline uint8_t Cram_Internal_Contains(Rect* a, Rect* b)
{
return b->x >= a->x &&
b->y >= a->y &&
b->x + b->w <= a->x + a->w &&
b->y + b->h <= a->y + a->h;
}
void Cram_Internal_PruneRects(RectPackContext* context)
{
int32_t i, j;
for (i = 0; i < context->freeRectangleCount; i += 1)
{
for (j = context->newFreeRectangleCount - 1; j >= 0; j -= 1)
{
if (Cram_Internal_Contains(&context->freeRectangles[i], &context->newFreeRectangles[j]))
{
/* plug the hole */
context->newFreeRectangles[j] = context->newFreeRectangles[context->newFreeRectangleCount - 1];
context->newFreeRectangleCount -= 1;
}
}
}
if (context->freeRectangleCapacity < context->freeRectangleCount + context->newFreeRectangleCount)
{
context->freeRectangleCapacity = Cram_max(context->freeRectangleCapacity * 2, context->freeRectangleCount + context->newFreeRectangleCount);
context->freeRectangles = Cram_realloc(context->freeRectangles, sizeof(Rect) * context->freeRectangleCapacity);
}
for (i = 0; i < context->newFreeRectangleCount; i += 1)
{
context->freeRectangles[context->freeRectangleCount] = context->newFreeRectangles[i];
context->freeRectangleCount += 1;
}
context->newFreeRectangleCount = 0;
}
static inline void Cram_Internal_AddNewFreeRect(RectPackContext *context, Rect rect)
{
int32_t i;
for (i = context->newFreeRectangleCount - 1; i >= 0; i -= 1)
{
if (Cram_Internal_Contains(&context->newFreeRectangles[i], &rect))
{
return;
}
if (Cram_Internal_Contains(&rect, &context->newFreeRectangles[i]))
{
context->newFreeRectangles[i] = context->newFreeRectangles[context->newFreeRectangleCount - 1];
context->newFreeRectangleCount -= 1;
}
}
if (context->newFreeRectangleCount == context->newFreeRectangleCapacity)
{
context->newFreeRectangleCapacity *= 2;
context->newFreeRectangles = Cram_realloc(context->newFreeRectangles, sizeof(Rect) * context->newFreeRectangleCapacity);
}
context->newFreeRectangles[context->newFreeRectangleCount] = rect;
context->newFreeRectangleCount += 1;
}
uint8_t Cram_Internal_SplitRect(RectPackContext *context, Rect *rect, Rect *freeRect)
{
Rect newRect;
/* Test intersection */
if ( rect->x >= freeRect->x + freeRect->w ||
rect->y >= freeRect->y + freeRect->h ||
rect->x + rect->w <= freeRect->x ||
rect->y + rect->h <= freeRect->y )
{
return 0;
}
/* now we have new free rectangles! */
/* NOTE: free rectangles can overlap. */
if (rect->y < freeRect->y + freeRect->h && rect->y + rect->h > freeRect->y)
{
/* Left side */
if (rect->x > freeRect->x && rect->x < freeRect->x + freeRect->w)
{
newRect = *freeRect;
newRect.w = rect->x - freeRect->x;
Cram_Internal_AddNewFreeRect(context, newRect);
}
/* Right side */
if (rect->x + rect->w < freeRect->x + freeRect->w)
{
newRect = *freeRect;
newRect.x = rect->x + rect->w;
newRect.w = freeRect->x + freeRect->w - (rect->x + rect->w);
Cram_Internal_AddNewFreeRect(context, newRect);
}
}
if (rect->x < freeRect->x + freeRect->w && rect->x + rect->w > freeRect->x)
{
/* Top side */
if (rect->y > freeRect->y && rect->y < freeRect->y + freeRect->h)
{
newRect = *freeRect;
newRect.h = rect->y - freeRect->y;
Cram_Internal_AddNewFreeRect(context, newRect);
}
/* Bottom side */
if (rect->y + rect->h < freeRect->y + freeRect->h)
{
newRect = *freeRect;
newRect.y = rect->y + rect->h;
newRect.h = freeRect->y + freeRect->h - (rect->y + rect->h);
Cram_Internal_AddNewFreeRect(context, newRect);
}
}
return 1;
}
void Cram_Internal_PlaceRect(RectPackContext *context, Rect *rect)
{
Rect *freeRect;
int32_t i;
for (i = context->freeRectangleCount - 1; i >= 0; i -= 1)
{
freeRect = &context->freeRectangles[i];
if (Cram_Internal_SplitRect(context, rect, freeRect))
{
/* plug the hole */
context->freeRectangles[i] = context->freeRectangles[context->freeRectangleCount - 1];
context->freeRectangleCount -= 1;
}
}
Cram_Internal_PruneRects(context);
}
/* Given rects with width and height, modifies rects with packed x and y positions. */
int8_t Cram_Internal_PackRects(RectPackContext *context, Rect *rects, uint32_t numRects)
{
Rect **rectsToPack = Cram_malloc(sizeof(Rect*) * numRects);
int32_t rectsToPackCount = numRects;
Rect *rectPtr;
int32_t bestScore = INT32_MAX;
int32_t bestSecondaryScore = INT32_MAX;
PackScoreInfo scoreInfo;
int32_t bestRectIndex, bestX, bestY;
int32_t i, repeat;
for (i = 0; i < numRects; i += 1)
{
rectsToPack[i] = &rects[i];
}
for (repeat = 0; repeat < numRects; repeat += 1)
{
bestScore = INT32_MAX;
for (i = 0; i < rectsToPackCount; i += 1)
{
rectPtr = rectsToPack[i];
Cram_Internal_Score(context, rectPtr->w, rectPtr->h, &scoreInfo);
if (scoreInfo.score < bestScore || (scoreInfo.score == bestScore && scoreInfo.secondaryScore < bestSecondaryScore))
{
bestScore = scoreInfo.score;
bestSecondaryScore = scoreInfo.secondaryScore;
bestRectIndex = i;
bestX = scoreInfo.x;
bestY = scoreInfo.y;
}
}
if (bestScore == INT32_MAX)
{
/* doesn't fit! abort! */
return -1;
}
rectPtr = rectsToPack[bestRectIndex];
rectPtr->x = bestX;
rectPtr->y = bestY;
Cram_Internal_PlaceRect(context, rectPtr);
/* plug the hole */
rectsToPack[bestRectIndex] = rectsToPack[rectsToPackCount - 1];
rectsToPackCount -= 1;
}
Cram_free(rectsToPack);
return 0;
}
/* API functions */
uint32_t Cram_LinkedVersion(void)
{
return CRAM_COMPILED_VERSION;
}
Cram_Context* Cram_Init(Cram_ContextCreateInfo *createInfo)
{
Cram_Internal_Context *context = Cram_malloc(sizeof(Cram_Internal_Context));
context->name = Cram_strdup(createInfo->name);
context->width = createInfo->maxDimension;
context->height = createInfo->maxDimension;
context->padding = createInfo->padding;
context->trim = createInfo->trim;
context->images = Cram_malloc(INITIAL_DATA_CAPACITY * sizeof(Cram_Image*));
context->imageCapacity = INITIAL_DATA_CAPACITY;
context->imageCount = 0;
context->pixels = NULL;
context->imageDatas = NULL;
context->imageDataCount = 0;
return (Cram_Context*) context;
}
static char* Cram_Internal_GetImageName(const char *path)
{
char *lastSeparator = strrchr(path, SEPARATOR) + 1;
size_t returnBytes = strlen(lastSeparator) + 1;
char *name = Cram_malloc(returnBytes);
int32_t i;
for (i = 0; i < returnBytes; i += 1)
{
name[i] = lastSeparator[i];
}
return name;
}
void Cram_AddFile(Cram_Context *context, const char *path)
{
Cram_Internal_Context *internalContext = (Cram_Internal_Context*) context;
Cram_Image *image;
uint8_t *pixels;
int32_t leftTrim, topTrim, rightTrim, bottomTrim;
int32_t width, height, numChannels;
int32_t i;
if (internalContext->imageCapacity == internalContext->imageCount)
{
internalContext->imageCapacity *= 2;
internalContext->images = Cram_realloc(internalContext->images, internalContext->imageCapacity * sizeof(Cram_Image*));
}
image = Cram_malloc(sizeof(Cram_Image));
image->name = Cram_Internal_GetImageName(path);
pixels = stbi_load(
path,
&width,
&height,
&numChannels,
STBI_rgb_alpha
);
image->originalRect.x = 0;
image->originalRect.y = 0;
image->originalRect.w = width;
image->originalRect.h = height;
/* Check for trim */
if (internalContext->trim)
{
topTrim = 0;
for (i = 0; i < height; i += 1)
{
if (!Cram_Internal_IsRowClear((uint32_t*) pixels, i, width))
{
topTrim = i;
break;
}
}
leftTrim = 0;
for (i = 0; i < width; i += 1)
{
if (!Cram_Internal_IsColumnClear((uint32_t*) pixels, i, width, height))
{
leftTrim = i;
break;
}
}
bottomTrim = height;
for (i = height - 1; i >= topTrim; i -= 1)
{
if (!Cram_Internal_IsRowClear((uint32_t*) pixels, i, width))
{
bottomTrim = i + 1;
break;
}
}
rightTrim = width;
for (i = width - 1; i >= leftTrim; i -= 1)
{
if (!Cram_Internal_IsColumnClear((uint32_t*) pixels, i, width, height))
{
rightTrim = i + 1;
break;
}
}
image->trimmedRect.x = leftTrim;
image->trimmedRect.y = topTrim;
image->trimmedRect.w = rightTrim - leftTrim;
image->trimmedRect.h = bottomTrim - topTrim;
}
else
{
image->trimmedRect = image->originalRect;
}
/* copy and free source pixels */
image->pixels = Cram_malloc(image->trimmedRect.w * image->trimmedRect.h * 4);
Rect dstRect;
dstRect.x = 0;
dstRect.y = 0;
dstRect.w = image->trimmedRect.w;
dstRect.h = image->trimmedRect.h;
Cram_Internal_CopyPixels((uint32_t*) image->pixels, image->trimmedRect.w, (uint32_t*) pixels, width, &dstRect, &image->trimmedRect);
stbi_image_free(pixels);
/* hash */
image->hash = stbds_hash_bytes(image->pixels, image->trimmedRect.w * image->trimmedRect.h * 4, 0);
/* check if this is a duplicate */
image->duplicateOf = NULL;
for (i = 0; i < internalContext->imageCount; i += 1)
{
if (!internalContext->images[i]->duplicateOf)
{
if (Cram_Internal_IsImageEqual(image, internalContext->images[i]))
{
/* this is duplicate data! */
image->duplicateOf = internalContext->images[i];
Cram_free(image->pixels);
image->pixels = NULL;
break;
}
}
}
internalContext->images[internalContext->imageCount] = image;
internalContext->imageCount += 1;
}
int8_t Cram_Pack(Cram_Context *context)
{
RectPackContext *rectPackContext;
Cram_Internal_Context *internalContext = (Cram_Internal_Context*) context;
uint32_t numNodes = internalContext->width;
Rect *packerRects;
uint32_t numRects = 0;
Rect *packerRect;
Rect dstRect, srcRect;
Cram_Image *image;
uint32_t maxWidth = 0;
uint32_t maxHeight = 0;
int32_t i;
internalContext->imageDataCount = internalContext->imageCount;
internalContext->imageDatas = Cram_realloc(internalContext->imageDatas, sizeof(Cram_ImageData) * internalContext->imageDataCount);
rectPackContext = Cram_Internal_InitRectPacker(internalContext->width, internalContext->height);
for (i = 0; i < internalContext->imageCount; i += 1)
{
if (!internalContext->images[i]->duplicateOf)
{
numRects += 1;
}
}
packerRects = Cram_malloc(sizeof(Rect) * numRects);
numRects = 0;
for (i = 0; i < internalContext->imageCount; i += 1)
{
if (!internalContext->images[i]->duplicateOf)
{
packerRect = &packerRects[numRects];
packerRect->w = internalContext->images[i]->trimmedRect.w + internalContext->padding;
packerRect->h = internalContext->images[i]->trimmedRect.h + internalContext->padding;
numRects += 1;
}
}
if (Cram_Internal_PackRects(rectPackContext, packerRects, numRects) < 0)
{
return -1;
}
numRects = 0;
for (i = 0; i < internalContext->imageCount; i += 1)
{
if (!internalContext->images[i]->duplicateOf)
{
packerRect = &packerRects[numRects];
internalContext->images[i]->packedRect.x = packerRect->x;
internalContext->images[i]->packedRect.y = packerRect->y;
internalContext->images[i]->packedRect.w = internalContext->images[i]->trimmedRect.w;
internalContext->images[i]->packedRect.h = internalContext->images[i]->trimmedRect.h;
maxWidth = Cram_max(maxWidth, packerRect->x + packerRect->w);
maxHeight = Cram_max(maxHeight, packerRect->y + packerRect->h);
numRects += 1;
}
}
internalContext->width = Cram_Internal_NextPowerOfTwo(maxWidth);
internalContext->height = Cram_Internal_NextPowerOfTwo(maxHeight);
internalContext->pixels = Cram_realloc(internalContext->pixels, internalContext->width * internalContext->height * 4);
Cram_memset(internalContext->pixels, 0, internalContext->width * internalContext->height * 4);
for (i = 0; i < internalContext->imageCount; i += 1)
{
if (!internalContext->images[i]->duplicateOf)
{
dstRect.x = internalContext->images[i]->packedRect.x;
dstRect.y = internalContext->images[i]->packedRect.y;
dstRect.w = internalContext->images[i]->trimmedRect.w;
dstRect.h = internalContext->images[i]->trimmedRect.h;
srcRect.x = 0;
srcRect.y = 0;
srcRect.w = internalContext->images[i]->trimmedRect.w;
srcRect.h = internalContext->images[i]->trimmedRect.h;
Cram_Internal_CopyPixels(
(uint32_t*) internalContext->pixels,
internalContext->width,
(uint32_t*) internalContext->images[i]->pixels,
internalContext->images[i]->trimmedRect.w,
&dstRect,
&srcRect
);
}
if (internalContext->images[i]->duplicateOf)
{
image = internalContext->images[i]->duplicateOf;
}
else
{
image = internalContext->images[i];
}
internalContext->imageDatas[i].x = image->packedRect.x;
internalContext->imageDatas[i].y = image->packedRect.y;
internalContext->imageDatas[i].width = image->trimmedRect.w;
internalContext->imageDatas[i].height = image->trimmedRect.h;
internalContext->imageDatas[i].trimOffsetX = image->trimmedRect.x - image->originalRect.x;
internalContext->imageDatas[i].trimOffsetY = image->trimmedRect.y - image->originalRect.y;
internalContext->imageDatas[i].untrimmedWidth = image->originalRect.w;
internalContext->imageDatas[i].untrimmedHeight = image->originalRect.h;
internalContext->imageDatas[i].name = strdup(internalContext->images[i]->name);
}
Cram_free(packerRects);
return 0;
}
void Cram_GetPixelData(Cram_Context *context, uint8_t **pPixels, uint32_t *pWidth, uint32_t *pHeight)
{
Cram_Internal_Context *internalContext = (Cram_Internal_Context*) context;
*pPixels = internalContext->pixels;
*pWidth = internalContext->width;
*pHeight = internalContext->height;
}
void Cram_GetMetadata(Cram_Context *context, Cram_ImageData **pImage, uint32_t *pImageCount)
{
Cram_Internal_Context *internalContext = (Cram_Internal_Context*) context;
*pImage = internalContext->imageDatas;
*pImageCount = internalContext->imageDataCount;
}
void Cram_Destroy(Cram_Context *context)
{
Cram_Internal_Context *internalContext = (Cram_Internal_Context*) context;
int32_t i;
if (internalContext->pixels != NULL)
{
Cram_free(internalContext->pixels);
}
for (i = 0; i < internalContext->imageCount; i += 1)
{
if (!internalContext->images[i]->duplicateOf)
{
Cram_free(internalContext->images[i]->pixels);
}
Cram_free(internalContext->images[i]->name);
Cram_free(internalContext->images[i]);
}
Cram_free(internalContext->name);
Cram_free(internalContext->images);
Cram_free(internalContext->imageDatas);
Cram_free(internalContext);
}

150
tools/cli/json_writer.h Normal file
View File

@ -0,0 +1,150 @@
#ifndef JSON_WRITER_H
#define JSON_WRITER_H
#include <string.h>
#include <stdint.h>
#define INITIAL_JSON_OUTPUT_CAPACITY 2048
typedef struct JsonBuilder
{
char *string;
size_t index;
size_t capacity;
size_t indentLevel;
} JsonBuilder;
JsonBuilder* JsonBuilder_Init()
{
JsonBuilder *builder = malloc(sizeof(JsonBuilder));
builder->string = malloc(INITIAL_JSON_OUTPUT_CAPACITY);
builder->capacity = INITIAL_JSON_OUTPUT_CAPACITY;
builder->string[0] = '\0';
strcat(builder->string, "{\n");
builder->indentLevel = 1;
builder->index = 2;
return builder;
}
void JsonBuilder_Internal_MaybeExpand(JsonBuilder *builder, size_t len)
{
if (builder->capacity < builder->index + len)
{
builder->capacity = max(builder->index + len, builder->capacity * 2);
builder->string = realloc(builder->string, builder->capacity);
}
}
void JsonBuilder_Internal_Indent(JsonBuilder *builder)
{
int32_t i;
JsonBuilder_Internal_MaybeExpand(builder, builder->indentLevel);
for (i = 0; i < builder->indentLevel; i += 1)
{
strcat(builder->string, "\t");
}
builder->index += builder->indentLevel;
}
void JsonBuilder_Internal_RemoveTrailingComma(JsonBuilder *builder)
{
if (builder->string[builder->index - 2] == ',')
{
builder->index -= 2;
builder->index += sprintf(&builder->string[builder->index], "\n");
}
}
void JsonBuilder_AppendProperty(JsonBuilder *builder, char *propertyName, char *propertyString, uint8_t isString)
{
JsonBuilder_Internal_Indent(builder);
JsonBuilder_Internal_MaybeExpand(builder, strlen(propertyName) + 4);
builder->index += sprintf(&builder->string[builder->index], "\"%s\": ", propertyName);
if (isString)
{
JsonBuilder_Internal_MaybeExpand(builder, strlen(propertyString) + 4);
builder->index += sprintf(&builder->string[builder->index], "\"%s\",\n", propertyString);
}
else
{
JsonBuilder_Internal_MaybeExpand(builder, strlen(propertyString) + 2);
builder->index += sprintf(&builder->string[builder->index], "%s,\n", propertyString);
}
}
void JsonBuilder_AppendStringProperty(JsonBuilder *builder, char *propertyName, char *value)
{
JsonBuilder_AppendProperty(builder, propertyName, value, 1);
}
void JsonBuilder_AppendIntProperty(JsonBuilder *builder, char *propertyName, int32_t value)
{
char buffer[65];
itoa(value, buffer, 10);
JsonBuilder_AppendProperty(builder, propertyName, buffer, 0);
}
void JsonBuilder_StartObject(JsonBuilder *builder)
{
JsonBuilder_Internal_Indent(builder);
JsonBuilder_Internal_MaybeExpand(builder, 2);
builder->index += sprintf(&builder->string[builder->index], "{\n");
builder->indentLevel += 1;
}
void JsonBuilder_EndObject(JsonBuilder *builder)
{
JsonBuilder_Internal_RemoveTrailingComma(builder);
builder->indentLevel -= 1;
JsonBuilder_Internal_Indent(builder);
JsonBuilder_Internal_MaybeExpand(builder, 3);
builder->index += sprintf(&builder->string[builder->index], "},\n");
}
void JsonBuilder_StartArrayProperty(JsonBuilder *builder, char *propertyName)
{
JsonBuilder_Internal_Indent(builder);
JsonBuilder_Internal_MaybeExpand(builder, strlen(propertyName) + 6);
builder->index += sprintf(&builder->string[builder->index], "\"%s\": [\n", propertyName);
builder->indentLevel += 1;
}
void JsonBuilder_FinishArrayProperty(JsonBuilder *builder)
{
JsonBuilder_Internal_RemoveTrailingComma(builder);
builder->indentLevel -= 1;
JsonBuilder_Internal_Indent(builder);
JsonBuilder_Internal_MaybeExpand(builder, 3);
builder->index += sprintf(&builder->string[builder->index], "],\n");
}
void JsonBuilder_Finish(JsonBuilder *builder)
{
builder->indentLevel = 0;
JsonBuilder_Internal_RemoveTrailingComma(builder);
JsonBuilder_Internal_MaybeExpand(builder, 2);
builder->index += sprintf(&builder->string[builder->index], "}\n");
}
void JsonBuilder_Destroy(JsonBuilder *builder)
{
free(builder->string);
free(builder);
}
#endif /* JSON_WRITER_H */

1212
tools/cli/lib/dirent.h Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

254
tools/cli/main.c Normal file
View File

@ -0,0 +1,254 @@
#include "cram.h"
#include "dirent.h"
#include "json_writer.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define MAX_DIR_LENGTH 2048
static Cram_Context *context;
static const char* GetFilenameExtension(const char *filename)
{
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
{
return "";
}
return dot + 1;
}
/* Mostly taken from K&R C 2nd edition page 182 */
static void dirwalk(char *dir)
{
dirent *dp;
DIR *dfd;
char subname[2048];
if ((dfd = opendir(dir)) == NULL)
{
fprintf(stderr, "Can't open %s\n", dir);
return;
}
while ((dp = readdir(dfd)) != NULL)
{
if ( strcmp(dp->d_name, ".") == 0 ||
strcmp(dp->d_name, "..") == 0
)
{
continue;
}
sprintf(subname, "%s%c%s", dir, SEPARATOR, dp->d_name);
if (dp->d_type == DT_DIR)
{
dirwalk(subname);
}
else
{
if (strcmp(GetFilenameExtension(subname), "png") == 0)
{
Cram_AddFile(context, subname);
}
else
{
fprintf(stdout, "skipping %s\n", subname);
}
}
}
closedir(dfd);
}
/* TODO: command line options */
void print_help()
{
fprintf(stdout, "Usage: cram input_dir output_dir atlas_name [--padding padding_value] [--notrim] [--dimension max_dimension]");
}
uint8_t check_dir_exists(char *path)
{
DIR *dir = opendir(path);
if (dir) {
closedir(dir);
return 1;
} else {
return 0;
}
}
int main(int argc, char *argv[])
{
Cram_ContextCreateInfo createInfo;
uint8_t *pixelData;
uint32_t width;
uint32_t height;
char *arg;
char *inputDirPath = NULL;
char *outputDirPath = NULL;
char *imageOutputFilename;
char *metadataFilename;
JsonBuilder *jsonBuilder;
Cram_ImageData *imageDatas;
uint32_t imageCount;
int32_t i;
/* Set defaults */
createInfo.padding = 0;
createInfo.trim = 1;
createInfo.maxDimension = 8192;
createInfo.name = NULL;
if (argc < 2)
{
print_help();
return 1;
}
for (i = 1; i < argc; i += 1)
{
arg = argv[i];
if (strcmp(arg, "--padding") == 0)
{
i += 1;
createInfo.padding = atoi(argv[i]);
if (createInfo.padding < 0)
{
fprintf(stderr, "Padding must be equal to or greater than 0!");
return 1;
}
}
else if (strcmp(arg, "--notrim") == 0)
{
createInfo.trim = 0;
}
else if (strcmp(arg, "--dimension") == 0)
{
i += 1;
createInfo.maxDimension = atoi(argv[i]);
if (createInfo.maxDimension < 0 || createInfo.maxDimension > 8192)
{
fprintf(stderr, "Padding must be between 0 and 8192!");
return 1;
}
}
else if (strcmp(arg, "--help") == 0)
{
print_help();
return 0;
}
else
{
if (inputDirPath == NULL)
{
inputDirPath = arg;
}
else if (outputDirPath == NULL)
{
outputDirPath = arg;
}
else if (createInfo.name == NULL)
{
createInfo.name = arg;
}
}
}
if (inputDirPath == NULL || createInfo.name == NULL)
{
print_help();
return 1;
}
/* check that dirs exist */
if (!check_dir_exists(inputDirPath))
{
fprintf(stderr, "Input directory not found!");
return 1;
}
if (!check_dir_exists(outputDirPath))
{
fprintf(stderr, "Output directory not found!");
return 1;
}
context = Cram_Init(&createInfo);
dirwalk(inputDirPath);
if (Cram_Pack(context) < 0)
{
fprintf(stderr, "Not enough room! Packing aborted!");
return 1;
}
/* output pixel data */
Cram_GetPixelData(context, &pixelData, &width, &height);
imageOutputFilename = Cram_malloc(strlen(createInfo.name) + 5);
strcpy(imageOutputFilename, createInfo.name);
strcat(imageOutputFilename, ".png");
stbi_write_png(
imageOutputFilename,
width,
height,
4,
pixelData,
width * 4
);
/* output json */
Cram_GetMetadata(context, &imageDatas, &imageCount);
jsonBuilder = JsonBuilder_Init();
JsonBuilder_AppendStringProperty(jsonBuilder, "Name", createInfo.name);
JsonBuilder_AppendIntProperty(jsonBuilder, "Width", width);
JsonBuilder_AppendIntProperty(jsonBuilder, "Height", height);
JsonBuilder_StartArrayProperty(jsonBuilder, "Images");
for (i = 0; i < imageCount; i += 1)
{
JsonBuilder_StartObject(jsonBuilder);
JsonBuilder_AppendStringProperty(jsonBuilder, "Name", imageDatas[i].name);
JsonBuilder_AppendIntProperty(jsonBuilder, "X", imageDatas[i].x);
JsonBuilder_AppendIntProperty(jsonBuilder, "Y", imageDatas[i].y);
JsonBuilder_AppendIntProperty(jsonBuilder, "W", imageDatas[i].width);
JsonBuilder_AppendIntProperty(jsonBuilder, "H", imageDatas[i].height);
JsonBuilder_AppendIntProperty(jsonBuilder, "TrimOffsetX", imageDatas[i].trimOffsetX);
JsonBuilder_AppendIntProperty(jsonBuilder, "TrimOffsetY", imageDatas[i].trimOffsetY);
JsonBuilder_AppendIntProperty(jsonBuilder, "UntrimmedWidth", imageDatas[i].untrimmedWidth);
JsonBuilder_AppendIntProperty(jsonBuilder, "UntrimmedHeight", imageDatas[i].untrimmedHeight);
JsonBuilder_EndObject(jsonBuilder);
}
JsonBuilder_FinishArrayProperty(jsonBuilder);
JsonBuilder_Finish(jsonBuilder);
metadataFilename = Cram_malloc(strlen(createInfo.name) + 6);
strcpy(metadataFilename, createInfo.name);
strcat(metadataFilename, ".json");
FILE *jsonOutput = fopen(metadataFilename, "w");
if (!jsonOutput)
{
fprintf(stderr, "Could not open JSON file for writing!");
return 1;
}
fprintf(jsonOutput, jsonBuilder->string);
JsonBuilder_Destroy(jsonBuilder);
fclose(jsonOutput);
Cram_free(imageOutputFilename);
Cram_free(metadataFilename);
Cram_Destroy(context);
return 0;
}