extends RigidBody

export (String, MULTILINE) var patch = ""
export (float, 0, 100) var audible_range_max = 10.0

var _my_patch = "res://main.pd"
var _my_id = 0

func set_size(size):
	$CollisionShape.shape.radius = size
	$MeshInstance.mesh.radius = size
	$MeshInstance.mesh.height = size * 2

func set_freq(freq):
	Global._gdpd.start_message(2)
	Global._gdpd.add_symbol('freq')
	Global._gdpd.add_float(freq)
	Global._gdpd.finish_list("fromGodot" + String(_my_id))

func set_gain(gain):
	Global._gdpd.start_message(2)
	Global._gdpd.add_symbol('gain')
	Global._gdpd.add_float(gain)
	Global._gdpd.finish_list("fromGodot" + String(_my_id))

func set_color(color):
	$MeshInstance.material_override = SpatialMaterial.new()
	$MeshInstance.material_override.albedo_color = color

func _ready():
	# load patch
	_my_id = Global.load_patch(ProjectSettings.globalize_path(_my_patch))

	# listen 'player_transform_updated' event
	Events.connect("player_transform_updated", self, "_on_Events_player_transform_updated")

func _on_Events_player_transform_updated(playerpos, playerheading):
	var mypos = get_global_translation()
	var mypos2d = Vector2(mypos.x, mypos.z)
	var playerpos2d = Vector2(playerpos.x, playerpos.z)
	# calculate distance
	var distance = mypos.distance_to(playerpos)
	# calculate angle
	var angle = fmod(fmod(playerpos2d.angle_to_point(mypos2d) + playerheading - PI/2, PI*2) + PI*2, PI*2)
	if angle > PI:
		angle = angle - PI*2
	# (check)
#	print(str(_my_id) +" : ("+ str(distance) +","+ str(angle) +")")
	# calculate gain
	var gain = max(1 - distance/audible_range_max, 0)
	# send to the patch
	Global._gdpd.start_message(3)
	Global._gdpd.add_symbol("panvol")
	Global._gdpd.add_float(gain)
	Global._gdpd.add_float(angle)
	Global._gdpd.finish_list("fromGodot" + String(_my_id))


func _exit_tree():
	Global.close_patch(_my_id)
