// Copyright (c) 2023 Lachlan McDonald
// This work is licensed under the MIT License (MIT)
// https://github.com/lachlanmcdonald/magicavoxel-shaders
//
// xs primitive/stairs_stringer [Mode] [Direction] [Count] [Height] [Stringer]
//
// xs_begin
// author : '@lmcdx.bsky.social'
// arg : { name = 'Mode'  var = 'm_mode'  range = '0 3'  value = '0'  step = '1'  precision = '0' }
// arg : { name = 'Direction'  var = 'm_direction'  range = '0 3'  value = '0'  step = '1'  precision = '0' }
// arg : { name = 'Count'  var = 'm_count'  range = '1 256'  value = '5'  step = '1'  precision = '0' }
// arg : { name = 'Height'  var = 'm_height'  range = '1 256'  value = '1'  step = '1'  precision = '0' }
// arg : { name = 'Stringer'  var = 'm_stringer'  range = '0 256'  value = '0'  step = '1'  precision = '0' }
// xs_end

int mode = int(m_mode);
int direction = int(m_direction);
float count = min(m_count, i_volume_size.z);
float height = m_height;
float stringer = m_stringer;

float map(vec3 v) {
	float volume_n;
	float vector_n;

	if (direction == 0) {
		vector_n = v.x;
		volume_n = i_volume_size.x;
	} else if (direction == 1) {
		vector_n = v.y;
		volume_n = i_volume_size.y;
	} else if (direction == 2) {
		vector_n = i_volume_size.x - v.x;
		volume_n = i_volume_size.x;
	} else if (direction == 3) {
		vector_n = i_volume_size.y - v.y;
		volume_n = i_volume_size.y;
	}

	if (mode == 1) {
		height = max(1.0, floor(i_volume_size.z / count));
	} else if (mode == 2) {
		count = max(2.0, floor(i_volume_size.z / height));
	} else if (mode == 3) {
		stringer = max(0.0, floor(i_volume_size.z / (count + height)) - 1.0);
	}

	float w = volume_n / count;
	float d = floor(vector_n / w);
	float a = d * height;
	float b = d * height + height;

	if (vector_n - (d * w) <= w) {
		if (v.z > a && v.z < (b + stringer)) {
			return i_color_index;
		}
	}

	return 0.0;
}