# script_point_y_toward_position by motomataru
# Input: from position, to position
# Output: reg0 fixed point distance
("point_y_toward_position", [
(store_script_param, ":from_position", 1),
(store_script_param, ":to_position", 2),
(position_get_x, ":dist_x_to_cosine", ":to_position"),
(position_get_x, ":from_coord", ":from_position"),
(val_sub, ":dist_x_to_cosine", ":from_coord"),
(store_mul, ":sum_square", ":dist_x_to_cosine", ":dist_x_to_cosine"),
(position_get_y, ":dist_y_to_sine", ":to_position"),
(position_get_y, ":from_coord", ":from_position"),
(val_sub, ":dist_y_to_sine", ":from_coord"),
(store_mul, reg0, ":dist_y_to_sine", ":dist_y_to_sine"),
(val_add, ":sum_square", reg0),
(convert_from_fixed_point, ":sum_square"),
(store_sqrt, ":distance_between", ":sum_square"),
(try_begin),
(gt, ":distance_between", 0),
(convert_to_fixed_point, ":dist_x_to_cosine"),
(val_div, ":dist_x_to_cosine", ":distance_between"),
(convert_to_fixed_point, ":dist_y_to_sine"),
(val_div, ":dist_y_to_sine", ":distance_between"),
(try_begin),
(lt, ":dist_x_to_cosine", 0),
(assign, ":bound_a", 90),
(assign, ":bound_b", 270),
(assign, ":theta", 180),
(else_try),
(assign, ":bound_a", 90),
(assign, ":bound_b", -90),
(assign, ":theta", 0),
(try_end),
(assign, ":sine_theta", 0), #avoid error on compile
(convert_to_fixed_point, ":theta"),
(convert_to_fixed_point, ":bound_a"),
(convert_to_fixed_point, ":bound_b"),
(try_for_range, reg0, 0, 6), #precision 90/2exp6 (around 2 degrees)
(store_sin, ":sine_theta", ":theta"),
(try_begin),
(gt, ":sine_theta", ":dist_y_to_sine"),
(assign, ":bound_a", ":theta"),
(else_try),
(lt, ":sine_theta", ":dist_y_to_sine"),
(assign, ":bound_b", ":theta"),
(try_end),
(store_add, ":angle_sum", ":bound_b", ":bound_a"),
(store_div, ":theta", ":angle_sum", 2),
(try_end),
(convert_from_fixed_point, ":theta"),
(position_get_rotation_around_z, reg0, ":from_position"),
(val_sub, ":theta", reg0),
(val_sub, ":theta", 90), #point y-axis at destination
(position_rotate_z, ":from_position", ":theta"),
(try_end),
(assign, reg0, ":distance_between"),
]),