Home Reference Source

stdlib/color.js

/**
 * Represents a color in the Source Engine
 */
export class Color {
	/**
	 * Creates an empty color
	 */
	constructor() {
		this._r = 0;
		this._g = 0;
		this._b = 0;
		this._a = 255;
		this._schemaKey = undefined;
	}

	/**
	 * Parse a Color object from a string
	 * @param {string} data - The data to parse
	 * @return {Color}
	 */
	static parse(data) {
		if (!data)
			throw new Error("No data given");

		var result = new Color();

		let split = data.split(' ');
		if (split.length == 4)
		{
			result.r = parseInt(split[0]);
			result.g = parseInt(split[1]);
			result.b = parseInt(split[2]);
			result.a = parseInt(split[3]);
		} else {
			result._schemaKey = data;
		}
		return result;
	}

	/**
	 * Claps the value to the valid range [0-255]
	 * @param {number} i
	 * @return {number}
	 */
	static clamp(i) {
		var result = Math.round(i);
		if (result < 0)
			result = 0;
		if (result > 255)
			result = 255;
		return result;
	}

	/**
	 * The name of the lookup key in the schema file
	 * @return {string}
	 */
	get schemaKey() {
		return this._schemaKey;
	}

	/**
	 * @type {string}
	 */
	set schemaKey(value) {
		this._schemaKey = value;
	}

	/**
	 * The red component
	 * @return {number}
	 */
	get r() {
		if (this._schemaKey != undefined)
			throw new Error("Unable to fetch schema from javascript, unknown");
		return this._r;
	}
	/**
	 * The green component
	 * @return {number}
	 */
	get g() {
		if (this._schemaKey != undefined)
			throw new Error("Unable to fetch schema from javascript, unknown");
		return this._g;
	}
	/**
	 * The blue component
	 * @return {number}
	 */
	get b() {
		if (this._schemaKey != undefined)
			throw new Error("Unable to fetch schema from javascript, unknown");
		return this._b;
	}
	/**
	 * The alpha component
	 * @return {number}
	 */
	get a() {
		if (this._schemaKey != undefined)
			throw new Error("Unable to fetch schema from javascript, unknown");
		return this._a;
	}

	/**
	 * Sets the red component
	 * @param {number} value
	 */
	set r(value) { this._r = Color.clamp(value); }
	/**
	 * Sets the green component
	 * @param {number} value
	 */
	set g(value) { this._g = Color.clamp(value); }
	/**
	 * Sets the blue component
	 * @param {number} value
	 */
	set b(value) { this._b = Color.clamp(value); }
	/**
	 * Sets the alpha component
	 * @param {number} value
	 */
	set a(value) { this._a = Color.clamp(value); }

	toString() {
		if (this._schemaKey == undefined) {
			return this.r + " " + this.g + " " + this.b + " " + this.a;
		}
		return this._schemaKey;
	}
}