feat(user/mw_wc2sp.sh):Generate subpage list wikicode
[BK-2020-03.git] / user / mc_distance_calc.sh
... / ...
CommitLineData
1#!/usr/bin/env bash
2# Desc: Calculates distances between two minecraft coordinates
3# Depends: bash 5.1.16, bc 1.07.1
4# Depends: BK-2020-03: yell(), die(), must()
5# Version: 0.0.2
6# Example: script.sh 0 0 0 1 1 1
7# Note: results in xyz distance of 1.73205…
8
9yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
10die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
11must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
12checkFlt() {
13 # Desc: Checks if arg is a float
14 # Usage: checkFlt arg
15 # Input: arg: float
16 # Output: - return code 0 (if arg is float)
17 # - return code 1 (if arg is not float)
18 # Example: if ! checkFlt $arg; then echo "not flt"; fi;
19 # Version: 0.0.2
20 # Depends: yell(), die(), bash 5.0.3
21 # Ref/Attrib: JDB https://stackoverflow.com/a/12643073 float regex
22 local returnState
23
24 #===Process Arg===
25 if [[ $# -ne 1 ]]; then
26 die "ERROR:Invalid number of arguments:$#";
27 fi;
28
29 RETEST1='^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$'; # Regular Expression to test
30 if [[ ! $1 =~ $RETEST1 ]] ; then
31 returnState="false";
32 else
33 returnState="true";
34 fi;
35
36 #===Determine function return code===
37 if [ "$returnState" = "true" ]; then
38 return 0;
39 else
40 return 1;
41 fi;
42} # Checks if arg is float
43main() {
44 x1="$1"; y1="$2"; z1="$3";
45 x2="$4"; y2="$5"; z2="$6";
46 #declare -p x1 y1 z1 x2 y2 z2; # debug
47
48 # Check inputs
49 if ! checkFlt "$x1"; then die "FATAL:Not a float:$x1"; fi;
50 if ! checkFlt "$y1"; then die "FATAL:Not a float:$y1"; fi;
51 if ! checkFlt "$z1"; then die "FATAL:Not a float:$z1"; fi;
52 if ! checkFlt "$x2"; then die "FATAL:Not a float:$x2"; fi;
53 if ! checkFlt "$y2"; then die "FATAL:Not a float:$y2"; fi;
54 if ! checkFlt "$z2"; then die "FATAL:Not a float:$z2"; fi;
55
56 # Calculate distances
57 dist_xyz_eq="sqrt( ($x2 - $x1)^2 + ($y2 - $y1)^2 + ($z2 - $x1)^2 )";
58 dist_xyz="$(printf "%s\n" "$dist_xyz_eq" | bc -l;)";
59 #declare -p dist_xyz_eq dist_xyz; # debug
60
61 dist_xz_eq=" sqrt( ($x2 - $x1)^2 + ($z2 - $z1)^2 ) ";
62 dist_xz="$(printf "%s\n" "$dist_xz_eq" | bc -l;)";
63 declare -p dist_xz_eq dist_xz; # debug
64
65 printf "dist_xyz:%s\n" "$dist_xyz";
66 printf "dist_xz:%s\n" "$dist_xz";
67}; # Main program
68
69main "$@";