1 /*
2  * libtilemcore - Graphing calculator emulation library
3  *
4  * Copyright (C) 2010 Benjamin Moody
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License
8  * as published by the Free Software Foundation; either version 2.1 of
9  * the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see
18  * <http://www.gnu.org/licenses/>.
19  */
20 
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24 
25 #include <stdio.h>
26 #include <math.h>
27 #include "tilem.h"
28 
tilem_color_palette_new(int rlight,int glight,int blight,int rdark,int gdark,int bdark,double gamma)29 dword* tilem_color_palette_new(int rlight, int glight, int blight,
30 			       int rdark, int gdark, int bdark,
31 			       double gamma)
32 {
33 	dword* pal = tilem_new_atomic(dword, 256);
34 	double r0, g0, b0, dr, dg, db;
35 	double igamma = 1.0 / gamma;
36 	double s = (1.0 / 255.0);
37 	int r, g, b, i;
38 
39 	r0 = pow(rlight * s, gamma);
40 	g0 = pow(glight * s, gamma);
41 	b0 = pow(blight * s, gamma);
42 	dr = (pow(rdark * s, gamma) - r0) * s;
43 	dg = (pow(gdark * s, gamma) - g0) * s;
44 	db = (pow(bdark * s, gamma) - b0) * s;
45 
46 	pal[0] = (rlight << 16) | (glight << 8) | blight;
47 
48 	for (i = 1; i < 255; i++) {
49 		r = pow(r0 + i * dr, igamma) * 255.0 + 0.5;
50 		if (r < 0) r = 0;
51 		if (r > 255) r = 255;
52 
53 		g = pow(g0 + i * dg, igamma) * 255.0 + 0.5;
54 		if (g < 0) g = 0;
55 		if (g > 255) g = 255;
56 
57 		b = pow(b0 + i * db, igamma) * 255.0 + 0.5;
58 		if (b < 0) b = 0;
59 		if (b > 255) b = 255;
60 
61 		pal[i] = (r << 16) | (g << 8) | b;
62 	}
63 
64 	pal[255] = (rdark << 16) | (gdark << 8) | bdark;
65 
66 	return pal;
67 }
68 
tilem_color_palette_new_packed(int rlight,int glight,int blight,int rdark,int gdark,int bdark,double gamma)69 byte* tilem_color_palette_new_packed(int rlight, int glight, int blight,
70                                      int rdark, int gdark, int bdark,
71                                      double gamma)
72 {
73 	dword* palette;
74 	byte* packed;
75 	int i;
76 
77 	palette = tilem_color_palette_new(rlight, glight, blight,
78 	                                  rdark, gdark, bdark, gamma);
79 
80 	packed = tilem_new_atomic(byte, 256 * 3);
81 	for (i = 0; i < 256; i++) {
82 		packed[i * 3] = palette[i] >> 16;
83 		packed[i * 3 + 1] = palette[i] >> 8;
84 		packed[i * 3 + 2] = palette[i];
85 	}
86 
87 	tilem_free(palette);
88 
89 	return packed;
90 }
91