All files / src/lib/compiler/precompile determineUsedAssets.ts

77.78% Statements 105/135
66.92% Branches 87/130
76.47% Functions 13/17
77.44% Lines 103/133

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337  2x 2x                       2x   2x   2x 2x 2x                                     2x                     7x 7x 7x 7x 7x 7x 7x 7x   7x 7x   7x 7x 7x 7x 7x 7x 7x   7x 9x 4x   5x       7x 28x 16x 16x 9x   16x     7x                           7x   7x   7x   7x   7x 8x 1x       7x         6x 6x 1x 6x 1x         7x 6x 4x       7x 7x   7x                   7x   7x             9x 9x 9x 5x 5x                                                 5x 5x         7x 13x 13x 13x                                               7x 9x   9x                 9x               9x             9x 4x 4x       7x                 14x               14x 1x 1x 1x 1x 1x 1x 1x           14x           14x           14x         14x 14x 17x   17x   17x   7x 10x   1x 1x 1x     9x   9x   3x             7x                    
import type { Reference } from "components/forms/ReferencesSelect";
import { DMG_PALETTE, MAX_NESTED_SCRIPT_DEPTH } from "consts";
import { eventHasArg } from "lib/helpers/eventSystem";
import type {
  BackgroundData,
  CustomEvent,
  EmoteData,
  FontData,
  Scene,
  SoundData,
  SpriteSheetData,
  TilesetData,
  Variable,
} from "shared/lib/entities/entitiesTypes";
import { walkScenesScripts } from "shared/lib/scripts/walk";
import { ScriptEventHandlers } from "lib/scriptEventsHandlers/handlerTypes";
import keyBy from "lodash/keyBy";
import { ColorModeSetting, ProjectResources } from "shared/lib/resources/types";
import { ensureString } from "shared/types";
import { valuesOf } from "shared/lib/helpers/record";
import l10n from "shared/lib/lang/l10n";
 
type HexPalette = [string, string, string, string];
 
export type ReferencedBackground = BackgroundData & {
  is360: boolean;
  uiPalette: HexPalette;
  colorMode: ColorModeSetting;
  forceTilesetGeneration: boolean;
};
 
export type ReferencedSprite = SpriteSheetData & {
  colorMode: ColorModeSetting;
};
 
export type ReferencedEmote = EmoteData;
 
export type ReferencedTileset = TilesetData;
 
