Skip to content

Commit

Permalink
Allow changing the color serialization format to hex.
Browse files Browse the repository at this point in the history
  • Loading branch information
leMaik committed Oct 19, 2024
1 parent d7ee5df commit c7a251d
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions chunky/src/java/se/llbit/util/JsonUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
*/
package se.llbit.util;

import se.llbit.json.Json;
import se.llbit.json.JsonArray;
import se.llbit.json.JsonObject;
import se.llbit.json.JsonValue;
import se.llbit.json.*;
import se.llbit.math.ColorUtil;
import se.llbit.math.QuickMath;
import se.llbit.math.Vector3;
Expand Down Expand Up @@ -74,7 +71,8 @@ public static Vector3 rgbFromJson(JsonValue json) {

/**
* Parse RGB color from JSON.
* @param json Either an object with red, green and blue keys (0…1), an array with 1…3 values (r,g,b) in range 0…1, or six digit hex color.
*
* @param json Either an object with red, green and blue keys (0…1), an array with 1…3 values (r,g,b) in range 0…1, or six digit hex color.
* @param color Target color vector (r,g,b from 0…1)
*/
public static void rgbFromJson(JsonValue json, Vector3 color) {
Expand All @@ -93,15 +91,26 @@ public static void rgbFromJson(JsonValue json, Vector3 color) {
}

/**
* Parse RGB color from JSON.
* @param json Either an object with red, green and blue keys (0…1), an array with 1…3 values (r,g,b) in range 0…1, or six digit hex color.
* @param color Target color vector (r,g,b from 0…1)
* Serialize an RGB color to JSON in a way that can be parsed by {@link #rgbFromJson(JsonValue)}.
* <p/>
* Depending on the <code>chunky.colorSerializationFormat</code> system property, this returns either an object with red, green and blue keys, or a hex string.
*
* @param color Color vector (r,g,b from 0…1)
* @return Serialized color
*/
public static JsonValue rgbToJson(Vector3 color) {
JsonObject colorObj = new JsonObject();
colorObj.add("red", color.x);
colorObj.add("green", color.y);
colorObj.add("blue", color.z);
return colorObj;
switch (System.getProperty("chunky.colorSerializationFormat", "hex")) {
case "hex": {
return new JsonString(String.format("#%02x%02x%02x", (int) (color.x * 255), (int) (color.y * 255), (int) (color.z * 255)));
}
case "object":
default: {
JsonObject colorObj = new JsonObject();
colorObj.add("red", color.x);
colorObj.add("green", color.y);
colorObj.add("blue", color.z);
return colorObj;
}
}
}
}

0 comments on commit c7a251d

Please sign in to comment.