extends Spatial


# Declare member variables here. Examples:
# var a = 2
# var b = "text"


#These are terrible but will hopefully improve as problems become evident
#Units are 1000km, hours, and degrees
export var semimajor_axis = 100000
export var semiminor_axis = 0
export var angle_of_apoapsis = 42
export var xtilt = 0
export var ytilt = 0
export var daylen = 6
export var color = Color.blue
var orbital_period
var planet
var eccentric_anomaly
var mean_anomaly
var eccentricity
var focus

# Called when the node enters the scene tree for the first time.
func _ready():
	planet = get_child(0)
	self.rotate_y(deg2rad(angle_of_apoapsis))
	self.rotate_x(deg2rad(xtilt))
	self.rotate_z(deg2rad(ytilt))
	eccentricity = sqrt(1 - pow(semiminor_axis,2)/pow(semimajor_axis,2))

	eccentric_anomaly = 0
	mean_anomaly = 0

	orbital_period = 2 * PI * sqrt(pow(semimajor_axis,3)/1.327e2)

	focus = sqrt(pow(semimajor_axis,2) - pow(semiminor_axis,2))
	
	var path = get_node("ImmediateGeometry")
	path.material_override.albedo_color = color
	
	path.begin(Mesh.PRIMITIVE_LINE_LOOP)
	for i in range(1000):
		var x = semimajor_axis * (cos(i/500.0 * PI) - eccentricity)
		var y = semiminor_axis * sin(i/500.0 * PI)
		path.add_vertex(Vector3(x,0,y))
	path.end()
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass
# warning-ignore:unused_argument
func _physics_process(delta):
	mean_anomaly += delta * 5000 / orbital_period * 60
	
	eccentric_anomaly = mean_anomaly

# warning-ignore:unused_variable
	for x in range(1000): # yay brute force!
		eccentric_anomaly = mean_anomaly + eccentricity * sin(eccentric_anomaly)
	
	var x = semimajor_axis * (cos(eccentric_anomaly) - eccentricity)
	var y = semiminor_axis * sin(eccentric_anomaly)
	planet.translation = Vector3(x,0,y)
	pass
