#ifndef TWN_UTIL_C_H
#define TWN_UTIL_C_H

#include "twn_types.h"

#include <SDL2/SDL.h>

#include <stdbool.h>
#include <math.h>

#define MAX SDL_max
#define MIN SDL_min

void *cmalloc(size_t size);
void *crealloc(void *ptr, size_t size);
void *ccalloc(size_t num, size_t size);

void cry_impl(const char *file, const int line, const char *title, const char *text);
#define CRY(title, text) cry_impl(__FILE__, __LINE__, title, text)
#define CRY_SDL(title) cry_impl(__FILE__, __LINE__, title, SDL_GetError())
#define CRY_PHYSFS(title)                                               \
cry_impl(__FILE__, __LINE__, title, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()))

/* for when there's absolutely no way to continue */
_Noreturn void die_abruptly(void);

/* note: you must free the returned string */
char *expand_asterisk(const char *mask, const char *to);

/* http://www.azillionmonkeys.com/qed/sqroot.html */
static inline float fast_sqrt(float x)
{
    union {
        float f;
        uint32_t u;
    } pun = {.f = x};

    pun.u += 127 << 23;
    pun.u >>= 1;

    return pun.f;
}


static inline Vec2 fast_cossine(float a) {
    const float s = sinf(a);
    return (Vec2){
        .x = fast_sqrt(1.0f - s * s) * (a >= (float)M_PI_2 && a < (float)(M_PI + M_PI_2) ? -1 : 1),
        .y = s
    };
}

static inline bool is_power_of_two(int x)
{
    return (x != 0) && ((x & (x - 1)) == 0);
}

#endif
