extends Camera3D
class_name CameraManager

var target:int
var target_pos:Vector2 = Vector2.ZERO
var target_pos_y:float
var target_pos_now:Vector2 = Vector2.ZERO
var level_size:Vector2
var offset:float = 5
var camera_limit = Vector3(6.4,1.04,3.6) #x,up,z-downd

var basic_size = Vector2(640,360)
var scale_y = cos(deg_to_rad(45.0)) * 2.0 #1.414
var sample_rate = 3.0
var stage_size = basic_size * sample_rate
var stage_scale = Vector2(1,scale_y) / sample_rate
var stage_offset_y = (scale_y - 1.0) * 0.5 / sample_rate * stage_size.y
var screen_pos_scale = Vector2(sample_rate,sample_rate/scale_y)
var screen_pos_offset = Vector2(0,-stage_offset_y)

func _ready():
	Global.camera_mgr = self
	SignalManager.character_create.connect(on_character_create)
	SignalManager.character_pos_changed.connect(on_character_pos_changed)
	SignalManager.character_hit_floor.connect(on_character_hit_floor)
	SignalManager.character_destroy.connect(on_character_destroy)
	SignalManager.level_size_change.connect(on_level_size_change)
	SignalManager.level_loading_end.connect(on_level_loading_end)
	
func _process(delta):
	target_pos_lerp(0,delta,5)
	target_pos_lerp(1,delta,5)
	position.x = target_pos_now.x
	position.z = target_pos_now.y + target_pos_y + offset
	position.y = target_pos_y + offset

func target_pos_lerp(index:int,delta:float,delta_scale:float):
	var diff = abs(target_pos_now[index] - target_pos[index])
	if diff < Setting.pixel_size:
		target_pos_now[index] = Util.snap_float(target_pos[index])
	else:
		var weight_min = Setting.pixel_size / 2 / diff
		var weight = max(delta * delta_scale,weight_min)
		target_pos_now[index] = lerp(target_pos_now[index], target_pos[index], weight)

func on_character_create(id:int,type:int,pos:Vector3):
	if type == Enum.ECharacterType.Player:
		target = id
		on_character_pos_changed(id,pos)
		on_character_hit_floor(id,pos)
		on_level_loading_end()
	
func on_character_pos_changed(id:int,pos:Vector3):
	if id == target:
		set_target_pos(pos)

func on_character_hit_floor(id:int,pos:Vector3):
	if id == target:
		target_pos_y = pos.y
		set_target_pos(pos)

func set_target_pos(pos:Vector3):
	target_pos.x = clamp(pos.x,camera_limit.x,level_size.x-camera_limit.x)
	target_pos.y = clamp(pos.z-target_pos_y,camera_limit.y-target_pos_y,level_size.y-camera_limit.z-target_pos_y)

func on_character_destroy(id:int):target = 0
func on_level_size_change(size:Vector2):level_size = size

func on_level_loading_end():
	target_pos_now.x = target_pos.x
	target_pos_now.y = target_pos.y

func get_screen_pos(pos:Vector3) -> Vector2:
	var ret = unproject_position(pos)
	ret.x /= screen_pos_scale.x
	ret.y /= screen_pos_scale.y
	ret.x += screen_pos_offset.x
	ret.y += screen_pos_offset.y
	return ret
	