export const determineUsedAssets = ({
  projectData,
  customEventsLookup,
  scriptEventHandlers,
  warnings,
}: {
  projectData: ProjectResources;
  customEventsLookup: Record<string, CustomEvent>;
  scriptEventHandlers: ScriptEventHandlers;
  warnings: (msg: string) => void;
}) => {
  const variablesLookup = keyBy(projectData.variables.variables, "id");
  const soundsLookup = keyBy(projectData.sounds, "id");
  const fontsLookup = keyBy(projectData.fonts, "id");
  const backgroundsLookup = keyBy(projectData.backgrounds, "id");
  const spritesLookup = keyBy(projectData.sprites, "id");
  const emotesLookup = keyBy(projectData.emotes, "id");
  const tilesetsLookup = keyBy(projectData.tilesets, "id");
  const palettesLookup = keyBy(projectData.palettes, "id");
 
  const defaultPlayerSprites = projectData.settings.defaultPlayerSprites;
  const projectColorMode = projectData.settings.colorMode;
 
  const usedVariablesLookup: Record<string, Variable> = {};
  const usedSoundsLookup: Record<string, SoundData> = {};
  const usedFontsLookup: Record<string, FontData> = {};
  const usedBackgroundsLookup: Record<string, ReferencedBackground> = {};
  const usedSpritesLookup: Record<string, ReferencedSprite> = {};
  const usedEmotesLookup: Record<string, ReferencedEmote> = {};
  const usedTilesetsLookup: Record<string, ReferencedTileset> = {};
 
  const getSceneColorMode = (scene: Scene): ColorModeSetting => {
    if (scene.colorModeOverride === "none" || projectColorMode === "mono") {
      return projectColorMode;
    }
    return scene.colorModeOverride;
  };
 
  const addAssetById =
    <T>(assetLookup: Record<string, T>, usedLookup: Record<string, T>) =>
    (id: string) => {
      const asset = assetLookup[id];
      if (asset && !usedLookup[id]) {
        usedLookup[id] = asset;
      }
      return !!asset;
    };
 
  const addVariableById = (id: string) => {
    Iif (!usedVariablesLookup[id]) {
      const variable = variablesLookup[id];
      if (variable) {
        usedVariablesLookup[id] = variable;
      } else {
        usedVariablesLookup[id] = {
          id,
          name: `VAR_${id}`,
          symbol: `VAR_${id}`,
        };
      }
    }
  };
  const addSoundById = addAssetById(soundsLookup, usedSoundsLookup);
 
  const addFontById = addAssetById(fontsLookup, usedFontsLookup);
 
  const addEmoteById = addAssetById(emotesLookup, usedEmotesLookup);
 
  const addTilesetById = addAssetById(tilesetsLookup, usedTilesetsLookup);
 
  const addFontsFromString = (s: string) => {
    (s.match(/(!F:[0-9a-f-]+!)/g) || [])
      .map((id) => id.substring(3).replace(/!$/, ""))
      .forEach(addFontById);
  };
 
  const addReferences = (
    references: Reference[],
    filterType: string,
    addFn: (id: string) => void,
  ) => {
    const referencedIds = references
      .filter((ref) => ref.type === filterType)
      .map((ref) => ref.id);
    for (const id of referencedIds) {
      addFn(id);
    }
  };
 
  // Add default font
  if (!addFontById(projectData.settings.defaultFontId)) {
    if (projectData.fonts.length > 0) {
      addFontById(projectData.fonts[0].id);
    }
  }
 
  const defaultBackgroundId = projectData.backgrounds?.[0]?.id ?? "";
  const defaultSpriteId = projectData.sprites?.[0]?.id ?? "";
 
  const isIncompatibleColorMode = (
    colorModeA: string,
    colorModeB: string,
  ): boolean => {
    return (
      colorModeA !== colorModeB &&
      (colorModeA === "color" || colorModeB === "color")
    );
  };
 
  const incompatibleWarnedIds = new Set<string>();
 
  const addBackgroundById = (
    backgroundId: string,
    is360: boolean,
    uiPalette: HexPalette,
    colorMode: ColorModeSetting,
    forceTilesetGeneration: boolean,
  ) => {
    const id = ensureString(backgroundId, defaultBackgroundId);
    const asset = backgroundsLookup[id];
    if (asset) {
      if (!usedBackgroundsLookup[id]) {
        usedBackgroundsLookup[id] = {
          ...asset,
          is360,
          uiPalette,
          colorMode,
          forceTilesetGeneration,
        };
      } else E{
        Iif (
          isIncompatibleColorMode(
            colorMode,
            usedBackgroundsLookup[id].colorMode,
          )
        ) {
          Iif (!incompatibleWarnedIds.has(asset.id)) {
            warnings(
              l10n("WARNING_BACKGROUND_IN_MULTIPLE_COLOR_MODES", {
                filename: asset.filename,
              }),
            );
            incompatibleWarnedIds.add(asset.id);
          }
          usedBackgroundsLookup[id].colorMode = projectColorMode;
        }
      }
      if (forceTilesetGeneration) {
        usedBackgroundsLookup[id].forceTilesetGeneration = true;
      }
    }
  };
 
  const addSpriteById = (spriteId: string, colorMode: ColorModeSetting) => {
    const id = ensureString(spriteId, defaultSpriteId);
    const asset = spritesLookup[id];
    Iif (asset) {
      if (!usedSpritesLookup[id]) {
        usedSpritesLookup[id] = {
          ...asset,
          colorMode,
        };
      } else {
        Iif (
          isIncompatibleColorMode(colorMode, usedSpritesLookup[id].colorMode)
        ) {
          Iif (!incompatibleWarnedIds.has(asset.id)) {
            warnings(
              l10n("WARNING_SPRITE_IN_MULTIPLE_COLOR_MODES", {
                filename: asset.filename,
              }),
            );
            incompatibleWarnedIds.add(asset.id);
          }
          usedSpritesLookup[id].colorMode = projectColorMode;
        }
      }
    }
  };
 
  projectData.scenes.forEach((scene) => {
    const colorMode = getSceneColorMode(scene);
 
    const uiPalette = (
      scene.paletteIds?.[7] === "dmg"
        ? DMG_PALETTE
        : palettesLookup[
            scene.paletteIds?.[7] ||
              projectData.settings.defaultBackgroundPaletteIds?.[7]
          ]
    )?.colors as HexPalette;
 
    addBackgroundById(
      ensureString(scene.backgroundId, defaultBackgroundId),
      scene.type === "LOGO",
      uiPalette,
      colorMode,
      !scene.tilesetId,
    );
 
    addSpriteById(
      ensureString(
        scene.playerSpriteSheetId || defaultPlayerSprites[scene.type],
        "",
      ),
      colorMode,
    );
    for (let a = 0; a < scene.actors.length; a++) {
      const actor = scene.actors[a];
      addSpriteById(actor.spriteSheetId, colorMode);
    }
  });
 
  walkScenesScripts(
    projectData.scenes,
    {
      customEvents: {
        lookup: customEventsLookup,
        maxDepth: MAX_NESTED_SCRIPT_DEPTH,
      },
    },
    (cmd, scene) => {
      const uiPalette = projectData.palettes.find(
        (p) =>
          p.id ===
          (scene.paletteIds[7] ||
            projectData.settings.defaultBackgroundPaletteIds[7]),
      )?.colors as HexPalette;
 
      // Add Referenced Assets
      if (eventHasArg(cmd, "references") && cmd.args?.references) {
        const references = cmd.args?.references as Reference[];
        addReferences(references, "variable", addVariableById);
        addReferences(references, "sound", addSoundById);
        addReferences(references, "font", addFontById);
        addReferences(references, "emote", addEmoteById);
        addReferences(references, "tileset", addTilesetById);
        addReferences(references, "background", (id: string) => {
          const colorMode = getSceneColorMode(scene);
          addBackgroundById(id, false, uiPalette, colorMode, true);
        });
      }
 
      Iif (eventHasArg(cmd, "backgroundId")) {
        const id = ensureString(cmd.args?.backgroundId, "");
        const colorMode = getSceneColorMode(scene);
        addBackgroundById(id, false, uiPalette, colorMode, true);
      }
 
      Iif (eventHasArg(cmd, "spriteSheetId")) {
        const id = ensureString(cmd.args?.spriteSheetId, "");
        const colorMode = getSceneColorMode(scene);
        addSpriteById(id, colorMode);
      }
 
      Iif (eventHasArg(cmd, "emoteId")) {
        const id = ensureString(cmd.args?.emoteId, "");
        addEmoteById(id);
      }
 
      if (cmd.args) {
        for (const key in cmd.args) {
          const value = cmd.args[key];
          const fieldType =
            scriptEventHandlers[cmd.command]?.fieldsLookup[key]?.type;
 
          if (fieldType === "textarea" && typeof value === "string") {
            // String text fields
            addFontsFromString(value);
          } else if (fieldType === "textarea" && Array.isArray(value)) {
            // Multi value text fields
            for (const row of value) {
              if (typeof row === "string") {
                addFontsFromString(row);
              }
            }
          } else Iif (fieldType === "tileset" && typeof value === "string") {
            addTilesetById(value);
          } else if (fieldType === "soundEffect" && typeof value === "string") {
            // Sounds
            addSoundById(value);
          }
        }
      }
    },
  );
 
  return {
    referencedVariables: valuesOf(usedVariablesLookup),
    referencedSounds: valuesOf(usedSoundsLookup),
    referencedFonts: valuesOf(usedFontsLookup),
    referencedBackgrounds: valuesOf(usedBackgroundsLookup),
    referencedSprites: valuesOf(usedSpritesLookup),
    referencedEmotes: valuesOf(usedEmotesLookup),
    referencedTilesets: valuesOf(usedTilesetsLookup),
  };
};