Merge remote-tracking branch 'gui/main' into merge-gui-and-server

This commit is contained in:
lucas lelievre committed 2022-11-13 02:27:28 +01:00
commit ae94de39b1
430 files changed
+44297 -50

No files matched your search

+672
View File
@@ -0,0 +1,672 @@
package io.eiren.math;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.math.Vector4f;
public class FloatMath {
public static final float PI = (float) Math.PI;
public static final float TWO_PI = (float) (Math.PI * 2);
public static final float ANGLE_EPSILON = 0.028f; // in degrees (float
// epsilon for sin/cos)
public static final float ANGLE_EPSILON_RAD = toRad(ANGLE_EPSILON);
public static final float ZERO_TOLERANCE_F = FastMath.ZERO_TOLERANCE;
public static final double ZERO_TOLERANCE_D = 0.0001d;
public static final float SQRT_TWO = (float) Math.sqrt(2f);
public static final float INV_SQRT_TWO = 1f / SQRT_TWO;
public static final float SQRT_THREE = (float) Math.sqrt(3f);
public static final float INV_SQRT_THREE = 1f / SQRT_THREE;
public static final float TWO_FPI = PI * 2;
public static final float SIN_75_DEG = 0.965926f;
public static final float SIN_60_DEG = 0.866025f;
public static final float SIN_45_DEG = 0.707107f;
public static final float SIN_30_DEG = 0.5f;
public static final float SIN_15_DEG = 0.258819f;
public static final float COS_75_DEG = 0.258819f;
public static final float COS_60_DEG = 0.5f;
public static final float COS_45_DEG = 0.707107f;
public static final float COS_30_DEG = 0.866025f;
public static final float COS_15_DEG = 0.965926f;
public static final int TEN_BITS = ~(~0 << 10);
public static final int TENTH_BIT = 1 << 10;
public static final int TEN_BITS_MAX = ~(~0 << 9);
public static final int TEN_BITS_MAX_UNSIGNED = ~(~0 << 10);
public static final int TWO_BITS = ~(~0 << 2);
public static final int SECOND_BIT = 1 << 2;
public static final int TWO_BITS_MAX = ~(~0 << 1);
public static final int TWO_BITS_MAX_UNSIGNED = ~(~0 << 2);
public static float roundIfZero(float x) {
return Math.abs(x) < ZERO_TOLERANCE_F ? 0.0f : x;
}
public static boolean equalsToZero(float x) {
return Math.abs(x) < ZERO_TOLERANCE_F;
}
public static boolean lessThanZero(float x) {
return (x < -ZERO_TOLERANCE_F);
}
public static boolean lessOrEqualsToZero(float x) {
return (x < ZERO_TOLERANCE_F);
}
public static boolean greaterThanZero(float x) {
return (x > ZERO_TOLERANCE_F);
}
public static boolean greaterOrEqualsToZero(float x) {
return (x > -ZERO_TOLERANCE_F);
}
public static boolean equalsToZero(float x, float epsilon) {
return Math.abs(x) < epsilon;
}
public static boolean equalsWithEpsilon(float x, float y) {
return Math.abs(x - y) < ZERO_TOLERANCE_F;
}
public static boolean equalsWithEpsilon(float x, float y, float epsilon) {
return Math.abs(x - y) < epsilon;
}
public static boolean lessWithEpsilon(float x, float y) {
return (x < y - ZERO_TOLERANCE_F);
}
public static boolean lessOrEqualsWithEpsilon(float x, float y) {
return (x < y + ZERO_TOLERANCE_F);
}
public static boolean lessWithEpsilon(float x, float y, float epsilon) {
return (x < y - epsilon);
}
public static boolean lessOrEqualsWithEpsilon(float x, float y, float epsilon) {
return (x < y + epsilon);
}
public static boolean greaterWithEpsilon(float x, float y) {
return (x > y + ZERO_TOLERANCE_F);
}
public static boolean greaterOrEqualsWithEpsilon(float x, float y) {
return (x > y - ZERO_TOLERANCE_F);
}
public static boolean greaterWithEpsilon(float x, float y, float epsilon) {
return (x > y + epsilon);
}
public static boolean greaterOrEqualsWithEpsilon(float x, float y, float epsilon) {
return (x > y - epsilon);
}
public static double roundIfZero(double x) {
return Math.abs(x) < ZERO_TOLERANCE_D ? 0.0d : x;
}
public static boolean equalsToZero(double x) {
return Math.abs(x) < ZERO_TOLERANCE_D;
}
public static boolean equalsWithEpsilon(double x, double y) {
return Math.abs(x - y) < ZERO_TOLERANCE_D;
}
public static boolean lessWithEpsilon(double x, double y) {
return (x < y - ZERO_TOLERANCE_D);
}
public static boolean lessOrEqualsWithEpsilon(double x, double y) {
return (x < y + ZERO_TOLERANCE_D);
}
public static boolean greaterWithEpsilon(double x, double y) {
return (x > y + ZERO_TOLERANCE_D);
}
public static boolean greaterOrEqualsWithEpsilon(double x, double y) {
return (x > y - ZERO_TOLERANCE_D);
}
public static float toDegrees(float angrad) {
return angrad * 180.0f / PI;
}
public static float toRad(float deg) {
return deg / 180.0f * PI;
}
public static boolean radEqual(float angle1, float angle2) {
float diff = clampRad(angle1 - angle2);
return Math.abs(diff) < ANGLE_EPSILON_RAD;
}
public static boolean degreesEqual(float angle1, float angle2) {
float diff = clampDegrees(angle1 - angle2);
return Math.abs(diff) < ANGLE_EPSILON;
}
/**
* @deprecated use {@link #normalizeRad(float)}
*/
@Deprecated
public static float clampRad(float angle) {
return normalizeRad(angle);
}
public static float normalizeRad(float angle) {
return FastMath.normalize(angle, -FastMath.PI, FastMath.PI);
}
/**
* @deprecated use {@link #normalizeDegrees(float)}
*/
@Deprecated
public static float clampDegrees(float angle) {
return normalizeDegrees(angle);
}
public static float normalizeDegrees(float angle) {
return FastMath.normalize(angle, -180f, 180f);
}
public static float animateEase(float t) {
// Special case of Bezier interpolation (p0 = p1 = 0, p2 = p3 = 1)
return (3.0f - 2.0f * t) * t * t;
}
public static float animateEaseIn(float t) {
return t * t;
}
/**
* Lineary remaps value from the source interval to the target interval.
* <a href="https://en.wikipedia.org/wiki/Linear_interpolation">details</a>
*/
public static float mapValue(
float value,
float sourceStart,
float sourceEnd,
float targetStart,
float targetEnd
) {
return targetStart
+ (value - sourceStart) * (targetEnd - targetStart) / (sourceEnd - sourceStart);
}
/**
* Clamps the given value and remaps to the target interval.
* <p>
* Note the source interval values should be sorted.
*/
public static float mapValueWithClampBefore(
float value,
float sourceBottom,
float sourceTop,
float targetBottom,
float targetTop
) {
return mapValue(
clamp(value, sourceBottom, sourceTop),
sourceBottom,
sourceTop,
targetBottom,
targetTop
);
}
/**
* Remaps the given value to the target interval and clamps.
* <p>
* Note the target interval values should be sorted.
*/
public static float mapValueWithClampAfter(
float value,
float sourceBottom,
float sourceTop,
float targetBottom,
float targetTop
) {
return clamp(
mapValue(value, sourceBottom, sourceTop, targetBottom, targetTop),
targetBottom,
targetTop
);
}
public static float smoothstep(float edge0, float edge1, float x) {
// Scale, bias and saturate x to 0..1 range
x = FastMath.clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
// Evaluate polynomial
return x * x * (3f - 2f * x);
}
public static float smootherstep(float edge0, float edge1, float x) {
// Scale, and clamp x to 0..1 range
x = FastMath.clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
// Evaluate polynomial
return x * x * x * (x * (x * 6f - 15f) + 10f);
}
/**
* Applies linear contrast (with clamping).
*
* @param t - input value in range (0..1)
* @param k - contrast factor in range (-1..1):
* <ul>
* <li>1.0 - maximal contrast</li>
* <li><b>0.0</b> - bypass (returns input value)</li>
* <li>-1.0 - minimal contrast (returns 0.5f for any input)</li>
* </ul>
* @return contrasted value in range (0..1)
*/
public static float contrastLinear(float t, float k) {
float x = 2f * t - 1f; // -1..1
float gamma = (1f + k) / (1f - k);
float f = FastMath.clamp(gamma * x, -1f, 1f); // -1..1
return 0.5f * (f + 1f); // 0..1
}
/**
* Applies non-linear contrast by power function.
*
* @param t - input value in range (0..1)
* @param k - contrast factor in range (-1..1) exclusive:
* <ul>
* <li>0.999 - maximal contrast</li>
* <li>0.0 - bypass (returns input value)</li>
* <li>-0.999 - minimal contrast</li>
* </ul>
* @return contrasted value in range (0..1)
*/
public static float contrastPower(float t, float k) {
float x = 2f * t - 1f; // -1..1
float gamma = (1f - k) / (1f + k);
float f = FastMath.sign(x) * FastMath.pow(FastMath.abs(x), gamma); // -1..1
return 0.5f * (f + 1f); // 0..1
}
/**
* Applies non-linear contrast by square splines.
*
* @param t - input value in range (0..1)
* @param k - contrast factor in range (-1..1):
* <ul>
* <li>1.0 - maximal contrast</li>
* <li>0.0 - bypass (returns input value)</li>
* <li>-1.0 - minimal contrast</li>
* </ul>
* @return contrasted value in range (0..1)
*/
public static float contrastQuadricSpline(float t, float k) {
float x = 2f * t - 1f; // -1..1
float f = x * (1f + k * (1f - FastMath.abs(x))); // -1..1
return 0.5f * (f + 1f); // 0..1
}
/**
* Applies non-linear contrast by square splines inverted function.
*
* @param t - input value in range (0..1)
* @param k - contrast factor in range (-2..2):
* <ul>
* <li>2.0 - maximal contrast</li>
* <li>0.0 - bypass (returns input value)</li>
* <li>-2.0 - minimal contrast</li>
* </ul>
* @return contrasted value in range (0..1)
*/
public static float contrastInvertQuadricSpline(float t, float k) {
float x = 2f * t - 1f; // -1..1
float g;
if (k > 0) {
g = FastMath.sign(x) * FastMath.sqrt(FastMath.abs(x)) - 2f * x;
} else {
g = FastMath.sign(x) * (FastMath.sqrt(1f - FastMath.abs(x)) - 1f);
}
float f = (1f + k) * x + k * g; // -1..1
return 0.5f * (f + 1f); // 0..1
}
/**
* Applies non-linear contrast by cubic splines.
*
* @param t - input value in range (0..1)
* @param k - contrast factor in range (-1..1):
* <ul>
* <li>1.0 - maximal contrast</li>
* <li>0.0 - bypass (returns input value)</li>
* <li>-1.0 - minimal contrast</li>
* </ul>
* @return contrasted value in range (0..1)
*/
public static float contrastCubicSpline(float t, float k) {
float x = 2f * t - 1f; // -1..1
float f = x * (1f + FastMath.abs(k) * (x * x - 1f));
if (k < 0)
f -= x * 3f * k * (1f - FastMath.abs(x));
return 0.5f * (f + 1f); // 0..1
}
public static float fraction(float f) {
return f - (int) f;
}
public static double fraction(double d) {
return d - (long) d;
}
/**
* @deprecated Do not copy {@link Math} methods.
*/
@Deprecated
public static float min(float a, float b) {
return a > b ? b : a;
}
public static float min(float a, float b, float c) {
return Math.min(Math.min(a, b), c);
}
public static float min(float a, float b, float c, float d) {
return Math.min(Math.min(a, b), Math.min(c, d));
}
/**
* @deprecated Do not copy {@link Math} methods.
*/
@Deprecated
public static float max(float a, float b) {
return a > b ? a : b;
}
public static float max(float a, float b, float c) {
return Math.max(Math.max(a, b), c);
}
public static float max(float a, float b, float c, float d) {
return Math.max(Math.max(a, b), Math.max(c, d));
}
public static float cos(float value) {
return (float) Math.cos(value);
}
public static float sin(float value) {
return (float) Math.sin(value);
}
public static float ceil(float value) {
return (float) Math.ceil(value);
}
public static float floor(float value) {
return (float) Math.floor(value);
}
public static float pow(float value, float power) {
return (float) Math.pow(value, power);
}
/**
* @deprecated Do not copy {@link Math} methods.
*/
@Deprecated
public static float abs(float value) {
return (float) Math.abs(value);
}
/**
* @deprecated Do not copy {@link Math} methods.
*/
@Deprecated
public static float round(float value) {
return (float) Math.round(value);
}
public static float sqrt(float value) {
return (float) Math.sqrt(value);
}
public static float distance(float x0, float y0, float z0, float x1, float y1, float z1) {
return distance(x1 - x0, y1 - y0, z1 - z0);
}
public static float distance(float x, float y, float z) {
return sqrt(sqrDistance(x, y, z));
}
public static float sqrDistance(float x, float y, float z) {
return x * x + y * y + z * z;
}
public static float distance(float x, float y) {
return sqrt(sqrDistance(x, y));
}
public static float sqrDistance(float x, float y) {
return x * x + y * y;
}
public static float sqrDistance(Vector3f v, float x1, float y1, float z1) {
return sqrDistance(x1 - v.x, y1 - v.y, z1 - v.z);
}
public static float sqrDistance(float x0, float y0, float z0, float x1, float y1, float z1) {
return sqrDistance(x1 - x0, y1 - y0, z1 - z0);
}
public static float hypot(float x, float y) {
return FastMath.sqrt(x * x + y * y);
}
public static float hypot(float x, float y, float z) {
return FastMath.sqrt(x * x + y * y + z * z);
}
/**
* The same as FastMath.clamp
*/
public static float clamp(float value, float min, float max) {
if (value <= min)
return min;
if (value >= max)
return max;
return value;
}
public static Vector3f int2101010RevToFloats(int packedValue, Vector3f store) {
if (store == null)
store = new Vector3f();
store.x = packedValue & TEN_BITS_MAX;
if ((packedValue & TENTH_BIT) != 0)
store.x *= -1;
store.y = (packedValue >>> 10) & TEN_BITS_MAX;
if ((packedValue & (TENTH_BIT << 10)) != 0)
store.y *= -1;
store.z = (packedValue >>> 20) & TEN_BITS_MAX;
if ((packedValue & (TENTH_BIT << 20)) != 0)
store.z *= -1;
return store;
}
public static int floatToInt210101Rev(Vector3f values) {
int store = 0;
store |= ((int) values.x) & TEN_BITS_MAX;
if (values.x < 0)
store |= TENTH_BIT;
store |= (((int) values.y) & TEN_BITS_MAX) << 10;
if (values.y < 0)
store |= TENTH_BIT << 10;
store |= (((int) values.z) & TEN_BITS_MAX) << 20;
if (values.z < 0)
store |= TENTH_BIT << 20;
return store;
}
public static int floatToInt210101RevNormalized(Vector3f values) {
int store = 0;
store |= ((int) (values.x * TEN_BITS)) & TEN_BITS_MAX;
if (values.x < 0)
store |= TENTH_BIT;
store |= (((int) (values.y * TEN_BITS)) & TEN_BITS_MAX) << 10;
if (values.y < 0)
store |= TENTH_BIT << 10;
store |= (((int) (values.z * TEN_BITS)) & TEN_BITS_MAX) << 20;
if (values.z < 0)
store |= TENTH_BIT << 20;
return store;
}
public static int floatToUnsignedInt210101Rev(Vector3f values) {
int store = 0;
store |= ((int) values.x) & TEN_BITS;
store |= (((int) values.y) & TEN_BITS) << 10;
store |= (((int) values.z) & TEN_BITS) << 20;
return store;
}
public static int floatToUnsignedInt210101RevNormalized(Vector3f values) {
int store = 0;
store |= ((int) (values.x * TEN_BITS)) & TEN_BITS;
store |= (((int) (values.y * TEN_BITS)) & TEN_BITS) << 10;
store |= (((int) (values.z * TEN_BITS)) & TEN_BITS) << 20;
return store;
}
public static int floatToInt210101Rev(float x, float y, float z) {
int store = 0;
store |= ((int) x) & TEN_BITS_MAX;
if (x < 0)
store |= TENTH_BIT;
store |= (((int) y) & TEN_BITS_MAX) << 10;
if (y < 0)
store |= TENTH_BIT << 10;
store |= (((int) z) & TEN_BITS_MAX) << 20;
if (z < 0)
store |= TENTH_BIT << 20;
return store;
}
public static int floatToUnsignedInt210101Rev(float x, float y, float z) {
int store = 0;
store |= ((int) x) & TEN_BITS;
store |= (((int) y) & TEN_BITS) << 10;
store |= (((int) z) & TEN_BITS) << 20;
return store;
}
public static Vector4f int2101010RevToFloats(int packedValue, Vector4f store) {
if (store == null)
store = new Vector4f();
store.x = packedValue & TEN_BITS_MAX;
if ((packedValue & TENTH_BIT) != 0)
store.x *= -1;
store.y = (packedValue >>> 10) & TEN_BITS_MAX;
if ((packedValue & (TENTH_BIT << 10)) != 0)
store.y *= -1;
store.z = (packedValue >>> 20) & TEN_BITS_MAX;
if ((packedValue & (TENTH_BIT << 20)) != 0)
store.z *= -1;
store.w = (packedValue >>> 30) & TWO_BITS_MAX;
if ((packedValue & (SECOND_BIT << 30)) != 0)
store.w *= -1;
return store;
}
public static int floatToInt210101Rev(Vector4f values) {
int store = 0;
store |= ((int) values.x) & TEN_BITS_MAX;
if (values.x < 0)
store |= TENTH_BIT;
store |= (((int) values.y) & TEN_BITS_MAX) << 10;
if (values.y < 0)
store |= TENTH_BIT << 10;
store |= (((int) values.z) & TEN_BITS_MAX) << 20;
if (values.z < 0)
store |= TENTH_BIT << 20;
store |= (((int) values.z) & TWO_BITS_MAX) << 30;
if (values.w < 0)
store |= SECOND_BIT << 30;
return store;
}
public static int floatToUnsignedInt210101Rev(Vector4f values) {
int store = 0;
store |= ((int) values.x) & TEN_BITS;
store |= (((int) values.y) & TEN_BITS) << 10;
store |= (((int) values.z) & TEN_BITS) << 20;
store |= (((int) values.z) & TWO_BITS) << 30;
return store;
}
public static Vector3f unsignedInt2101010RevToFloats(int packedValue, Vector3f store) {
if (store == null)
store = new Vector3f();
store.x = packedValue & TEN_BITS;
store.y = (packedValue >>> 10) & TEN_BITS;
store.z = (packedValue >>> 20) & TEN_BITS;
return store;
}
public static Vector4f unsignedInt2101010RevToFloats(int packedValue, Vector4f store) {
if (store == null)
store = new Vector4f();
store.x = packedValue & TEN_BITS;
store.y = (packedValue >>> 10) & TEN_BITS;
store.z = (packedValue >>> 20) & TEN_BITS;
store.w = (packedValue >>> 30) & TWO_BITS;
return store;
}
public static Vector3f int2101010RevNormalizedToFloats(int packedValue, Vector3f store) {
store = int2101010RevToFloats(packedValue, store);
store.x /= TEN_BITS_MAX;
store.y /= TEN_BITS_MAX;
store.z /= TEN_BITS_MAX;
return store;
}
public static Vector4f int2101010RevNormalizedToFloats(int packedValue, Vector4f store) {
store = int2101010RevToFloats(packedValue, store);
store.x /= TEN_BITS_MAX;
store.y /= TEN_BITS_MAX;
store.z /= TEN_BITS_MAX;
store.w /= TWO_BITS_MAX;
return store;
}
public static Vector3f unsignedInt2101010RevNormalizedToFloats(
int packedValue,
Vector3f store
) {
store = unsignedInt2101010RevToFloats(packedValue, store);
store.x /= TEN_BITS;
store.y /= TEN_BITS;
store.z /= TEN_BITS;
return store;
}
public static Vector4f unsignedInt2101010RevNormalizedToFloats(
int packedValue,
Vector4f store
) {
store = unsignedInt2101010RevToFloats(packedValue, store);
store.x /= TEN_BITS;
store.y /= TEN_BITS;
store.z /= TEN_BITS;
store.w /= TWO_BITS;
return store;
}
}
+257
View File
@@ -0,0 +1,257 @@
package io.eiren.math;
import com.jme3.math.Vector3f;
public class Vector3d implements Cloneable {
public double x;
public double y;
public double z;
public Vector3d() {
}
public Vector3d(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3d(double x1, double y1, double z1, double x2, double y2, double z2) {
this.x = x2 - x1;
this.y = y2 - y1;
this.z = z2 - z1;
}
public Vector3d(Vector3f src) {
this(src.x, src.y, src.z);
}
public Vector3d set(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
public Vector3d set(Vector3d v) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
}
public Vector3d add(double addX, double addY, double addZ) {
return new Vector3d(this.x + addX, this.y + addY, this.z + addZ);
}
public Vector3d addLocal(Vector3d vec) {
return addLocal(vec.x, vec.y, vec.z);
}
public Vector3d addLocal(double addX, double addY, double addZ) {
x += addX;
y += addY;
z += addZ;
return this;
}
public Vector3d substract(double subX, double subY, double subZ) {
return new Vector3d(this.x - subX, this.y - subY, this.z - subZ);
}
public Vector3d substractLocal(Vector3d vec) {
if (null == vec) {
return null;
}
x -= vec.x;
y -= vec.y;
z -= vec.z;
return this;
}
public Vector3d substractLocal(double subX, double subY, double subZ) {
x -= subX;
y -= subY;
z -= subZ;
return this;
}
public Vector3d negate() {
return new Vector3d(-x, -y, -z);
}
public Vector3d negateLocal() {
x = -x;
y = -y;
z = -z;
return this;
}
public Vector3d mult(double scalar) {
return new Vector3d(x * scalar, y * scalar, z * scalar);
}
public Vector3d multLocal(double scalar) {
x *= scalar;
y *= scalar;
z *= scalar;
return this;
}
public Vector3d divide(double scalar) {
return new Vector3d(x / scalar, y / scalar, z / scalar);
}
public Vector3d divideLocal(double scalar) {
x /= scalar;
y /= scalar;
z /= scalar;
return this;
}
public double dot(Vector3d v) {
return x * v.x + y * v.y + z * v.z;
}
public double dot(double vx, double vy, double vz) {
return x * vx + y * vy + z * vz;
}
public Vector3d cross(Vector3d other, Vector3d result) {
if (result == null)
result = new Vector3d();
double resX = ((y * other.z) - (z * other.y));
double resY = ((z * other.x) - (x * other.z));
double resZ = ((x * other.y) - (y * other.x));
result.set(resX, resY, resZ);
return result;
}
@Override
public Vector3d clone() {
return new Vector3d(this.x, this.y, this.z);
}
public Vector3d normalize() {
double length = x * x + y * y + z * z;
if (length != 1.0 && length != 0.0) {
double invLength = 1.0 / Math.sqrt(length);
return mult(invLength);
}
return clone();
}
public Vector3d normalizeLocal() {
double length = x * x + y * y + z * z;
if (length != 1.0 && length != 0.0) {
length = Math.sqrt(length);
double invLength = 1.0 / length;
x *= invLength;
z *= invLength;
y *= invLength;
}
return this;
}
public Vector3f toVector3f() {
return new Vector3f((float) x, (float) y, (float) z);
}
public double length() {
return Math.sqrt(x * x + y * y + z * z);
}
public double lengthSquared() {
return x * x + y * y + z * z;
}
@Override
public String toString() {
return new StringBuilder("Vector3D{")
.append(x)
.append(',')
.append(y)
.append(',')
.append(z)
.append('}')
.toString();
}
public void rotateAroundX(float f) {
double f1 = Math.cos(f);
double f2 = Math.sin(f);
double d = x;
double d1 = y * f1 + z * f2;
double d2 = z * f1 - y * f2;
x = (float) d;
y = (float) d1;
z = (float) d2;
}
public void rotateAroundY(float f) {
double f1 = Math.cos(f);
double f2 = Math.sin(f);
double d = x * f1 + z * f2;
double d1 = y;
double d2 = z * f1 - x * f2;
x = (float) d;
y = (float) d1;
z = (float) d2;
}
public double distanceTo(Vector3d vec3d) {
return Math.sqrt(squaredDistance(vec3d));
}
public double squaredDistance(Vector3d point) {
return squaredDistance(point.x, point.y, point.z);
}
public double squaredDistance(double toX, double toY, double toZ) {
return (this.x - toX) * (this.x - toX)
+ (this.y - toY) * (this.y - toY)
+ (this.z - toZ) * (this.z - toZ);
}
public Vector3d add(Vector3d dir) {
return add(dir.x, dir.y, dir.z);
}
public Vector3d substract(Vector3d dir) {
return substract(dir.x, dir.y, dir.z);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(z);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector3d other = (Vector3d) obj;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))
return false;
if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z))
return false;
return true;
}
}
@@ -0,0 +1,130 @@
package io.eiren.util;
import java.beans.ConstructorProperties;
import com.jme3.system.NanoTimer;
/**
* This timer accumulate measured TPF and returns average/min/max FPS value
*/
public class BufferedTimer extends NanoTimer {
private final float measureInterval;
private float averageTpf;
private float averageFps;
private float averageFrameRenderTime;
private float sumFrameRenderTime;
private float sumTpf;
private float minFpsCurrent;
private float maxFpsCurrent;
private float maxFps;
private float minFps;
private int count;
private boolean measured = false;
/**
* Measure average tpf over the provided inverval in seconds
*
* @param measureInterval interval to measure averages over
*/
public BufferedTimer(float measureInterval) {
averageFps = 0;
sumTpf = 0;
count = 0;
this.measureInterval = measureInterval;
}
public float getAverageFPS() {
return averageFps;
}
public float getMinFPS() {
return minFps;
}
public float getMaxFPS() {
return maxFps;
}
public void addRenderTime(float renderTime) {
sumFrameRenderTime += renderTime;
}
public float getAverageFrameRenderTime() {
return averageFrameRenderTime;
}
public boolean isMeasured() {
if (measured) {
measured = false;
return true;
}
return false;
}
public TimerSample getCurrentData() {
return new TimerSample(getFrameRate(), minFps, maxFps, averageFps);
}
@Override
public void update() {
super.update();
// Accumulate instant rate
sumTpf += getTimePerFrame();
float fps = getFrameRate();
if (fps < minFpsCurrent)
minFpsCurrent = fps;
if (fps > maxFpsCurrent)
maxFpsCurrent = fps;
++count;
// Calculate results once per measure interval
if (!measured || sumTpf > measureInterval) {
// Average results
averageTpf = sumTpf / count;
averageFps = 1.0f / averageTpf;
averageFrameRenderTime = sumFrameRenderTime / count;
minFps = minFpsCurrent;
maxFps = maxFpsCurrent;
// Reset counter
sumTpf = 0;
sumFrameRenderTime = 0;
minFpsCurrent = Float.MAX_VALUE;
maxFpsCurrent = 0;
count = 0;
measured = true;
}
}
public static class TimerSample {
public float fps;
public float minFps;
public float maxFps;
public float averageFps;
@ConstructorProperties({ "fps", "minFps", "maxFps", "averageFps" })
public TimerSample(float fps, float minFps, float maxFps, float averageFps) {
this.fps = fps;
this.minFps = minFps;
this.maxFps = maxFps;
this.averageFps = averageFps;
}
public float getFps() {
return fps;
}
public float getMinFps() {
return minFps;
}
public float getMaxFps() {
return maxFps;
}
public float getAverageFps() {
return averageFps;
}
}
}
+41
View File
@@ -0,0 +1,41 @@
package io.eiren.util;
import java.awt.Image;
import java.awt.Toolkit;
import java.lang.reflect.Method;
import java.util.List;
public class MacOSX {
public static void setIcons(List<? extends Image> icons) {
try {
Class<?> applicationClass = Class.forName("com.apple.eawt.Application");
Method m = applicationClass.getDeclaredMethod("getApplication");
Object application = m.invoke(null);
m = application.getClass().getDeclaredMethod("setDockIconImage", Image.class);
m.invoke(application, icons.get(icons.size() - 1));
} catch (Exception e) {}
}
public static void setTitle(String title) {
try {
Class<?> applicationClass = Class.forName("com.apple.eawt.Application");
Method m = applicationClass.getDeclaredMethod("getApplication");
Object application = m.invoke(null);
m = application.getClass().getDeclaredMethod("setDockIconImage", String.class);
m.invoke(application, title);
} catch (Exception e) {}
}
public static boolean hasRetinaDisplay() {
Object obj = Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor");
if (obj instanceof Float) {
Float f = (Float) obj;
int scale = f.intValue();
return (scale == 2); // 1 indicates a regular mac display.
}
return false;
}
}
@@ -0,0 +1,47 @@
package io.eiren.util;
import java.io.File;
public enum OperatingSystem {
//@formatter:off
LINUX("linux", new String[]{"linux", "unix"}),
WINDOWS("windows", new String[]{"win"}),
OSX("osx", new String[]{"mac"}),
UNKNOWN("unknown", new String[0]);
//@fomatter: on
private final String[] aliases;
public final String name;
private static OperatingSystem currentPlatform;
private OperatingSystem(String name, String[] aliases) {
this.aliases = aliases;
this.name = name;
}
public static String getJavaExecutable(boolean forceConsole) {
String separator = System.getProperty("file.separator");
String path = System.getProperty("java.home") + separator + "bin" + separator;
if(getCurrentPlatform() == WINDOWS) {
if(!forceConsole && new File(path + "javaw.exe").isFile())
return path + "javaw.exe";
return path + "java.exe";
}
return path + "java";
}
public static OperatingSystem getCurrentPlatform() {
if(currentPlatform != null)
return currentPlatform;
String osName = System.getProperty("os.name").toLowerCase();
for(OperatingSystem os : values()) {
for(String alias : os.aliases) {
if(osName.contains(alias))
return currentPlatform = os;
}
}
return UNKNOWN;
}
}
@@ -0,0 +1,35 @@
package io.eiren.util;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class StringUtils {
private static char DECIMAL_SEP;
public static char getDecimalSeparator() {
if (DECIMAL_SEP == '\u0000') {
final Locale l = Locale.getDefault(Locale.Category.FORMAT);
// Formatter.java always use "." in the Locale.US
DECIMAL_SEP = (l == null || l.equals(Locale.US)
? '.'
: DecimalFormatSymbols.getInstance(l).getDecimalSeparator());
}
return DECIMAL_SEP;
}
public static String prettyNumber(float f) {
return prettyNumber(f, 4);
}
public static String prettyNumber(float f, int numDigits) {
String str = String.format("%." + numDigits + "f", f);
if (numDigits != 0)
str = org.apache.commons.lang3.StringUtils.stripEnd(str, "0");
char lastChar = str.charAt(str.length() - 1);
if (lastChar == getDecimalSeparator())
str = str.substring(0, str.length() - 1);
return str;
}
}
+176
View File
@@ -0,0 +1,176 @@
package io.eiren.util;
import java.io.Closeable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Util {
public static void close(Object r) {
try {
if (r != null) {
if (r instanceof Closeable)
((Closeable) r).close();
else if (r instanceof AutoCloseable)
((AutoCloseable) r).close();
}
} catch (Exception e) {}
}
public static void close(Object r1, Object r2) {
close(r1);
close(r2);
}
public static void close(Object... r) {
for (int i = 0; i < r.length; ++i)
try {
if (r[i] != null) {
if (r[i] instanceof Closeable)
((Closeable) r[i]).close();
else if (r[i] instanceof AutoCloseable)
((AutoCloseable) r[i]).close();
}
} catch (Exception e) {}
}
public static void close(AutoCloseable... r) {
for (int i = 0; i < r.length; ++i)
try {
if (r[i] != null)
r[i].close();
} catch (Exception e) {}
}
public static void close(Closeable... r) {
for (int i = 0; i < r.length; ++i)
try {
if (r[i] != null)
r[i].close();
} catch (Exception e) {}
}
/**
* <p>
* Performs a deep toString of provided object. It shows content of arrays,
* collections and maps (trove not supported yet).
* </p>
* <p>
* <b>Highly ineffective, use only for debug.</b>
* </p>
*
* @param object
* @return
*/
public static String toString(Object object) {
if (object == null)
return "null";
StringBuilder buf = new StringBuilder();
elementToString(object, buf, new HashSet<Object>());
return buf.toString();
}
private static void deepToString(Map<Object, Object> m, StringBuilder buf, Set<Object> dejaVu) {
if (m == null) {
buf.append("null");
return;
}
if (m.size() == 0) {
buf.append("{}");
return;
}
dejaVu.add(m);
buf.append('{');
Iterator<Entry<Object, Object>> iterator = m.entrySet().iterator();
boolean has = false;
while (iterator.hasNext()) {
if (has)
buf.append(',');
Entry<Object, Object> e = iterator.next();
elementToString(e.getKey(), buf, dejaVu);
buf.append(':');
elementToString(e.getValue(), buf, dejaVu);
has = true;
}
buf.append('}');
dejaVu.remove(m);
}
private static void deepToString(
Collection<Object> list,
StringBuilder buf,
Set<Object> dejaVu
) {
Object[] array = list.toArray();
deepToString(array, buf, dejaVu);
}
private static void deepToString(Object[] a, StringBuilder buf, Set<Object> dejaVu) {
if (a == null) {
buf.append("null");
return;
}
if (a.length == 0) {
buf.append("[]");
return;
}
dejaVu.add(a);
buf.append('[');
for (int i = 0; i < a.length; i++) {
if (i != 0)
buf.append(',');
Object element = a[i];
elementToString(element, buf, dejaVu);
}
buf.append(']');
dejaVu.remove(a);
}
@SuppressWarnings("unchecked")
private static void elementToString(Object element, StringBuilder buf, Set<Object> dejaVu) {
if (element == null) {
buf.append("null");
} else {
Class<?> eClass = element.getClass();
if (eClass.isArray()) {
if (eClass == byte[].class)
buf.append(Arrays.toString((byte[]) element));
else if (eClass == short[].class)
buf.append(Arrays.toString((short[]) element));
else if (eClass == int[].class)
buf.append(Arrays.toString((int[]) element));
else if (eClass == long[].class)
buf.append(Arrays.toString((long[]) element));
else if (eClass == char[].class)
buf.append(Arrays.toString((char[]) element));
else if (eClass == float[].class)
buf.append(Arrays.toString((float[]) element));
else if (eClass == double[].class)
buf.append(Arrays.toString((double[]) element));
else if (eClass == boolean[].class)
buf.append(Arrays.toString((boolean[]) element));
else { // element is an array of object references
if (dejaVu.contains(element))
buf.append("[...]");
else
deepToString((Object[]) element, buf, dejaVu);
}
} else { // element is non-null and not an array
if (element instanceof Collection)
deepToString((Collection<Object>) element, buf, dejaVu);
else if (element instanceof Map)
deepToString((Map<Object, Object>) element, buf, dejaVu);
else if (element instanceof CharSequence)
buf.append('"').append(element.toString()).append('"');
else
buf.append(element.toString());
}
}
}
}
@@ -0,0 +1,10 @@
package io.eiren.util.ann;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(value = RetentionPolicy.SOURCE)
public @interface AWTThread {
}
@@ -0,0 +1,9 @@
package io.eiren.util.ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ ElementType.FIELD, ElementType.METHOD })
public @interface DebugSwitch {
}
@@ -0,0 +1,19 @@
package io.eiren.util.ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks methods and classes that use unsafe or direct access to memory. Proceed
* with caution.
*
* @author Rena
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface NativeUnsafe {
}
@@ -0,0 +1,30 @@
package io.eiren.util.ann;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* <p>
* Означает необходимость обязательной синхронизации этого меcта во внешних
* методах. В аргументах передаётся название поля для синхронизации.
* </p>
* <p>
* Методы, помеченные данной аннотацией могут вызывать только Thread-Safe
* методы, либо методы, помеченные такой же аннотацией с тем же полем
* синхронизации.
* </p>
* <p>
* Поля, помеченные данной аннотацией должны быть синхронизированны на указанное
* поле при чтении или записи.
* </p>
*
* @see {@link ThreadSafe}, {@link ThreadSecure}, {@link ThreadSafeSingle}
* @author Rena
*/
@Retention(value = RetentionPolicy.SOURCE)
public @interface Synchronize {
String[] value();
}
@@ -0,0 +1,27 @@
package io.eiren.util.ann;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* <p>
* Методы, помеченные этой аннотацией должны быть Thread-Safe.
* </p>
* <p>
* <b>Важно:</b> данные методы гарантированно должны обеспечивать потоковую
* безопасность, но не обязаны обеспечивать концессивность (полноту данных или
* точность синхронизации).
* </p>
* <p>
* Для полностью потоко-безопасных методов можно использовать аннотацию
* {@link ThreadSecure}.
* </p>
*
* @see {@link ThreadSecure}, {@link Synchronize}, {@link ThreadSafeSingle}
* @author Rena
*/
@Retention(value = RetentionPolicy.SOURCE)
public @interface ThreadSafe {
}
@@ -0,0 +1,17 @@
package io.eiren.util.ann;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Соблюдает те же требования что и {@link ThreadSafe} но при условии, что сам
* метод вызывается только из одного потока одновременно.
*
* @see {@link ThreadSafe}, {@link ThreadSecure}, {@link Synchronize}
* @author Rena
*/
@Retention(value = RetentionPolicy.SOURCE)
public @interface ThreadSafeSingle {
}
@@ -0,0 +1,22 @@
package io.eiren.util.ann;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* <p>
* Методы, помеченные этой аннотацией должны быть полностью Thread-Safe.
* </p>
* <p>
* <b>Важно:</b> данные методы гарантированно должны обеспечивать потоковую
* безопасность и консистентность (полноту данных и точность синхронизации).
* </p>
*
* @see {@link ThreadSafe}, {@link Synchronize}, {@link ThreadSafeSingle}
* @author Rena
*/
@Retention(value = RetentionPolicy.SOURCE)
public @interface ThreadSecure {
}
@@ -0,0 +1,39 @@
package io.eiren.util.ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>
* Означает что поле используется для временных или быстро изменяющихся
* переменных.
* </p>
* <p>
* Поле помеченное этой аннотацией не влияет на долгосрочное состояние объекта,
* не участвует в сериализации, вычислении equals и hashCode, не определяет
* поведение объекта для внешнего кода. Поэтому такие поля не должны
* использоваться внешним кодом, их состояние имеет смысл только для самого
* объекта в котором они объявлены.
* </p>
* Примеры:
* <ul>
* <li>Временный объект, который используется в методах для внутренних
* вычислений. Например векторные и матричные вычисления.</li>
* <li>Внутренний флаг для мультитрединга. Например, флаг апдейта графического
* состояния взводимый из игрового потока.</li>
* <li>Выведенное значение или структура, которое инициализируется самим
* объектом по фиксированному правилу. Например, производное значение от
* переменной параметризующей объект. Инициализируемый в конструкторе lookup
* table.</li>
* </ul>
*
* @author tort32
*/
@Retention(value = RetentionPolicy.SOURCE)
@Target({ ElementType.FIELD })
public @interface Transient {
}
@@ -0,0 +1,547 @@
package io.eiren.util.collections;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
@SuppressWarnings("unchecked")
public class FastList<E> extends AbstractList<E>
implements RandomAccess, Cloneable, RemoveAtSwapList<E> {
private static final Object[] emptyArray = new Object[0];
public static final int MAX_ARRAY_SIZE = 2147483639;
protected int size = 0;
protected Object[] array;
public FastList(int capacity) {
array = capacity == 0 ? emptyArray : new Object[capacity];
}
public FastList() {
this(5);
}
public FastList(Collection<E> source) {
this(source.size());
addAll(source);
}
public FastList(FastList<E> source) {
this(source.size);
addAllInternal(0, source.array, source.size);
}
public FastList(E[] source) {
this(source.length);
addAll(source);
}
public FastList(E source) {
this();
add(source);
}
private FastList(Object[] arr, int size) {
this(size);
System.arraycopy(arr, 0, array, 0, size);
this.size = size;
}
private FastList(boolean f) {
}
public static <E> FastList<E> reuseArray(E[] source) {
FastList<E> list = new FastList<>(true);
list.array = source;
list.size = source.length;
return list;
}
private void checkBounds(int index) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(
new StringBuilder("Index: ")
.append(index)
.append(", size: ")
.append(size)
.toString()
);
}
public void ensureCapacity(int numToFit) {
if (array.length < size + numToFit)
grow(numToFit + size);
}
private void grow(int i) {
int j = array.length;
int k = j + (j >> 1);
if (k - i < 0)
k = i;
if (k - 2147483639 > 0)
k = hugeCapacity(i);
array = Arrays.copyOf(array, k);
}
private static int hugeCapacity(int i) {
if (i < 0)
throw new OutOfMemoryError("Huge capacity negative: " + i);
else
return i <= MAX_ARRAY_SIZE ? MAX_ARRAY_SIZE : 2147483647;
}
public void copyInto(Object[] anArray) {
System.arraycopy(array, 0, anArray, 0, size);
}
@Override
public E get(int index) {
checkBounds(index);
return (E) array[index];
}
public E unsafeGet(int index) {
return (E) array[index];
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int size() {
return size;
}
@Override
public int indexOf(Object obj) {
for (int j = 0; j < size; j++)
if (obj == array[j])
return j;
return -1;
}
@Override
public int lastIndexOf(Object obj) {
for (int j = size - 1; j >= 0; j--)
if (obj == array[j])
return j;
return -1;
}
@Override
public boolean contains(Object obj) {
return indexOf(obj) >= 0;
}
public void trimToSize() {
int i = array.length;
if (size < i)
array = Arrays.copyOf(array, size);
}
@Override
public Object[] toArray() {
return Arrays.copyOf(array, size);
}
@Override
public <T> T[] toArray(T aobj[]) {
if (aobj.length < size)
return (T[]) Arrays.copyOf(array, size, aobj.getClass());
System.arraycopy(array, 0, aobj, 0, size);
if (aobj.length > size)
aobj[size] = null;
return aobj;
}
@Override
public boolean add(E e) {
ensureCapacity(1);
array[size++] = e;
return true;
}
@Override
public E remove(int i) {
checkBounds(i);
E obj = (E) array[i];
removeInternal(i);
return obj;
}
@Override
public boolean remove(Object obj) {
for (int j = 0; j < size; j++)
if (obj == array[j]) {
removeInternal(j);
return true;
}
return false;
}
public boolean removeAll(Object[] toRemove) {
boolean removed = false;
for (int i = toRemove.length - 1; i >= 0; --i) {
int index = indexOf(toRemove[i]);
if (index != -1) {
removeInternal(index);
removed = true;
}
}
return removed;
}
protected void removeInternal(int i) {
int j = size - i - 1;
if (j > 0)
System.arraycopy(array, i + 1, array, i, j);
array[--size] = null;
}
public void unsafeRemove(int i) {
removeInternal(i);
}
@Override
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
@Override
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.array;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r, elementData, w, size - r);
w += size - r;
}
if (w != size) {
for (int i = w; i < size; i++)
elementData[i] = null;
size = w;
modified = true;
}
}
return modified;
}
@Override
public void clear() {
for (int i = 0; i < size; i++)
array[i] = null;
size = 0;
}
public void fakeClear() {
size = 0;
}
@Override
public boolean addAll(Collection<? extends E> collection) {
return addAll(size, collection);
}
public void addAll(E[] arr) {
addAllInternal(size, arr, arr.length);
}
public void addAll(E[] arr, int limit) {
addAllInternal(size, arr, limit);
}
public void addAll(int index, E[] arr) {
addAllInternal(index, arr, arr.length);
}
public void addAll(int index, E[] arr, int limit) {
addAllInternal(index, arr, limit);
}
private void addAllInternal(int index, Object[] arr, int limit) {
if (limit > arr.length)
limit = arr.length;
if (limit == 1) {
add(index, (E) arr[0]);
} else if (limit > 0) {
if (index >= size) {
ensureCapacity(size - index + limit);
System.arraycopy(arr, 0, array, index, limit);
size = index + limit;
} else {
if (array.length < size + limit) {
Object[] newArray = new Object[size + limit];
System.arraycopy(array, 0, newArray, 0, index);
System.arraycopy(arr, 0, newArray, index, limit);
System.arraycopy(array, index, newArray, index + limit, size - index);
array = newArray;
} else {
System.arraycopy(array, index, array, index + 1, size - index);
System.arraycopy(arr, 0, array, index, limit);
}
size += limit;
}
}
}
@Override
public boolean addAll(int index, Collection<? extends E> collection) {
if (collection.size() > 0) {
if (collection instanceof FastList) {
addAllInternal(
index,
((FastList<? extends E>) collection).array,
collection.size()
);
} else if (collection instanceof RandomAccess) {
Object[] arr = collection.toArray(new Object[collection.size()]);
addAllInternal(index, arr, arr.length);
} else {
if (index >= size) {
ensureCapacity(size - index + collection.size());
Iterator<? extends E> iterator = collection.iterator();
int i = index;
while (iterator.hasNext())
array[i++] = iterator.next();
size = index + collection.size();
} else {
if (array.length < size + collection.size()) {
Object[] newArray = new Object[size + collection.size()];
System.arraycopy(array, 0, newArray, 0, index);
Iterator<? extends E> iterator = collection.iterator();
int i = index;
while (iterator.hasNext())
newArray[i++] = iterator.next();
System
.arraycopy(
array,
index,
newArray,
index + collection.size(),
size - index
);
array = newArray;
} else {
System.arraycopy(array, index, array, index + 1, size - index);
Iterator<? extends E> iterator = collection.iterator();
while (iterator.hasNext())
array[index++] = iterator.next();
}
size += collection.size();
}
}
return true;
}
return false;
}
@Override
public void add(int index, E element) {
if (index >= size) {
ensureCapacity(size - index + 1);
size = index + 1;
array[index] = element;
} else {
if (array.length < size + 1) {
Object[] newArray = new Object[size + 1];
System.arraycopy(array, 0, newArray, 0, index);
newArray[index] = element;
System.arraycopy(array, index, newArray, index + 1, size - index);
array = newArray;
} else {
System.arraycopy(array, index, array, index + 1, size - index);
array[index] = element;
}
size++;
}
}
@Override
public E set(int index, E element) {
checkBounds(index);
E oldValue = (E) array[index];
array[index] = element;
return oldValue;
}
@Override
public FastList<E> clone() {
return new FastList<E>(array, size);
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
final E[] elementData = (E[]) this.array;
final int size = this.size;
for (int i = 0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public E removeAtSwap(int i) {
checkBounds(i);
E obj = (E) array[i];
removeAtSwapInternal(i);
return obj;
}
@Override
public boolean removeAtSwap(Object obj) {
for (int j = 0; j < size; j++)
if (obj == array[j]) {
removeAtSwapInternal(j);
return true;
}
return false;
}
protected void removeAtSwapInternal(int i) {
int j = size - i - 1;
if (j > 0)
array[i] = array[size - 1];
array[--size] = null;
}
@Override
public void removeRange(int i, int toIndex) {
checkBounds(i);
checkBounds(toIndex);
int j = size - toIndex - 1;
if (j > 0)
System.arraycopy(array, toIndex + 1, array, i, j);
size -= (toIndex - i + 1);
Arrays.fill(array, i, toIndex, null);
}
@Override
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
for (int i = 0; i < size; ++i)
set(i, operator.apply(get(i)));
}
@Override
public void sort(Comparator<? super E> c) {
Arrays.sort((E[]) array, 0, size, c);
}
@Override
public int hashCode() {
int hashCode = 1;
for (int i = 0; i < size; ++i) {
Object o = array[i];
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
}
return hashCode;
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(array, 0, size, Spliterator.ORDERED);
}
/**
* Special comodification iterator. <b>Use with caution.</b>
* <p>
* <i>To get element type correctly assign result to reference type
* {@code FastList<T>.SkipFastListIterator}</i>
*
* @return skip iterator to iterate this list in thread-safe manner
*/
public SkipFastListIterator skipIterator() {
return new SkipFastListIterator();
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i = 0; modCount == expectedModCount && i < size; i++) {
final E element = (E) array[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed
// elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i = 0, j = 0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
array[j] = array[i];
}
for (int k = newSize; k < size; k++) {
array[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
public class SkipFastListIterator implements ResettableIterator<E>, SkipIterator<E> {
public int position;
@Override
public boolean hasNext() {
return position < size;
}
@Override
public E next() {
Object[] arr = array;
if (arr.length > position) {
return (E) arr[position++];
}
position++; // Increase position so hasNext() never loops infinitely
return null;
}
@Override
public void reset() {
position = 0;
}
}
}
@@ -0,0 +1,41 @@
package io.eiren.util.collections;
import java.util.Collection;
/**
* FastList that performs Remove-At-Swap on stanard remove() operations.
*
* <p>
* Remove operations breaks ordering of this list
*
* @author Rena
*
* @param <E>
*/
public class RemoveAtSwapFastList<E> extends FastList<E> {
public RemoveAtSwapFastList(int capacity) {
super(capacity);
}
public RemoveAtSwapFastList() {
}
public RemoveAtSwapFastList(Collection<E> source) {
super(source);
}
public RemoveAtSwapFastList(E[] source) {
super(source);
}
public RemoveAtSwapFastList(E source) {
super(source);
}
@Override
protected void removeInternal(int i) {
super.removeAtSwapInternal(i);
}
}
@@ -0,0 +1,11 @@
package io.eiren.util.collections;
import java.util.List;
public interface RemoveAtSwapList<E> extends List<E> {
public E removeAtSwap(int i);
public boolean removeAtSwap(Object object);
}
@@ -0,0 +1,17 @@
package io.eiren.util.collections;
import java.util.Iterator;
/**
* {@link Iterator} that can be reset and iterated from the start by using
* {@link #reset()}
*
* @author Rena
*
* @param <E>
*/
public interface ResettableIterator<E> extends Iterator<E> {
public void reset();
}
@@ -0,0 +1,16 @@
package io.eiren.util.collections;
import java.util.Iterator;
/**
* {@link Iterator} that can return null on {@link #next()} or can lie on
* {@link #hasNext()}. It is <b>not thread-secure!</b>
*
* @param <E> the type of elements returned by this iterator
*/
public interface SkipIterator<E> extends Iterator<E> {
@Override
E next();
}
@@ -0,0 +1,137 @@
package io.eiren.util.logging;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DefaultGLog extends Thread implements IGLog {
private final Logger logger;
public static class LogEntry {
private Level level;
private String message;
private Throwable t;
public LogEntry(Level level, String message, Throwable t) {
this(level, message);
this.t = t;
}
public LogEntry(Level level, String message) {
this.level = level;
this.message = message;
this.t = null;
}
public Level getLevel() {
return level;
}
public String getMessage() {
return message;
}
public Throwable getException() {
return t;
}
}
private final ArrayBlockingQueue<LogEntry> queue = new ArrayBlockingQueue<LogEntry>(50000);
private volatile LoggerRecorder recorder;
@Override
public void info(String message) {
add(new LogEntry(Level.INFO, message));
}
@Override
public void info(String message, Throwable t) {
add(new LogEntry(Level.INFO, message, t));
}
@Override
public void severe(String message) {
add(new LogEntry(Level.SEVERE, message));
}
@Override
public void severe(String message, Throwable t) {
add(new LogEntry(Level.SEVERE, message, t));
}
@Override
public void warning(String message) {
add(new LogEntry(Level.WARNING, message));
}
@Override
public void warning(String message, Throwable t) {
add(new LogEntry(Level.WARNING, message, t));
}
@Override
public void debug(String message) {
add(new LogEntry(Level.INFO, "[DBG] " + message));
}
@Override
public void debug(String message, Throwable t) {
add(new LogEntry(Level.INFO, "[DBG] " + message, t));
}
@Override
public void log(Level level, String message) {
add(new LogEntry(level, message));
}
@Override
public void log(Level level, String message, Throwable t) {
add(new LogEntry(level, message, t));
}
private void add(LogEntry entry) {
try {
queue.put(entry);
} catch (InterruptedException e) {}
try {
if (recorder != null)
recorder.addEntry(entry);
} catch (NullPointerException e) {}
}
@Override
public void setRecorder(LoggerRecorder recorder) {
this.recorder = recorder;
}
@Override
public LoggerRecorder removeRecorder() {
LoggerRecorder lr = this.recorder;
this.recorder = null;
return lr;
}
public DefaultGLog(Logger logger) {
super("Logger");
this.logger = logger;
this.setDaemon(true);
this.setPriority(7);
this.start();
}
@Override
public void run() {
while (true) {
try {
LogEntry log = queue.take();
if (log.t != null)
logger.log(log.level, log.message, log.t);
else
logger.log(log.level, log.message);
} catch (InterruptedException e) {}
}
}
}
@@ -0,0 +1,58 @@
package io.eiren.util.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class FileLogFormatter extends Formatter {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(dateFormat.format(record.getMillis()));
Level localLevel = record.getLevel();
if (localLevel == Level.FINEST)
sb.append(" [FINEST] ");
else if (localLevel == Level.FINER)
sb.append(" [FINER] ");
else if (localLevel == Level.FINE)
sb.append(" [FINE] ");
else if (localLevel == Level.INFO)
sb.append(" [INFO] ");
else if (localLevel == Level.WARNING)
sb.append(" [WARNING] ");
else if (localLevel == Level.SEVERE)
sb.append(" [SEVERE] ");
else
sb.append(" [" + localLevel.getLocalizedName() + "] ");
sb.append(record.getMessage());
sb.append('\n');
Throwable localThrowable = record.getThrown();
if (localThrowable != null) {
StringWriter localStringWriter = new StringWriter();
localThrowable.printStackTrace(new PrintWriter(localStringWriter));
sb.append(localStringWriter.toString());
}
String message = sb.toString();
Object parameters[] = record.getParameters();
if (parameters == null || parameters.length == 0)
return message;
if (
message.indexOf("{0") >= 0
|| message.indexOf("{1") >= 0
|| message.indexOf("{2") >= 0
|| message.indexOf("{3") >= 0
)
return java.text.MessageFormat.format(message, parameters);
return message;
}
}
@@ -0,0 +1,48 @@
package io.eiren.util.logging;
import java.util.logging.Level;
public interface IGLog {
public void info(String message);
public void severe(String message);
public void warning(String message);
public void debug(String message);
public default void info(String message, Throwable t) {
log(Level.INFO, message, t);
}
public default void severe(String message, Throwable t) {
log(Level.SEVERE, message, t);
}
public default void warning(String message, Throwable t) {
log(Level.WARNING, message, t);
}
public default void debug(String message, Throwable t) {
log(Level.INFO, "[DBG] " + message, t);
}
public void log(Level level, String message);
public void log(Level level, String message, Throwable t);
public void setRecorder(LoggerRecorder recorder);
public LoggerRecorder removeRecorder();
static class GLevel extends Level {
private static final long serialVersionUID = -539856764608026895L;
private GLevel(String s, int i) {
super(s, i);
}
}
}
@@ -0,0 +1,136 @@
package io.eiren.util.logging;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogManager {
private static AtomicBoolean initialized = new AtomicBoolean(false);
public static Logger global = Logger.getLogger("");
public static final IGLog log = new DefaultGLog(global);
public static ConsoleHandler handler;
public static void initialize(File logsDir, File mainLogDir)
throws SecurityException, IOException {
if (initialized.getAndSet(true))
return;
FileLogFormatter loc = new FileLogFormatter();
if (mainLogDir != null) {
if (!mainLogDir.exists())
mainLogDir.mkdirs();
File lastLogFile = new File(mainLogDir, "log_last.log");
if (lastLogFile.exists())
lastLogFile.delete();
File mainLog = new File(mainLogDir, "log_main.log");
FileHandler mHandler = new FileHandler(mainLog.getPath(), true);
FileHandler filehandler = new FileHandler(lastLogFile.getPath(), true);
mHandler.setFormatter(loc);
filehandler.setFormatter(loc);
global.addHandler(mHandler);
global.addHandler(filehandler);
}
if (logsDir != null) {
if (!logsDir.exists())
logsDir.mkdir();
if (!logsDir.isDirectory())
System.out.println("*** WARNING *** LOG FOLDER IS NOT A DIRECTORY!");
File currentLog = new File(
logsDir,
"log_"
+ new SimpleDateFormat("yyyy-MM-dd")
.format(Long.valueOf(System.currentTimeMillis()))
+ ".log"
);
FileHandler filehandler2 = new FileHandler(currentLog.getPath(), true);
filehandler2.setFormatter(loc);
global.addHandler(filehandler2);
}
}
public static void replaceMainHandler(ConsoleHandler newHandler) {
handler.close();
global.removeHandler(handler);
handler = newHandler;
global.addHandler(newHandler);
}
public static void addHandler(Handler add) {
global.addHandler(add);
}
public static void removeHandler(Handler remove) {
global.removeHandler(remove);
}
public static void enablePreciseTimestamp() {
handler.setFormatter(new PreciseConsoleLogFormatter());
}
public static void info(String message) {
log.info(message);
}
public static void severe(String message) {
log.severe(message);
}
public static void warning(String message) {
log.warning(message);
}
public static void debug(String message) {
log.debug(message);
}
public static void info(String message, Throwable t) {
log.info(message, t);
}
public static void severe(String message, Throwable t) {
log.severe(message, t);
}
public static void warning(String message, Throwable t) {
log.warning(message, t);
}
public static void debug(String message, Throwable t) {
log.debug(message, t);
}
public static void log(Level level, String message) {
log.log(level, message);
}
public static void log(Level level, String message, Throwable t) {
log.log(level, message, t);
}
static {
boolean hasConsoleHandler = false;
for (Handler h : global.getHandlers()) {
if (h instanceof ConsoleHandler) {
handler = (ConsoleHandler) h;
hasConsoleHandler = true;
}
}
if (!hasConsoleHandler) {
handler = new ConsoleHandler();
global.addHandler(handler);
}
handler.setFormatter(new ShortConsoleLogFormatter());
System.setOut(new PrintStream(new LoggerOutputStream(log, Level.INFO), true));
System.setErr(new PrintStream(new LoggerOutputStream(log, Level.SEVERE), true));
}
}
@@ -0,0 +1,52 @@
package io.eiren.util.logging;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
public class LoggerOutputStream extends ByteArrayOutputStream {
private static final String separator = System.getProperty("line.separator");
private final IGLog logger;
private final Level level;
private final String prefix;
private final StringBuilder buffer = new StringBuilder();
public LoggerOutputStream(IGLog logger, Level level) {
this(logger, level, "");
}
public LoggerOutputStream(IGLog logger, Level level, String prefix) {
super();
this.logger = logger;
this.level = level;
this.prefix = prefix;
}
@Override
public void flush() throws IOException {
synchronized (this) {
super.flush();
String record = this.toString();
super.reset();
if (record.length() > 0) {
buffer.append(record);
if (record.contains(separator)) {
String s = buffer.toString();
String[] split = s.split(separator);
for (int i = 0; i < split.length; ++i)
logger.log(level, prefix + split[i]);
buffer.setLength(0);
// buffer.append(split[split.length - 1]);
}
}
}
}
@Override
public void close() throws IOException {
flush();
}
}
@@ -0,0 +1,23 @@
package io.eiren.util.logging;
import java.util.List;
import io.eiren.util.collections.FastList;
import io.eiren.util.logging.DefaultGLog.LogEntry;
public class LoggerRecorder {
private final List<LogEntry> recorded = new FastList<LogEntry>();
public LoggerRecorder() {
}
public synchronized void addEntry(LogEntry e) {
recorded.add(e);
}
public List<LogEntry> getEntries() {
return recorded;
}
}
@@ -0,0 +1,32 @@
package io.eiren.util.logging;
import java.text.SimpleDateFormat;
import java.util.logging.LogRecord;
/**
* Format message timestamp as time passed from the start with milliseconds.
*/
public class PreciseConsoleLogFormatter extends ShortConsoleLogFormatter {
private final long startMills;
public PreciseConsoleLogFormatter() {
startMills = System.currentTimeMillis();
}
@Override
protected SimpleDateFormat createDateFormat() {
return new SimpleDateFormat("mm:ss.SSS");
}
@Override
protected void buildMessage(StringBuilder builder, LogRecord record) {
builder.append(date.format(record.getMillis() - startMills));
builder.append(" [");
builder.append(record.getLevel().getLocalizedName().toUpperCase());
builder.append("] ");
builder.append(record.getMessage());
builder.append('\n');
}
}
@@ -0,0 +1,58 @@
package io.eiren.util.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class ShortConsoleLogFormatter extends Formatter {
protected final SimpleDateFormat date;
public ShortConsoleLogFormatter() {
this.date = createDateFormat();
}
protected SimpleDateFormat createDateFormat() {
return new SimpleDateFormat("HH:mm:ss");
}
protected void buildMessage(StringBuilder builder, LogRecord record) {
builder.append(date.format(record.getMillis()));
builder.append(" [");
builder.append(record.getLevel().getLocalizedName().toUpperCase());
builder.append("] ");
builder.append(record.getMessage());
builder.append('\n');
}
@Override
public String format(LogRecord record) {
StringBuilder builder = new StringBuilder();
Throwable ex = record.getThrown();
buildMessage(builder, record);
if (ex != null) {
StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
builder.append(writer);
}
String message = builder.toString();
Object parameters[] = record.getParameters();
if (parameters == null || parameters.length == 0)
return message;
if (
message.indexOf("{0") >= 0
|| message.indexOf("{1") >= 0
|| message.indexOf("{2") >= 0
|| message.indexOf("{3") >= 0
)
return java.text.MessageFormat.format(message, parameters);
return message;
}
}
@@ -0,0 +1,23 @@
package io.eiren.yaml;
/**
* Configuration exception.
*
* @author sk89q
*/
public class YamlException extends Exception {
private static final long serialVersionUID = -2442886939908724203L;
public YamlException() {
super();
}
public YamlException(String msg) {
super(msg);
}
public YamlException(String msg, Throwable t) {
super(msg, t);
}
}
+149
View File
@@ -0,0 +1,149 @@
package io.eiren.yaml;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.BaseConstructor;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.representer.Representer;
/**
* YAML configuration loader. To use this class, construct it with path to a
* file and call its load() method. For specifying node paths in the various
* get*() methods, they support SK's path notation, allowing you to select child
* nodes by delimiting node names with periods.
*
* <p>
* For example, given the following configuration file:
* </p>
*
* <pre>
* members:
* - Hollie
* - Jason
* - Bobo
* - Aya
* - Tetsu
* worldguard:
* fire:
* spread: false
* blocks: [cloth, rock, glass]
* sturmeh:
* cool: false
* eats:
* babies: true
* </pre>
*
* <p>
* Calling code could access sturmeh's baby eating state by using
* <code>getBoolean("sturmeh.eats.babies", false)</code>. For lists, there are
* methods such as <code>getStringList</code> that will return a type safe list.
*
* <p>
* This class is currently incomplete. It is not yet possible to get a node.
* </p>
*
* @author sk89q
*/
public class YamlFile extends YamlNode {
private static Representer defaultRepresenter = new Representer();
private Representer representer = defaultRepresenter;
private BaseConstructor constructor = new SafeConstructor();
private DumperOptions options = new DumperOptions();
{
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
}
public YamlFile(Map<String, Object> rootMap) {
super(rootMap);
}
public YamlFile() {
super(new HashMap<String, Object>());
}
public DumperOptions getOptions() {
return options;
}
public void setRepresenter(Representer representer) {
this.representer = representer;
}
public void setBaseConstructor(BaseConstructor constr) {
this.constructor = constr;
}
/**
* Loads the configuration file. All errors are thrown away.
*
* @throws YamlException
*/
public void load(InputStream input) throws YamlException {
try {
Yaml yaml = new Yaml(constructor, representer, options);
read(yaml.load(new UnicodeReader(input)));
} catch (YamlException e) {
throw e;
} catch (Exception e) {
throw new YamlException("Exception while parsing yaml", e);
}
}
/**
* Saves the configuration to disk. All errors are clobbered.
*
* @return true if it was successful
* @throws UnsupportedEncodingException
*/
public void save(OutputStream output) {
Yaml yaml = new Yaml(constructor, representer, options);
try {
yaml.dump(root, new OutputStreamWriter(output, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
@SuppressWarnings("unchecked")
private void read(Object input) throws YamlException {
try {
root = (Map<String, Object>) (input == null ? new HashMap<String, Object>() : input);
} catch (ClassCastException e) {
throw new YamlException(
"Root document must be an key-value structure, recieved: " + input
);
}
}
/**
* This method returns an empty ConfigurationNode for using as a default in
* methods that select a node from a node list.
*
* @return
*/
public static YamlNode getEmptyNode() {
return new YamlNode(new HashMap<String, Object>());
}
public static YamlNode getEmptySortedNode() {
return new YamlNode(new TreeMap<String, Object>());
}
public static void setDefaultRepresenter(Representer r) {
defaultRepresenter = r;
}
}
+642
View File
@@ -0,0 +1,642 @@
package io.eiren.yaml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import io.eiren.util.Util;
/**
* Represents a configuration node.
*
* @author sk89q
*/
public class YamlNode {
public Map<String, Object> root;
public YamlNode(Map<String, Object> root) {
this.root = root;
}
public Object getProperty(String path) {
return getProperty(path, false);
}
/**
* Gets a property at a location. This will either return an Object or null,
* with null meaning that no configuration value exists at that location.
* This could potentially return a default value (not yet implemented) as
* defined by a plugin, if this is a plugin-tied configuration.
*
* @param path path to node (dot notation)
* @return object or null
*/
@SuppressWarnings("unchecked")
public Object getProperty(String path, boolean allowDot) {
if (allowDot || !path.contains(".")) {
Object val = root.get(path);
if (val == null) {
return null;
}
return val;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
if (o == null)
return null;
if (i == parts.length - 1)
return o;
try {
node = (Map<String, Object>) o;
} catch (ClassCastException e) {
return null;
}
}
return null;
}
public void setProperty(String path, Object value) {
setProperty(path, value, false);
}
/**
* Set the property at a location. This will override existing configuration
* data to have it conform to key/value mappings.
*
* @param path
* @param value
*/
@SuppressWarnings("unchecked")
public void setProperty(String path, Object value, boolean allowDot) {
if (value instanceof YamlNode)
value = ((YamlNode) value).root;
if (allowDot || !path.contains(".")) {
root.put(path, value);
return;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
// Found our target!
if (i == parts.length - 1) {
node.put(parts[i], value);
return;
}
if (o == null || !(o instanceof Map)) {
// This will override existing configuration data!
o = new HashMap<String, Object>();
node.put(parts[i], o);
}
node = (Map<String, Object>) o;
}
}
public void merge(YamlNode node) {
merge(node.root);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void merge(Map<String, Object> map) {
Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> e = iterator.next();
if (e.getValue() == null)
continue;
Object old = root.get(e.getKey());
if (old == null) {
root.put(e.getKey(), e.getValue());
} else if (old instanceof Map) {
if (!(e.getValue() instanceof Map)) {
root.put(e.getKey(), e.getValue());
} else {
new YamlNode((Map<String, Object>) old)
.merge((Map<String, Object>) e.getValue());
}
} else if (old instanceof List) {
if (!(e.getValue() instanceof List)) {
root.put(e.getKey(), e.getValue());
} else {
((List) old).addAll((List) e.getValue());
}
}
}
}
/**
* Gets a string at a location. This will either return an String or null,
* with null meaning that no configuration value exists at that location. If
* the object at the particular location is not actually a string, it will
* be converted to its string representation.
*
* @param path path to node (dot notation)
* @return string or null
*/
public String getString(String path) {
Object o = getProperty(path);
if (o == null)
return null;
return o.toString();
}
/**
* Gets a string at a location. This will either return an String or the
* default value. If the object at the particular location is not actually a
* string, it will be converted to its string representation.
*
* @param path path to node (dot notation)
* @param def default value
* @return string or default
*/
public String getString(String path, String def) {
String o = getString(path);
if (o == null)
return def;
return o;
}
public int getInt(String path, int def) {
return getInt(path, def, false);
}
/**
* Gets an integer at a location. This will either return an integer or the
* default value. If the object at the particular location is not actually a
* integer, the default value will be returned. However, other number types
* will be casted to an integer.
*
* @param path path to node (dot notation)
* @param def default value
* @return int or default
*/
public int getInt(String path, int def, boolean allowDot) {
Integer o = castInt(getProperty(path, allowDot));
if (o == null)
return def;
else
return o;
}
public long getLong(String path, long def) {
Long o = castLong(getProperty(path));
if (o == null)
return def;
else
return o;
}
/**
* Gets a double at a location. This will either return an double or the
* default value. If the object at the particular location is not actually a
* double, the default value will be returned. However, other number types
* will be casted to an double.
*
* @param path path to node (dot notation)
* @param def default value
* @return double or default
*/
public double getDouble(String path, double def) {
Double o = castDouble(getProperty(path));
if (o == null)
return def;
else
return o;
}
public float getFloat(String path, float def) {
return getFloat(path, def, false);
}
public float getFloat(String path, float def, boolean allowDot) {
Float o = castFloat(getProperty(path, allowDot));
if (o == null)
return def;
else
return o;
}
/**
* Gets a boolean at a location. This will either return an boolean or the
* default value. If the object at the particular location is not actually a
* boolean, the default value will be returned.
*
* @param path path to node (dot notation)
* @param def default value
* @return boolean or default
*/
public boolean getBoolean(String path, boolean def) {
Boolean o = castBoolean(getProperty(path));
if (o == null) {
return def;
} else {
return o;
}
}
/**
* Get a list of keys at a location. If the map at the particular location
* does not exist or it is not a map, null will be returned.
*
* @param path path to node (dot notation)
* @return list of keys
*/
@SuppressWarnings("unchecked")
public List<String> getKeys(String path) {
if (path == null)
return new ArrayList<String>(root.keySet());
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof Map) {
return new ArrayList<String>(((Map<String, Object>) o).keySet());
} else {
return null;
}
}
/**
* Gets a list of objects at a location. If the list is not defined, null
* will be returned. The node must be an actual list.
*
* @param path path to node (dot notation)
* @return boolean or default
*/
@SuppressWarnings("unchecked")
public List<Object> getList(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof List) {
return (List<Object>) o;
} else {
return null;
}
}
/**
* Gets a list of strings. Non-valid entries will not be in the list. There
* will be no null slots. If the list is not defined, the default will be
* returned. 'null' can be passed for the default and an empty list will be
* returned instead. If an item in the list is not a string, it will be
* converted to a string. The node must be an actual list and not just a
* string.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of strings
*/
public List<String> getStringList(String path, List<String> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<String>(0);
}
List<String> list = new ArrayList<String>();
for (Object o : raw) {
if (o == null) {
continue;
}
list.add(o.toString());
}
return list;
}
/**
* Gets a list of integers. Non-valid entries will not be in the list. There
* will be no null slots. If the list is not defined, the default will be
* returned. 'null' can be passed for the default and an empty list will be
* returned instead. The node must be an actual list and not just an
* integer.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Integer> getIntList(String path, List<Integer> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Integer>(0);
}
List<Integer> list = new ArrayList<Integer>();
for (Object o : raw) {
Integer i = castInt(o);
if (i != null) {
list.add(i);
}
}
return list;
}
/**
* Gets a list of doubles. Non-valid entries will not be in the list. There
* will be no null slots. If the list is not defined, the default will be
* returned. 'null' can be passed for the default and an empty list will be
* returned instead. The node must be an actual list and cannot be just a
* double.
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Double> getDoubleList(String path, List<Double> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Double>(0);
}
List<Double> list = new ArrayList<Double>();
for (Object o : raw) {
Double i = castDouble(o);
if (i != null) {
list.add(i);
}
}
return list;
}
/**
* Gets a list of booleans. Non-valid entries will not be in the list. There
* will be no null slots. If the list is not defined, the default will be
* returned. 'null' can be passed for the default and an empty list will be
* returned instead. The node must be an actual list and cannot be just a
* boolean,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
public List<Boolean> getBooleanList(String path, List<Boolean> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<Boolean>(0);
}
List<Boolean> list = new ArrayList<Boolean>();
for (Object o : raw) {
Boolean tetsu = castBoolean(o);
if (tetsu != null) {
list.add(tetsu);
}
}
return list;
}
/**
* Gets a list of nodes. Non-valid entries will not be in the list. There
* will be no null slots. If the list is not defined, the default will be
* returned. 'null' can be passed for the default and an empty list will be
* returned instead. The node must be an actual node and cannot be just a
* boolean,
*
* @param path path to node (dot notation)
* @param def default value or null for an empty list as default
* @return list of integers
*/
@SuppressWarnings("unchecked")
public List<YamlNode> getNodeList(String path, List<YamlNode> def) {
List<Object> raw = getList(path);
if (raw == null) {
return def != null ? def : new ArrayList<YamlNode>(0);
}
List<YamlNode> list = new ArrayList<YamlNode>();
for (Object o : raw) {
if (o instanceof Map) {
list.add(new YamlNode((Map<String, Object>) o));
}
}
return list;
}
public YamlNode getNode(String path) {
return getNode(path, false);
}
/**
* Get a configuration node at a path. If the node doesn't exist or the path
* does not lead to a node, null will be returned. A node has key/value
* mappings.
*
* @param path
* @return node or null
*/
@SuppressWarnings("unchecked")
public YamlNode getNode(String path, boolean allowDot) {
Object raw = getProperty(path, allowDot);
if (raw instanceof Map) {
return new YamlNode((Map<String, Object>) raw);
}
return null;
}
/**
* Get a list of nodes at a location. If the map at the particular location
* does not exist or it is not a map, null will be returned.
*
* @param path path to node (dot notation)
* @return map of nodes
*/
@SuppressWarnings("unchecked")
public Map<String, YamlNode> getNodes(String path) {
Object o = getProperty(path);
if (o == null) {
return null;
} else if (o instanceof Map) {
Map<String, YamlNode> nodes = new HashMap<String, YamlNode>();
for (Map.Entry<String, Object> entry : ((Map<String, Object>) o).entrySet()) {
if (entry.getValue() instanceof Map) {
nodes.put(entry.getKey(), new YamlNode((Map<String, Object>) entry.getValue()));
}
}
return nodes;
} else {
return null;
}
}
/**
* Casts a value to an integer. May return null.
*
* @param o
* @return
*/
private static Integer castInt(Object o) {
if (o == null) {
return null;
} else if (o instanceof Byte) {
return (int) (Byte) o;
} else if (o instanceof Integer) {
return (Integer) o;
} else if (o instanceof Double) {
return (int) (double) (Double) o;
} else if (o instanceof Float) {
return (int) (float) (Float) o;
} else if (o instanceof Long) {
return (int) (long) (Long) o;
} else {
return null;
}
}
private static Long castLong(Object o) {
if (o == null) {
return null;
} else if (o instanceof Byte) {
return (long) (Byte) o;
} else if (o instanceof Integer) {
return (long) (int) (Integer) o;
} else if (o instanceof Double) {
return (long) (double) (Double) o;
} else if (o instanceof Float) {
return (long) (float) (Float) o;
} else if (o instanceof Long) {
return (Long) o;
} else {
return null;
}
}
/**
* Casts a value to a double. May return null.
*
* @param o
* @return
*/
private static Double castDouble(Object o) {
if (o == null) {
return null;
} else if (o instanceof Float) {
return (double) (Float) o;
} else if (o instanceof Double) {
return (Double) o;
} else if (o instanceof Byte) {
return (double) (Byte) o;
} else if (o instanceof Integer) {
return (double) (Integer) o;
} else if (o instanceof Long) {
return (double) (Long) o;
} else {
return null;
}
}
private static Float castFloat(Object o) {
if (o == null) {
return null;
} else if (o instanceof Float) {
return (Float) o;
} else if (o instanceof Double) {
return ((Double) o).floatValue();
} else if (o instanceof Byte) {
return (float) (Byte) o;
} else if (o instanceof Integer) {
return (float) (Integer) o;
} else if (o instanceof Long) {
return (float) (Long) o;
} else {
return null;
}
}
/**
* Casts a value to a boolean. May return null.
*
* @param o
* @return
*/
private static Boolean castBoolean(Object o) {
if (o == null) {
return null;
} else if (o instanceof Boolean) {
return (Boolean) o;
} else {
return null;
}
}
public void removeProperty(String path) {
removeProperty(path, false);
}
/**
* Remove the property at a location. This will override existing
* configuration data to have it conform to key/value mappings.
*
* @param path
*/
@SuppressWarnings("unchecked")
public void removeProperty(String path, boolean allowDot) {
if (allowDot || !path.contains(".")) {
root.remove(path);
return;
}
String[] parts = path.split("\\.");
Map<String, Object> node = root;
for (int i = 0; i < parts.length; i++) {
Object o = node.get(parts[i]);
// Found our target!
if (i == parts.length - 1) {
node.remove(parts[i]);
return;
}
node = (Map<String, Object>) o;
if (node == null)
return;
}
}
@SuppressWarnings("unchecked")
protected void fullDump(Map<String, Object> target, String prefix) {
Iterator<Entry<String, Object>> i = root.entrySet().iterator();
while (i.hasNext()) {
Entry<String, Object> e = i.next();
if (e.getValue() instanceof Map)
new YamlNode((Map<String, Object>) e.getValue())
.fullDump(target, prefix + e.getKey() + ".");
else
target.put(prefix + e.getKey(), e.getValue());
}
}
public Map<String, Object> fullDump() {
Map<String, Object> map = new HashMap<String, Object>();
fullDump(map, "");
return map;
}
@Override
public String toString() {
return Util.toString(root);
}
}