extends Spatial

var sub = load("res://cosmic/osc.tscn")

var _rot_speed_origin

var gain1 = 40 # for $main
var range1 = 80 # for $main

var gain2 = 0.1 # for osc
var range2 = 20 # for osc

var ratio = 0.4

func _ready():
	# 'main' at center.
	$main.set_size(rand_range(10, 15))
	$main.audible_range_max = range1
	$main.set_freq(rand_range(100, 300))
	$main.set_gain(gain1)

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

	#
	_rot_speed_origin = $main._rot_speed

func _spawn(nsatellites, yrange):
	# many 'sub' surrounds 'main' like satellites
	for i in range(nsatellites):
		var s = sub.instance()
		$main.add_child(s)
		s.set_size(rand_range(0.2, 1.2))
		s.set_color(Color.black)
		var d = polar2cartesian(rand_range(20, 54), rand_range(0, 2*PI))
		s.translate(Vector3(d.x, rand_range(yrange[0], yrange[1]), d.y))
		s.audible_range_max = range2
		s.set_freq(rand_range(200, 2000))
		s.set_gain(gain2)

func _on_Events_player_transform_updated(playerpos, playerheading):
	var mypos = $main.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)
	if distance < $main/CollisionShape.shape.radius:
		$main._rot_speed = _rot_speed_origin * pow(distance/$main/CollisionShape.shape.radius, 2)
		for c in $main.get_children():
			if c.is_in_group('sounders'):
				c.audible_range_max = range2 * pow($main/CollisionShape.shape.radius/(distance + 0.1), 2)
				c.set_gain(gain2 * pow(distance/$main/CollisionShape.shape.radius, 2))
		$main.set_gain(gain1 * pow(distance/$main/CollisionShape.shape.radius, ratio))
	else:
		$main._rot_speed = _rot_speed_origin
		for c in $main.get_children():
			if c.is_in_group('sounders'):
				c.audible_range_max = range2
				c.set_gain(gain2)
		$main.set_gain(gain1)

