~turminal/raytracing

28d1b1c045cb136f2f9ad2d578f2293e87eb6979 — Bor Grošelj Simić 2 years ago 0b25dcb
color: add serialize/deserialize
1 files changed, 36 insertions(+), 1 deletions(-)

M color.ha
M color.ha => color.ha +36 -1
@@ 1,4 1,6 @@
use math::{sqrtf64, nextafterf64};
use math::{f64frombits, f64bits, sqrtf64, nextafterf64};
use endian;


export type color = struct {
	r: f64,


@@ 37,6 39,18 @@ export fn fromrgb(c: rgb) color = {
	};
};

export fn deserialize(b: []u8) color = color {
	r = f64frombits(endian::legetu64(b[..8])),
	g = f64frombits(endian::legetu64(b[8..16])),
	b = f64frombits(endian::legetu64(b[16..])),
};

export fn serialize(b: []u8, c: const *color) void = {
	endian::leputu64(b[..8], f64bits(c.r));
	endian::leputu64(b[8..16], f64bits(c.g));
	endian::leputu64(b[16..24], f64bits(c.b));
};

export fn lerp(c1: *const color, c2: *const color, t: f64) color = color {
	r = (1.0 - t) * c1.r + t * c2.r,
	g = (1.0 - t) * c1.g + t * c2.g,


@@ 51,3 65,24 @@ export fn sum_color(c1: *const color, c2: *const color) color = color {

export fn equal(c1: color, c2: color) bool =
	c1.r == c2.r && c1.g == c2.g && c1.b == c2.b;

@test fn equal() void = {
	let c = C(0.2, 0.45, 0.8);
	assert(equal(C(0.2, 0.45, 0.8), c));
	assert(!equal(c, C(0.2, 0.0, 0.8)));
	assert(!equal(c, C(0.0, 0.45, 0.8)));
	assert(!equal(c, C(0.2, 0.45, 0.0)));
};

@test fn serialize() void = {
	let c = C(0.2, 0.45, 0.8);
	let b: [24]u8 = [0...];
	serialize(b, &c);
	assert(equal(c, deserialize(b)));
};

@test fn sum_color() void = {
	let grey = C(0.5, 0.5, 0.5);
	let white = C(1.0, 1.0, 1.0);
	assert(equal(sum_color(&grey, &grey), white));
};