sle/src/strtocolor.c

60 lines
1.3 KiB
C

/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright (C) 2021 KikooDX */
#include "strtocolor.h"
#include "info.h"
#include <raylib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HEX_TABLE_SIZE 16
static const int hex_table[HEX_TABLE_SIZE] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
static const char *format_error =
"ERROR: flag expected a color argument in the form #RRGGBB, got "
"\"%s\"\n";
/* Attempt to convert a string to raylib Color. */
Color strtocolor(char *string)
{
int rgb[3] = {0, 0, 0};
char *character = string + (string[0] == '#');
const size_t string_len = strlen(character);
int i = 0;
int sum = 0;
if (string_len != 6) {
fprintf(stderr, format_error, string);
exit(EXIT_FAILURE);
}
while (*character != '\0') {
int value = -1;
int j;
for (j = 0; j < HEX_TABLE_SIZE; j += 1) {
if (hex_table[j] == *character) {
value = j;
break;
}
}
if (value == -1) {
fprintf(stderr, format_error, string);
exit(EXIT_FAILURE);
}
sum += value * (1 + 15 * (i % 2));
INFO_VAR("%d", sum);
if (i % 2) {
rgb[i / 2] = sum;
sum = 0;
}
i += 1;
character += 1;
}
INFO_VAR("r=%d", rgb[0]);
INFO_VAR("g=%d", rgb[1]);
INFO_VAR("b=%d", rgb[2]);
return (Color){rgb[0], rgb[1], rgb[2], 255};
}