extends Resource
class_name SummerDayQuad

export(PoolVector3Array) var original_vertices = PoolVector3Array([
	Vector3(-1.0, -1.0, 0.0),
	Vector3(1.0, -1.0, 0.0),
	Vector3(1.0, 1.0, 0.0),
	Vector3(-1.0, 1.0, 0.0),
])

export(PoolVector2Array) var vertices = PoolVector2Array([
	Vector2(-0.4, -0.4),
	Vector2(0.1, -0.4),
	Vector2(0.1, 0.1),
	Vector2(-0.4, 0.1),
])


func guess_normal() -> Vector3:
	var original_angles = get_quad_angles(original_vertices)
	
	var angles = get_quad_angles(vertices)
	
	var angle_changes = [
		range_lerp(angles[0], original_angles[0], PI, 0.0, 1.0),
		range_lerp(angles[1], original_angles[1], PI, 0.0, 1.0),
		range_lerp(angles[2], original_angles[2], PI, 0.0, 1.0),
		range_lerp(angles[3], original_angles[3], PI, 0.0, 1.0),
	]
	
	var FRONT_VECTOR = Vector3(0.0, 0.0, -1.0)
	
	# Going \.
	var s_slope_vector_dest
	var s_slope_vector_weight
	if angle_changes[0] > angle_changes[2]:
		s_slope_vector_dest = Vector3(-1.0, -1.0, 0.0)
		s_slope_vector_weight = angle_changes[0]
	elif angle_changes[0] < angle_changes[2]:
		s_slope_vector_dest = Vector3(1.0, 1.0, 0.0)
		s_slope_vector_weight = angle_changes[2]
	else:
		s_slope_vector_dest = FRONT_VECTOR
		s_slope_vector_weight = 0.0
	
	# Going /.
	var z_slope_vector_dest
	var z_slope_vector_weight
	if angle_changes[1] > angle_changes[3]:
		z_slope_vector_dest = Vector3(1.0, -1.0, 0.0)
		z_slope_vector_weight = angle_changes[1]
	elif angle_changes[1] < angle_changes[3]:
		z_slope_vector_dest = Vector3(-1.0, 1.0, 0.0)
		z_slope_vector_weight = angle_changes[3]
	else:
		z_slope_vector_dest = FRONT_VECTOR
		z_slope_vector_weight = 0.0
	
	var s_slope_vector = FRONT_VECTOR.slerp(
		s_slope_vector_dest, s_slope_vector_weight
	)
	
	var z_slope_vector = FRONT_VECTOR.slerp(
		z_slope_vector_dest, z_slope_vector_weight
	)
	
	var total_weight = s_slope_vector_weight + z_slope_vector_weight
	if total_weight != 0.0:
		return s_slope_vector.slerp(
			z_slope_vector, s_slope_vector_weight / total_weight
		)
	else:
		return FRONT_VECTOR


func get_quad_angles(verts) -> Array:
	var angles = []
	for i in range(4):
		var next_i = wrapi(i + 1, 0, 4)
		var prev_i = wrapi(i - 1, 0, 4)
		var to_next = verts[next_i] - verts[i]
		var to_prev = verts[prev_i] - verts[i]
		var angle = to_next.angle_to(to_prev)
		angles.append(angle)
	return angles
