// Copyright (c) 2023 Lachlan McDonald
// This work is licensed under the MIT License (MIT)
// https://github.com/lachlanmcdonald/magicavoxel-shaders
//
// This script utilises or modifies code from other projects or publications.
// Please see the attributions below for more information:
//
// 1. Copyright (c) 2020 ValgoBoi <https://github.com/ValgoBoi/clover-noise>
//    MIT License (MIT)
//    https://github.com/ValgoBoi/clover-noise/blob/master/LICENSE
//
// xs random [Threshold] [Color]
//
// xs_begin
// author : '@lmcdx.bsky.social'
// arg : { name = 'Threshold'  var = 'm_threshold'  range = '0 100'  value = '50'  step = '1'  precision = '0' }
// arg : { name = 'Color'  var = 'm_color'  range = '0 255'  value = '1'  step = '1'  precision = '0' }
// xs_end

float threshold = m_threshold / 100.0;

bool no_axis_mode = all(equal(ivec3(i_axis), ivec3(0)));
bvec3 axis_mode = no_axis_mode ? bvec3(true) : equal(ivec3(i_axis), ivec3(1));

float hash(vec2 p, float seed) {
	p += seed;
	return fract(1e4 * sin(17.0 * p.x + p.y * 0.1) * (0.1 + abs(sin(p.y * 13.0 + p.x))));
}

bool isSelectedPal(float p) {
	for (int i = 0; i < i_num_color_sels; i += 1) {
		if (p == color_sel(float(i))) {
			return true;
		}
	}
	return false;
}

float map(vec3 v) {
	float index = voxel(v);

	float x = axis_mode.x ? v.x : 1.0;
	float y = axis_mode.y ? v.y : 1.0;
	float z = axis_mode.z ? v.z : 1.0;
	float j = hash(vec2(x, y), threshold + i_iter + 1.0);
	float k = hash(vec2(j, z), threshold + i_iter + 1.0);

	if (isSelectedPal(index)) {
		if (k < threshold) {
			return m_color;
		}
	}
	return index;
}