nearest.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Selectors + DOM Manipulation
  2. const getColorInputNode = () => document.getElementById("color-input");
  3. const getMetricDropdownNode = () => document.getElementById("metric");
  4. const getIncludeXToggleNode = () => document.getElementById("include-x");
  5. const getNormQYToggleNode = () => document.getElementById("norm-q-y");
  6. const getCloseCoeffSliderNode = () => document.getElementById("close-coeff");
  7. const getCloseCoeffDisplayNode = () => document.getElementById("close-coeff-display");
  8. const getLimitSliderNode = () => document.getElementById("num-poke");
  9. const getLimitDisplayNode = () => document.getElementById("num-poke-display");
  10. const getNameInputNode = () => document.getElementById("pokemon-name");
  11. const getScoreListJABNode = () => document.getElementById("best-list-jab");
  12. const getScoreListRGBNode = () => document.getElementById("best-list-rgb");
  13. const getSearchListNode = () => document.getElementById("search-list");
  14. const getHideableControlNodes = () => document.querySelectorAll(".hideable_control");
  15. const getQJABDisplay = () => document.getElementById("q-vec-jab");
  16. const getQRGBDisplay = () => document.getElementById("q-vec-rgb");
  17. const getObjFnDisplay = () => document.getElementById("obj-fn");
  18. const clearNodeContents = node => { node.innerHTML = ""; };
  19. const hideCustomControls = () => getHideableControlNodes()
  20. .forEach(n => n.setAttribute("class", "hideable_control hideable_control--hidden"));
  21. const showCustomControls = () => getHideableControlNodes()
  22. .forEach(n => n.setAttribute("class", "hideable_control"));
  23. // Vector Math
  24. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  25. const vectorMag = v => Math.sqrt(vectorDot(v, v));
  26. const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
  27. // Angle Math
  28. const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
  29. const acosDeg = v => Math.acos(v) * 180 / Math.PI;
  30. // Pre-Compute Y Data
  31. const pokemonColorData = database.map(data => {
  32. const yRGBColor = d3.rgb(...data.yRGB);
  33. const [ yJABNorm, yJABHat ] = vectorNorm(data.yJAB);
  34. const [ yRGBNorm, yRGBHat ] = vectorNorm(data.yRGB);
  35. const [ _, yChromaHat ] = vectorNorm(data.yJAB.slice(1));
  36. return {
  37. ...data,
  38. yJABHex: d3.jab(...data.yJAB).formatHex(),
  39. yJABNorm, yJABHat,
  40. yRGBHex: yRGBColor.formatHex(),
  41. yRGBNorm, yRGBHat,
  42. yChromaHat,
  43. yHueAngle: d3.hsl(yRGBColor).h,
  44. }
  45. });
  46. const pokemonLookup = new Fuse(pokemonColorData, { keys: [ "name" ] });
  47. // Color Calculations
  48. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  49. const readColorInput = () => {
  50. const colorInput = "#" + (getColorInputNode()?.value?.replace("#", "") ?? "FFFFFF");
  51. if (colorInput.length !== 7) {
  52. return;
  53. }
  54. const rgb = d3.color(colorInput);
  55. const { J, a, b } = d3.jab(rgb);
  56. const qJAB = [ J, a, b ];
  57. const qRGB = [ rgb.r, rgb.g, rgb.b ];
  58. const [ qJABNorm, qJABHat ] = vectorNorm(qJAB);
  59. const qJABNormSq = qJABNorm * qJABNorm;
  60. const [ _, qChromaHat ] = vectorNorm(qJAB.slice(1));
  61. const [ qRGBNorm, qRGBHat ] = vectorNorm(qRGB);
  62. const qRGBNormSq = qRGBNorm * qRGBNorm;
  63. const qHueAngle = d3.hsl(rgb).h;
  64. return {
  65. qHex: rgb.formatHex(),
  66. qJAB, qJABHat, qJABNorm, qJABNormSq, qChromaHat,
  67. qRGB, qRGBHat, qRGBNorm, qRGBNormSq, qHueAngle,
  68. };
  69. };
  70. // State
  71. const state = {
  72. metric: null,
  73. includeX: null,
  74. normQY: null,
  75. closeCoeff: null,
  76. numPoke: null,
  77. searchTerm: null,
  78. targetColor: null,
  79. };
  80. // Metrics
  81. const scoringMetrics = [
  82. ({ xJAB, xRGB, yJAB, yRGB }) => [
  83. xJAB - 2 * vectorDot(yJAB, state.targetColor.qJAB),
  84. xRGB - 2 * vectorDot(yRGB, state.targetColor.qRGB),
  85. ],
  86. ({ yJABHat, yRGBHat }) => [
  87. -vectorDot(yJABHat, state.targetColor.qJABHat),
  88. -vectorDot(yRGBHat, state.targetColor.qRGBHat),
  89. ],
  90. ({ yChromaHat, yHueAngle }) => [
  91. acosDeg(vectorDot(state.targetColor.qChromaHat, yChromaHat)),
  92. angleDiff(state.targetColor.qHueAngle, yHueAngle),
  93. ],
  94. ({ xJAB, xRGB, yJAB, yRGB, yJABHat, yRGBHat }) => [
  95. (state.includeX ? xJAB : 0) - state.closeCoeff * vectorDot(
  96. state.normQY ? yJABHat : yJAB,
  97. state.normQY ? state.targetColor.qJABHat : state.targetColor.qJAB
  98. ),
  99. (state.includeX ? xRGB : 0) - state.closeCoeff * vectorDot(
  100. state.normQY ? yRGBHat : yRGB,
  101. state.normQY ? state.targetColor.qRGBHat : state.targetColor.qRGB
  102. ),
  103. ]
  104. ];
  105. const calcDisplayMetrics = ({
  106. xJAB, xRGB, yJABHat, yJABNorm, yRGBHat, yRGBNorm, yChromaHat, yHueAngle,
  107. }) => {
  108. // TODO - case on state.metric to avoid recalculation of subterms?
  109. const cosAngleJAB = vectorDot(state.targetColor.qJABHat, yJABHat);
  110. const yTermJAB = cosAngleJAB * yJABNorm * state.targetColor.qJABNorm;
  111. const cosAngleRGB = vectorDot(state.targetColor.qRGBHat, yRGBHat);
  112. const yTermRGB = cosAngleRGB * yRGBNorm * state.targetColor.qRGBNorm;
  113. return {
  114. stdDevRGB: Math.sqrt(xRGB - 2 * yTermRGB + state.targetColor.qRGBNormSq),
  115. stdDevJAB: Math.sqrt(xJAB - 2 * yTermJAB + state.targetColor.qJABNormSq),
  116. angleJAB: acosDeg(cosAngleJAB),
  117. angleRGB: acosDeg(cosAngleRGB),
  118. chromaAngle: acosDeg(vectorDot(state.targetColor.qChromaHat, yChromaHat)),
  119. hueAngle: angleDiff(state.targetColor.qHueAngle, yHueAngle),
  120. };
  121. };
  122. // Math Rendering
  123. const renderQVec = (q, node, sub) => {
  124. node.innerHTML = TeXZilla.toMathMLString(`\\vec{q}_{\\text{${sub}}} = \\left(${q.join(", ")}\\right)`);
  125. };
  126. const renderVec = math => `\\vec{${math.charAt(0)}}${math.substr(1)}`;
  127. const renderNorm = vec => `\\frac{${vec}}{\\left|\\left|${vec}\\right|\\right|}`;
  128. const metricText = [
  129. "\\text{RMS}_{P} ~ \\arg\\min_{P}\\left[X\\left(P\\right) - 2\\vec{q}\\cdot \\vec{Y}\\left(P\\right)\\right]",
  130. `\\angle \\left(\\vec{q}, \\vec{Y}\\left(P\\right)\\right) ~ \\arg\\min_{P}\\left[-${renderNorm(renderVec("q"))}\\cdot ${renderNorm(renderVec("Y\\left(P\\right)"))}\\right]`,
  131. "\\angle \\left(\\vec{q}_{\\perp}, \\vec{Y}\\left(P\\right)_{\\perp} \\right)",
  132. ];
  133. const updateObjective = () => {
  134. let tex = metricText?.[state.metric];
  135. if (!tex) {
  136. const { includeX, normQY, closeCoeff } = state;
  137. const xTerm = includeX ? "X\\left(P\\right)" : "";
  138. const qyMod = normQY ? c => renderNorm(renderVec(c)) : renderVec;
  139. tex = `\\arg\\min_{P}\\left[${xTerm}-${closeCoeff === 1 ? "" : closeCoeff}${qyMod("q")}\\cdot ${qyMod("Y\\left(P\\right)")}\\right]`;
  140. }
  141. const objFnNode = getObjFnDisplay();
  142. clearNodeContents(objFnNode);
  143. objFnNode.appendChild(TeXZilla.toMathML(tex));
  144. };
  145. // Pokemon Rendering
  146. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  147. const getSprite = pokemon => {
  148. pokemon = pokemon
  149. .replace("-alola", "-alolan")
  150. .replace("-galar", "-galarian")
  151. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  152. if (stripForm.find(s => pokemon.includes(s))) {
  153. pokemon = pokemon.replace(/-.*$/, "");
  154. }
  155. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  156. };
  157. const renderPokemon = (data, classes = {}) => {
  158. const { name, yJAB, yJABHex, yRGB, yRGBHex } = data;
  159. const { stdDevJAB, stdDevRGB, angleJAB, angleRGB, chromaAngle, hueAngle } = calcDisplayMetrics(data)
  160. const { labelClass = "", rgbClass = "", jabClass = "", scoreClass = "" } = classes;
  161. const titleName = name.charAt(0).toUpperCase() + name.substr(1);
  162. const textHex = getContrastingTextColor(yRGB);
  163. const rgbVec = yRGB.map(c => c.toFixed()).join(", ");
  164. const jabVec = yJAB.map(c => c.toFixed(1)).join(", ");
  165. const pkmn = document.createElement("div");
  166. pkmn.setAttribute("class", "pokemon_tile");
  167. pkmn.innerHTML = `
  168. <div class="pokemon_tile-image-wrapper">
  169. <img src="${getSprite(name)}" />
  170. </div>
  171. <div class="pokemon_tile-info_panel">
  172. <span class="pokemon_tile-pokemon_name">${titleName}</span>
  173. <div class="pokemon_tile-results">
  174. <div class="pokemon_tile-labels ${labelClass}">
  175. <span class="${jabClass}">Jab: </span>
  176. <span class="${rgbClass}">RGB: </span>
  177. </div>
  178. <div class="pokemon_tile-score_column ${scoreClass}">
  179. <span class="pokemon_tile-no_flex ${jabClass}">
  180. (${stdDevJAB.toFixed(2)}, ${angleJAB.toFixed(2)}&deg;, ${chromaAngle.toFixed(2)}&deg;)
  181. </span>
  182. <span class="pokemon_tile-no_flex ${rgbClass}">
  183. (${stdDevRGB.toFixed(2)}, ${angleRGB.toFixed(2)}&deg;, ${hueAngle.toFixed(2)}&deg;)
  184. </span>
  185. </div>
  186. <div class="pokemon_tile-hex_column">
  187. <div class="pokemon_tile-hex_color ${jabClass}" style="background-color: ${yJABHex}; color: ${textHex}">
  188. <span>${yJABHex}</span><span class="pokemon_tile-vector">(${jabVec})</span>
  189. </div>
  190. <div class="pokemon_tile-hex_color ${rgbClass}" style="background-color: ${yRGBHex}; color: ${textHex}">
  191. <span>${yRGBHex}</span><span class="pokemon_tile-vector">(${rgbVec})</span>
  192. </div>
  193. </div>
  194. </div>
  195. </div>
  196. `;
  197. return pkmn;
  198. };
  199. const getPokemonAppender = targetList => (pokemonData, classes) => {
  200. const li = document.createElement("li");
  201. li.appendChild(renderPokemon(pokemonData, classes));
  202. targetList.appendChild(li);
  203. };
  204. // Search
  205. const search = () => {
  206. const resultsNode = getSearchListNode();
  207. const append = getPokemonAppender(resultsNode);
  208. let found;
  209. if (state.searchTerm.trim().toLowerCase() === "!random") {
  210. found = Array.from({ length: 10 }, () => pokemonColorData[Math.floor(Math.random() * pokemonColorData.length)]);
  211. } else {
  212. found = pokemonLookup.search(state.searchTerm, { limit: 10 }).map(({ item }) => item);
  213. }
  214. clearNodeContents(resultsNode);
  215. found.forEach(item => append(item));
  216. };
  217. // Scoring
  218. const rescore = () => {
  219. const metricFn = scoringMetrics[state.metric ?? 0];
  220. // TODO might like to save this somewhere instead of recomputing when limit changes
  221. const scores = pokemonColorData.map(data => ({ ...data, scores: metricFn(data) }));
  222. const jabList = getScoreListJABNode();
  223. const appendJAB = getPokemonAppender(jabList);
  224. const rgbList = getScoreListRGBNode();
  225. const appendRGB = getPokemonAppender(rgbList);
  226. // extract best CIECAM02 results
  227. const bestJAB = scores
  228. .sort((a, b) => a.scores[0] - b.scores[0])
  229. .slice(0, state.numPoke);
  230. clearNodeContents(jabList);
  231. bestJAB.forEach(data => appendJAB(data, { labelClass: "hide", rgbClass: "hide" }));
  232. // extract best RGB results
  233. const bestRGB = scores
  234. .sort((a, b) => a.scores[1] - b.scores[1])
  235. .slice(0, state.numPoke);
  236. clearNodeContents(rgbList);
  237. bestRGB.forEach(data => appendRGB(data, { labelClass: "hide", jabClass: "hide" }));
  238. // update the rendered search results as well
  239. search();
  240. };
  241. // Listeners
  242. const onColorChanged = skipScore => {
  243. const readColor = readColorInput();
  244. if (readColor) {
  245. state.targetColor = readColor;
  246. renderQVec(state.targetColor.qJAB.map(c => c.toFixed(2)), getQJABDisplay(), "Jab");
  247. renderQVec(state.targetColor.qRGB.map(c => c.toFixed()), getQRGBDisplay(), "RGB");
  248. const textColor = getContrastingTextColor(state.targetColor.qRGB);
  249. document.querySelector("body").setAttribute("style", `background: ${state.targetColor.qHex}; color: ${textColor}`);
  250. state.targetColor
  251. if (!skipScore) {
  252. rescore();
  253. }
  254. }
  255. };
  256. const onRandomColor = () => {
  257. const color = [Math.random(), Math.random(), Math.random()].map(c => c * 255);
  258. getColorInputNode().value = d3.rgb(...color).formatHex();
  259. onColorChanged(); // triggers rescore
  260. };
  261. const onCustomControlsChanged = skipScore => {
  262. state.includeX = getIncludeXToggleNode()?.checked ?? false;
  263. state.normQY = getNormQYToggleNode()?.checked ?? false;
  264. state.closeCoeff = parseFloat(getCloseCoeffSliderNode()?.value ?? 2);
  265. getCloseCoeffDisplayNode().innerHTML = state.closeCoeff;
  266. updateObjective();
  267. if (!skipScore) {
  268. rescore();
  269. }
  270. }
  271. const onMetricChanged = skipScore => {
  272. const metric = getMetricDropdownNode()?.selectedIndex ?? 0;
  273. if (metric === state.metric) {
  274. return;
  275. }
  276. state.metric = metric;
  277. if (state.metric === 3) { // Custom
  278. showCustomControls();
  279. onCustomControlsChanged(skipScore); // triggers rescore
  280. } else {
  281. hideCustomControls();
  282. updateObjective();
  283. if (!skipScore) {
  284. rescore();
  285. }
  286. }
  287. };
  288. const onLimitChanged = skipScore => {
  289. state.numPoke = parseInt(getLimitSliderNode()?.value ?? 10);
  290. getLimitDisplayNode().textContent = state.numPoke;
  291. if (!skipScore) {
  292. // TODO don't need to rescore just need to expand
  293. rescore();
  294. }
  295. };
  296. const onSearchChanged = skipSearch => {
  297. state.searchTerm = getNameInputNode()?.value?.toLowerCase() ?? "";
  298. if (state.searchTerm.length === 0) {
  299. clearNodeContents(getSearchListNode());
  300. } else if (!skipSearch) {
  301. search();
  302. }
  303. };
  304. const onPageLoad = () => {
  305. // fake some events but don't do any searching or scoring
  306. onSearchChanged(true);
  307. onColorChanged(true);
  308. onMetricChanged(true);
  309. onLimitChanged(true);
  310. // then do a rescore directly, which will itself trigger a search
  311. rescore();
  312. };