All files / src/shared/lib/entities entitiesHelpers.ts

62.38% Statements 252/404
19.23% Branches 30/156
41.03% Functions 32/78
57.26% Lines 201/351

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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 113540x 40x 40x                                                                                         40x 40x 40x 40x 40x 40x 40x 40x             40x             40x       40x 40x                                                                                                                                                                     40x   40x 40x 40x 40x 40x 40x 40x   40x 40x     40x               40x       40x               40x       40x 40x     40x     40x     40x     40x     40x 40x 40x       40x               40x     40x 40x 40x             40x                                       40x     3x     40x                                                                                                                                                                                                                                                                                 40x                                           40x                       2x     40x 6x     40x         40x       40x     40x 132x 75x   57x 14x   43x     40x     61x 43x   18x 16x   2x     40x     58x 36x   22x 22x         40x                       40x                       40x 32x     40x   40x 66x     40x 56x     40x 14x             40x                                                     40x                 4x                   4x                   4x 1x   3x 3x 18x 5x   13x             3x     40x                 4x           4x           4x 1x   3x 3x 6x 1x   5x             3x     40x       40x       40x       40x             40x           40x                                                             40x   40x   40x 1x 40x 1x 40x   40x     40x     91x 7x       40x 7x   7x 91x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x     40x 7x     40x       121x 20x 20x 20x 3x 3x   20x         40x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x     40x                   40x         6x 3x         6x     6x 3x 3x   3x             3x     40x                                                                       40x               6x 6x 6x 6x                 40x             3x 3x   3x 3x 3x 3x                   40x                                                         40x                                           40x 56x     40x                                                                                                                                                                                                                                                                               40x         3x         40x       40x               40x               40x                   40x      
import { normalize, denormalize, schema, NormalizedSchema } from "normalizr";
import pick from "lodash/pick";
import cloneDeep from "lodash/cloneDeep";
import {
  EntitiesState,
  SpriteSheetNormalized,
  Metasprite,
  MetaspriteTile,
  SpriteAnimation,
  SceneNormalized,
  ActorNormalized,
  TriggerNormalized,
  Background,
  Palette,
  Music,
  Font,
  Avatar,
  Emote,
  CustomEventNormalized,
  Variable,
  EngineFieldValue,
  UnionValue,
  UnionDirectionValue,
  UnionNumberValue,
  UnionPropertyValue,
  UnionVariableValue,
  SpriteState,
  SpriteSheetData,
  ScriptEventNormalized,
  Sound,
  Tileset,
  CustomEventVariable,
  CustomEventActor,
  Actor,
  Scene,
  CustomEvent,
  Trigger,
  SpriteSheet,
  ActorPrefab,
  ActorPrefabNormalized,
  ActorScriptKey,
  TriggerPrefab,
  TriggerPrefabNormalized,
  TriggerScriptKey,
  ScriptEvent,
} from "shared/lib/entities/entitiesTypes";
import { EntityAdapter, EntityId, EntityState } from "@reduxjs/toolkit";
import { genSymbol, toValidSymbol } from "shared/lib/helpers/symbols";
import parseAssetPath from "shared/lib/assets/parseAssetPath";
import { COLLISION_SLOPE_VALUES } from "consts";
import { Asset, assetNameFromFilename } from "shared/lib/helpers/assets";
import l10n from "shared/lib/lang/l10n";
import isEqual from "lodash/isEqual";
import { isNormalizedScriptEqual } from "shared/lib/scripts/scriptHelpers";
import {
  ScriptEventDefs,
  isActorField,
  isPropertyField,
  isScriptValueField,
  isVariableField,
} from "shared/lib/scripts/scriptDefHelpers";
import {
  filterEvents,
  walkActorScriptsKeys,
  walkNormalizedScript,
  walkSceneScriptsKeys,
  walkTriggerScriptsKeys,
} from "shared/lib/scripts/walk";
import {
  extractScriptValueActorIds,
  extractScriptValueVariables,
} from "shared/lib/scriptValue/helpers";
import { ScriptValue, isScriptValue } from "shared/lib/scriptValue/types";
import { sortByKey } from "shared/lib/helpers/sortByKey";
import { Constant, ProjectEntityResources } from "shared/lib/resources/types";
 
export interface NormalizedEntities {
  scenes: Record<EntityId, SceneNormalized>;
  actors: Record<EntityId, ActorNormalized>;
  triggers: Record<EntityId, TriggerNormalized>;
  scriptEvents: Record<EntityId, ScriptEventNormalized>;
  backgrounds: Record<EntityId, Background>;
  sprites: Record<EntityId, SpriteSheetNormalized>;
  metasprites: Record<EntityId, Metasprite>;
  metaspriteTiles: Record<EntityId, MetaspriteTile>;
  spriteAnimations: Record<EntityId, SpriteAnimation>;
  spriteStates: Record<EntityId, SpriteState>;
  palettes: Record<EntityId, Palette>;
  music: Record<EntityId, Music>;
  sounds: Record<EntityId, Sound>;
  fonts: Record<EntityId, Font>;
  avatars: Record<EntityId, Avatar>;
  emotes: Record<EntityId, Emote>;
  tilesets: Record<EntityId, Tileset>;
  actorPrefabs: Record<EntityId, ActorPrefabNormalized>;
  triggerPrefabs: Record<EntityId, TriggerPrefabNormalized>;
  scripts: Record<EntityId, CustomEventNormalized>;
  variables: Record<EntityId, Variable>;
  constants: Record<EntityId, Constant>;
  engineFieldValues: Record<EntityId, EngineFieldValue>;
}
 
export interface NormalizedResult {
  scenes: EntityId[];
  actors: EntityId[];
  triggers: EntityId[];
  backgrounds: EntityId[];
  spriteSheets: EntityId[];
  palettes: EntityId[];
  actorPrefabs: EntityId[];
  triggerPrefabs: EntityId[];
  scripts: EntityId[];
  music: EntityId[];
  sounds: EntityId[];
  fonts: EntityId[];
  avatars: EntityId[];
  emotes: EntityId[];
  tilesets: EntityId[];
  variables: EntityId[];
  constants: EntityId[];
  variableResources: EntityId[];
  engineFieldValues: EntityId[];
}
 
export type NormalizedData = NormalizedSchema<
  NormalizedEntities,
  NormalizedResult
>;
 
type NamedEntity = { name: string };
 
export interface DenormalizedEntities {
  actors: Actor[];
  avatars: Avatar[];
  backgrounds: Background[];
  emotes: Emote[];
  engineFieldValues: {
    engineFieldValues: EngineFieldValue[];
  };
  fonts: Font[];
  music: Music[];
  palettes: Palette[];
  scenes: Scene[];
  scripts: CustomEvent[];
  sounds: Sound[];
  sprites: SpriteSheet[];
  tilesets: Tileset[];
  triggers: Trigger[];
  variables: {
    constants: Constant[];
    variables: Variable[];
  };
  actorPrefabs: ActorPrefab[];
  triggerPrefabs: TriggerPrefab[];
}
 
const inodeToAssetCache: Record<string, Asset> = {};
 
const backgroundSchema = new schema.Entity("backgrounds");
const musicSchema = new schema.Entity("music");
const soundSchema = new schema.Entity("sounds");
const fontSchema = new schema.Entity("fonts");
const avatarSchema = new schema.Entity("avatars");
const emoteSchema = new schema.Entity("emotes");
const tilesetSchema = new schema.Entity("tilesets");
 
const scriptEventSchema = new schema.Entity("scriptEvents");
scriptEventSchema.define({
  children: new schema.Values([scriptEventSchema]),
});
const actorSchema = new schema.Entity("actors", {
  script: [scriptEventSchema],
  startScript: [scriptEventSchema],
  updateScript: [scriptEventSchema],
  hit1Script: [scriptEventSchema],
  hit2Script: [scriptEventSchema],
  hit3Script: [scriptEventSchema],
});
const triggerSchema = new schema.Entity("triggers", {
  script: [scriptEventSchema],
  leaveScript: [scriptEventSchema],
});
const actorPrefabSchema = new schema.Entity("actorPrefabs", {
  script: [scriptEventSchema],
  startScript: [scriptEventSchema],
  updateScript: [scriptEventSchema],
  hit1Script: [scriptEventSchema],
  hit2Script: [scriptEventSchema],
  hit3Script: [scriptEventSchema],
});
const triggerPrefabSchema = new schema.Entity("triggerPrefabs", {
  script: [scriptEventSchema],
  leaveScript: [scriptEventSchema],
});
const metaspriteTilesSchema = new schema.Entity("metaspriteTiles");
const metaspritesSchema = new schema.Entity("metasprites", {
  tiles: [metaspriteTilesSchema],
});
const spriteAnimationsSchema = new schema.Entity("spriteAnimations", {
  frames: [metaspritesSchema],
});
const spriteStatesSchema = new schema.Entity("spriteStates", {
  animations: [spriteAnimationsSchema],
});
const spriteSheetsSchema = new schema.Entity("spriteSheets", {
  states: [spriteStatesSchema],
});
const spritesSchema = new schema.Entity("sprites", {
  states: [spriteStatesSchema],
});
const variablesSchema = new schema.Entity("variables");
const constantsSchema = new schema.Entity("constants");
const variablesResourceSchema = new schema.Entity("variableResources", {
  variables: [variablesSchema],
  constants: [constantsSchema],
});
const sceneSchema = new schema.Entity("scenes", {
  actors: [actorSchema],
  triggers: [triggerSchema],
  script: [scriptEventSchema],
  playerHit1Script: [scriptEventSchema],
  playerHit2Script: [scriptEventSchema],
  playerHit3Script: [scriptEventSchema],
});
const scriptsSchema = new schema.Entity("scripts", {
  script: [scriptEventSchema],
});
const palettesSchema = new schema.Entity("palettes");
const engineFieldValuesSchema = new schema.Entity("engineFieldValues");
const engineFieldValuesResourceSchema = new schema.Entity(
  "engineFieldValueResources",
  {
    engineFieldValues: [engineFieldValuesSchema],
  }
);
 
const resourcesSchema = {
  scenes: [sceneSchema],
  actors: [actorSchema],
  triggers: [triggerSchema],
  actorPrefabs: [actorPrefabSchema],
  triggerPrefabs: [triggerPrefabSchema],
  backgrounds: [backgroundSchema],
  music: [musicSchema],
  sounds: [soundSchema],
  fonts: [fontSchema],
  avatars: [avatarSchema],
  emotes: [emoteSchema],
  tilesets: [tilesetSchema],
  sprites: [spritesSchema],
  variables: variablesResourceSchema,
  scripts: [scriptsSchema],
  palettes: [palettesSchema],
  engineFieldValues: engineFieldValuesResourceSchema,
};
 
export const normalizeEntityResources = (
  projectResources: ProjectEntityResources
): NormalizedData => {
  return normalize(projectResources, resourcesSchema);
};
 
export const denormalizeEntities = (
  state: EntitiesState
): ProjectEntityResources => {
  const input = {
    scenes: state.scenes.ids,
    actors: state.actors.ids,
    triggers: state.triggers.ids,
    actorPrefabs: state.actorPrefabs.ids,
    triggerPrefabs: state.triggerPrefabs.ids,
    backgrounds: state.backgrounds.ids,
    sprites: state.spriteSheets.ids,
    palettes: state.palettes.ids,
    scripts: state.customEvents.ids,
    music: state.music.ids,
    sounds: state.sounds.ids,
    fonts: state.fonts.ids,
    avatars: state.avatars.ids,
    emotes: state.emotes.ids,
    tilesets: state.tilesets.ids,
    variables: "variables",
    engineFieldValues: "engineFieldValues",
  };
  const entities = {
    actors: state.actors.entities as Record<EntityId, ActorNormalized>,
    triggers: state.triggers.entities as Record<EntityId, TriggerNormalized>,
    scenes: state.scenes.entities as Record<EntityId, SceneNormalized>,
    actorPrefabs: state.actorPrefabs.entities as Record<
      EntityId,
      ActorPrefabNormalized
    >,
    triggerPrefabs: state.triggerPrefabs.entities as Record<
      EntityId,
      TriggerPrefabNormalized
    >,
    scriptEvents: state.scriptEvents.entities as Record<
      EntityId,
      ScriptEventNormalized
    >,
    backgrounds: state.backgrounds.entities as Record<EntityId, Background>,
    sprites: state.spriteSheets.entities as Record<
      EntityId,
      SpriteSheetNormalized
    >,
    metasprites: state.metasprites.entities as Record<EntityId, Metasprite>,
    metaspriteTiles: state.metaspriteTiles.entities as Record<
      EntityId,
      MetaspriteTile
    >,
    spriteAnimations: state.spriteAnimations.entities as Record<
      EntityId,
      SpriteAnimation
    >,
    spriteStates: state.spriteStates.entities as Record<EntityId, SpriteState>,
    palettes: state.palettes.entities as Record<EntityId, Palette>,
    scripts: state.customEvents.entities as Record<
      EntityId,
      CustomEventNormalized
    >,
    music: state.music.entities as Record<EntityId, Music>,
    sounds: state.sounds.entities as Record<EntityId, Sound>,
    fonts: state.fonts.entities as Record<EntityId, Font>,
    avatars: state.avatars.entities as Record<EntityId, Avatar>,
    emotes: state.emotes.entities as Record<EntityId, Emote>,
    tilesets: state.tilesets.entities as Record<EntityId, Tileset>,
    variableResources: {
      variables: {
        variables: state.variables.ids,
        constants: state.constants.ids,
      },
    },
    variables: state.variables.entities as Record<EntityId, Variable>,
    constants: state.constants.entities as Record<EntityId, Constant>,
    engineFieldValueResources: {
      engineFieldValues: { engineFieldValues: state.engineFieldValues.ids },
    },
    engineFieldValues: state.engineFieldValues.entities as Record<
      EntityId,
      EngineFieldValue
    >,
  };
  const denormalizedEntities: DenormalizedEntities = denormalize(
    input,
    resourcesSchema,
    entities
  );
 
  const entityToResource =
    <R extends string>(resourceType: R) =>
    <T>(entity: T): T & { _resourceType: R } => ({
      ...entity,
      _resourceType: resourceType,
      inode: undefined,
      _v: undefined,
    });
 
  const denormalizedEntityResources: ProjectEntityResources = {
    scenes: denormalizedEntities.scenes.map((scene, sceneIndex) => ({
      _index: sceneIndex,
      ...entityToResource("scene")(sceneFixNulls(scene)),
      actors: scene.actors.map((actor, actorIndex) => ({
        ...entityToResource("actor")(actorFixNulls(actor)),
        _index: actorIndex,
      })),
      triggers: scene.triggers.map((trigger, triggerIndex) => ({
        ...entityToResource("trigger")(triggerFixNulls(trigger)),
        _index: triggerIndex,
      })),
    })),
    actorPrefabs: denormalizedEntities.actorPrefabs.map((actorPrefab) =>
      entityToResource("actorPrefab")(actorFixNulls(actorPrefab))
    ),
    triggerPrefabs: denormalizedEntities.triggerPrefabs.map((triggerPrefab) =>
      entityToResource("triggerPrefab")(triggerFixNulls(triggerPrefab))
    ),
    backgrounds: denormalizedEntities.backgrounds.map(
      entityToResource("background")
    ),
    sprites: denormalizedEntities.sprites.map(entityToResource("sprite")),
    music: denormalizedEntities.music.map(entityToResource("music")),
    scripts: denormalizedEntities.scripts.map((script) =>
      entityToResource("script")(scriptFixNulls(script))
    ),
    palettes: denormalizedEntities.palettes.map(entityToResource("palette")),
    emotes: denormalizedEntities.emotes.map(entityToResource("emote")),
    avatars: denormalizedEntities.avatars.map(entityToResource("avatar")),
    fonts: denormalizedEntities.fonts.map(entityToResource("font")),
    tilesets: denormalizedEntities.tilesets.map(entityToResource("tileset")),
    sounds: denormalizedEntities.sounds.map(entityToResource("sound")),
    engineFieldValues: entityToResource("engineFieldValues")(
      denormalizedEntities.engineFieldValues
    ),
    variables: entityToResource("variables")(denormalizedEntities.variables),
  };
 
  return denormalizedEntityResources;
};
 
export const denormalizeSprite = ({
  sprite,
  metasprites,
  metaspriteTiles,
  spriteAnimations,
  spriteStates,
}: {
  sprite: SpriteSheetNormalized;
  metasprites: Record<string, Metasprite>;
  metaspriteTiles: Record<string, MetaspriteTile>;
  spriteAnimations: Record<string, SpriteAnimation>;
  spriteStates: Record<string, SpriteState>;
}): SpriteSheetData => {
  const entities = {
    metasprites,
    metaspriteTiles,
    spriteAnimations,
    spriteStates,
  };
  return denormalize(sprite, spriteSheetsSchema, entities);
};
 
export const normalizeSprite = (
  sprite: SpriteSheet
): {
  entities: {
    spriteSheets: Record<string, SpriteSheetNormalized>;
    metasprites: Record<string, Metasprite> | undefined;
    metaspriteTiles: Record<string, MetaspriteTile> | undefined;
    spriteAnimations: Record<string, SpriteAnimation> | undefined;
    spriteStates: Record<string, SpriteState> | undefined;
  };
  result: string;
} => {
  return normalize(sprite, spriteSheetsSchema);
};
 
export const matchAsset = (assetA: Asset) => (assetB: Asset) => {
  return assetA.filename === assetB.filename && assetA.plugin === assetB.plugin;
};
 
const collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: "base",
});
 
export const sortByFilename = (a: Asset, b: Asset) => {
  return collator.compare(a.filename, b.filename);
};
 
export const swapArrayElement = <T>(x: number, y: number, [...xs]: T[]): T[] =>
  xs.length > 1 ? (([xs[x], xs[y]] = [xs[y], xs[x]]), xs) : xs;
 
export const isUnionValue = (input: unknown): input is UnionValue => {
  if (typeof input !== "object") {
    return false;
  }
  if (!input || !("type" in input)) {
    return false;
  }
  return true;
};
 
export const isUnionVariableValue = (
  input: unknown
): input is UnionVariableValue => {
  if (!isUnionValue(input)) {
    return false;
  }
  if (input.type !== "variable") {
    return false;
  }
  return true;
};
 
export const isUnionPropertyValue = (
  input: unknown
): input is UnionPropertyValue => {
  if (!isUnionValue(input)) {
    return false;
  }
  if (input.type !== "property") {
    return false;
  }
  return true;
};
 
export const isUnionNumberValue = (
  input: unknown
): input is UnionNumberValue => {
  Iif (!isUnionValue(input)) {
    return false;
  }
  Iif (input.type !== "number") {
    return false;
  }
  return true;
};
 
export const isUnionDirectionValue = (
  input: unknown
): input is UnionDirectionValue => {
  Iif (!isUnionValue(input)) {
    return false;
  }
  Iif (input.type !== "direction") {
    return false;
  }
  return true;
};
 
export const toVariableNumber = (variable: string) => {
  return variable.replace(/[^0-9]/g, "");
};
 
export const localVariableCodes = ["L0", "L1", "L2", "L3", "L4", "L5"];
 
export const isVariableLocal = (variable: string) => {
  return localVariableCodes.indexOf(variable) > -1;
};
 
export const isVariableTemp = (variable: string) => {
  return ["T0", "T1"].indexOf(variable) > -1;
};
 
export const isVariableCustomEvent = (variable: string) => {
  return (
    ["V0", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9"].indexOf(
      variable
    ) > -1
  );
};
 
export const isCustomEventEqual = (
  customEventA: CustomEventNormalized,
  lookupA: Record<string, ScriptEventNormalized>,
  customEventB: CustomEventNormalized,
  lookupB: Record<string, ScriptEventNormalized>
) => {
  const compareA = {
    ...customEventA,
    script: undefined,
    id: undefined,
  };
  const compareB = {
    ...customEventB,
    script: undefined,
    id: undefined,
  };
  Iif (!isEqual(compareA, compareB)) {
    return false;
  }
  return isNormalizedScriptEqual(
    customEventA.script,
    lookupA,
    customEventB.script,
    lookupB
  );
};
 
export const isActorPrefabEqual = (
  prefabA: ActorPrefabNormalized,
  lookupA: Record<string, ScriptEventNormalized>,
  prefabB: ActorPrefabNormalized,
  lookupB: Record<string, ScriptEventNormalized>
) => {
  type CompareType = Omit<ActorPrefabNormalized, ActorScriptKey | "id"> &
    Record<ActorScriptKey | "id", undefined>;
 
  const compareA: CompareType = {
    ...prefabA,
    id: undefined,
    script: undefined,
    startScript: undefined,
    updateScript: undefined,
    hit1Script: undefined,
    hit2Script: undefined,
    hit3Script: undefined,
  };
  const compareB: CompareType = {
    ...prefabB,
    id: undefined,
    script: undefined,
    startScript: undefined,
    updateScript: undefined,
    hit1Script: undefined,
    hit2Script: undefined,
    hit3Script: undefined,
  };
  if (!isEqual(compareA, compareB)) {
    return false;
  }
  let scriptMatch = true;
  walkActorScriptsKeys((key) => {
    if (!scriptMatch) {
      return;
    }
    scriptMatch = isNormalizedScriptEqual(
      prefabA[key],
      lookupA,
      prefabB[key],
      lookupB
    );
  });
  return scriptMatch;
};
 
export const isTriggerPrefabEqual = (
  prefabA: TriggerPrefabNormalized,
  lookupA: Record<string, ScriptEventNormalized>,
  prefabB: TriggerPrefabNormalized,
  lookupB: Record<string, ScriptEventNormalized>
) => {
  type CompareType = Omit<TriggerPrefabNormalized, TriggerScriptKey | "id"> &
    Record<TriggerScriptKey | "id", undefined>;
 
  const compareA: CompareType = {
    ...prefabA,
    id: undefined,
    script: undefined,
    leaveScript: undefined,
  };
  const compareB: CompareType = {
    ...prefabB,
    id: undefined,
    script: undefined,
    leaveScript: undefined,
  };
  if (!isEqual(compareA, compareB)) {
    return false;
  }
  let scriptMatch = true;
  walkTriggerScriptsKeys((key) => {
    if (!scriptMatch) {
      return;
    }
    scriptMatch = isNormalizedScriptEqual(
      prefabA[key],
      lookupA,
      prefabB[key],
      lookupB
    );
  });
  return scriptMatch;
};
 
export const actorName = (actor: NamedEntity, actorIndex: number) => {
  return actor.name || defaultLocalisedActorName(actorIndex);
};
 
export const triggerName = (trigger: NamedEntity, triggerIndex: number) => {
  return trigger.name || defaultLocalisedTriggerName(triggerIndex);
};
 
export const sceneName = (scene: NamedEntity, sceneIndex: number) => {
  return scene.name || defaultLocalisedSceneName(sceneIndex);
};
 
export const customEventName = (
  customEvent: NamedEntity,
  customEventIndex: number
) => {
  return customEvent.name || defaultLocalisedCustomEventName(customEventIndex);
};
 
export const constantName = (constant: NamedEntity, constantIndex: number) => {
  return (constant.name || defaultLocalisedConstantName(constantIndex))
    .toLocaleUpperCase()
    .replace(/\s/g, "_");
};
 
export const paletteName = (palette: Palette, paletteIndex: number) => {
  // If we have a default name for a palette, use the localized version
  if (palette.defaultName) {
    switch (palette.id) {
      case "default-bg-1":
        return l10n("FIELD_PALETTE_DEFAULT_BG_N", { n: 1 });
      case "default-bg-2":
        return l10n("FIELD_PALETTE_DEFAULT_BG_N", { n: 2 });
      case "default-bg-3":
        return l10n("FIELD_PALETTE_DEFAULT_BG_N", { n: 3 });
      case "default-bg-4":
        return l10n("FIELD_PALETTE_DEFAULT_BG_N", { n: 4 });
      case "default-bg-5":
        return l10n("FIELD_PALETTE_DEFAULT_BG_N", { n: 5 });
      case "default-bg-6":
        return l10n("FIELD_PALETTE_DEFAULT_BG_N", { n: 6 });
      case "default-sprite":
        return l10n("FIELD_PALETTE_DEFAULT_SPRITES");
      case "default-ui":
        return l10n("FIELD_PALETTE_DEFAULT_UI");
    }
  } else {
    switch (palette.id) {
      case "dmg":
        return l10n("FIELD_PALETTE_DEFAULT_DMG");
    }
  }
  // Otherwise, use the auto-generated or user specified name
  return palette.name || defaultLocalisedPaletteName(paletteIndex);
};
 
export const defaultLocalisedActorName = (actorIndex: number) =>
  `${l10n("ACTOR")} ${actorIndex + 1}`;
export const defaultLocalisedTriggerName = (triggerIndex: number) =>
  `${l10n("TRIGGER")} ${triggerIndex + 1}`;
export const defaultLocalisedSceneName = (sceneIndex: number) =>
  `${l10n("SCENE")} ${sceneIndex + 1}`;
export const defaultLocalisedCustomEventName = (customEventIndex: number) =>
  `${l10n("CUSTOM_EVENT")} ${customEventIndex + 1}`;
export const defaultLocalisedConstantName = (constantIndex: number) =>
  `${l10n("CONSTANT")} ${constantIndex + 1}`;
export const defaultLocalisedPaletteName = (paletteIndex: number) =>
  l10n("TOOL_PALETTE_N", { number: paletteIndex + 1 });
 
const extractEntitySymbols = (
  entities: EntityState<{ symbol?: string }, string>
): Set<string> => {
  return new Set(
    Object.values(entities.entities).map((entity) => entity?.symbol ?? "")
  );
};
 
const extractEntityStateSymbols = (state: EntitiesState): Set<string> => {
  const allSymbols = new Set<string>();
 
  const addSymbols = (symbols: Set<string>) => {
    symbols.forEach((symbol) => allSymbols.add(symbol));
  };
 
  addSymbols(extractEntitySymbols(state.scenes));
  addSymbols(extractEntitySymbols(state.actors));
  addSymbols(extractEntitySymbols(state.triggers));
  addSymbols(extractEntitySymbols(state.backgrounds));
  addSymbols(extractEntitySymbols(state.spriteSheets));
  addSymbols(extractEntitySymbols(state.emotes));
  addSymbols(extractEntitySymbols(state.tilesets));
  addSymbols(extractEntitySymbols(state.fonts));
  addSymbols(extractEntitySymbols(state.variables));
  addSymbols(extractEntitySymbols(state.constants));
  addSymbols(extractEntitySymbols(state.customEvents));
  addSymbols(extractEntitySymbols(state.music));
  addSymbols(extractEntitySymbols(state.sounds));
 
  return allSymbols;
};
 
export const genEntitySymbol = (state: EntitiesState, name: string) => {
  return genSymbol(name, extractEntityStateSymbols(state));
};
 
export const ensureEntitySymbolsUnique = (
  entities: EntityState<{ symbol?: string }, string>,
  seenSymbols: Set<string>
) => {
  for (const entity of Object.values(entities.entities)) {
    if (entity) {
      entity.symbol = toValidSymbol(entity.symbol ?? "");
      if (seenSymbols.has(entity.symbol)) {
        const newSymbol = genSymbol(entity.symbol, seenSymbols);
        entity.symbol = newSymbol;
      }
      seenSymbols.add(entity.symbol);
    }
  }
};
 
export const ensureSymbolsUnique = (state: EntitiesState) => {
  const symbols: Set<string> = new Set();
  ensureEntitySymbolsUnique(state.scenes, symbols);
  ensureEntitySymbolsUnique(state.actors, symbols);
  ensureEntitySymbolsUnique(state.triggers, symbols);
  ensureEntitySymbolsUnique(state.backgrounds, symbols);
  ensureEntitySymbolsUnique(state.spriteSheets, symbols);
  ensureEntitySymbolsUnique(state.emotes, symbols);
  ensureEntitySymbolsUnique(state.tilesets, symbols);
  ensureEntitySymbolsUnique(state.fonts, symbols);
  ensureEntitySymbolsUnique(state.variables, symbols);
  ensureEntitySymbolsUnique(state.constants, symbols);
  ensureEntitySymbolsUnique(state.customEvents, symbols);
  ensureEntitySymbolsUnique(state.music, symbols);
  ensureEntitySymbolsUnique(state.sounds, symbols);
};
 
export const matchAssetEntity = <
  A extends Asset & { inode: string },
  T extends Asset & { inode: string }
>(
  entity: A,
  existingEntities: T[]
) => {
  return existingEntities.find(matchAsset(entity));
};
 
export const mergeAssetEntity = <T extends Asset & { inode: string }>(
  entities: EntityState<T, string>,
  entity: T,
  keepProps: (keyof T)[]
): T => {
  const existingEntities = entities.ids.map(
    (id) => entities.entities[id]
  ) as T[];
 
  // Check if asset already exists or was recently deleted
  const existingAsset =
    existingEntities.find(matchAsset(entity)) ||
    inodeToAssetCache[entity.inode];
 
  if (existingAsset) {
    delete inodeToAssetCache[entity.inode];
    const preferExisting = pick(existingAsset, keepProps);
 
    return {
      ...existingAsset,
      ...entity,
      ...preferExisting,
    };
  }
 
  return entity;
};
 
export const storeRemovedAssetInInodeCache = <
  T extends Asset & { inode: string }
>(
  filename: string,
  projectRoot: string,
  assetFolder: string,
  entities: EntityState<T, string>
): Asset => {
  const { file, plugin } = parseAssetPath(filename, projectRoot, assetFolder);
 
  const existingEntities = entities.ids.map(
    (id) => entities.entities[id]
  ) as T[];
 
  const asset = {
    filename: file,
    plugin,
  };
 
  const existingAsset = existingEntities.find(matchAsset(asset));
 
  Iif (existingAsset) {
    // Store deleted asset in inode cache incase it was just being renamed
    inodeToAssetCache[existingAsset.inode] = existingAsset;
  }
 
  return asset;
};
 
/**
 * Upsert entity, preferring some props from existing entity where available
 * @param entities entity state
 * @param adapter entity adapter
 * @param entity entity to upsert
 * @param keepProps array of props to keep
 */
export const upsertAssetEntity = <
  T extends Asset & { id: string; inode: string }
>(
  entities: EntityState<T, string>,
  adapter: EntityAdapter<T, string>,
  entity: T,
  keepProps: (keyof T)[]
) => {
  const mergedEntity = mergeAssetEntity(entities, entity, keepProps);
  const didInsert = entity === mergedEntity;
  adapter.upsertOne(entities, mergedEntity);
  return didInsert;
};
 
/**
 * Search entities for matching asset and remove
 * @param entities entity state
 * @param adapter entity adapter
 * @param asset asset to remove
 */
export const removeAssetEntity = <
  T extends Asset & { id: string; inode: string }
>(
  entities: EntityState<T, string>,
  adapter: EntityAdapter<T, string>,
  asset: Asset
) => {
  const existingEntities = entities.ids.map(
    (id) => entities.entities[id]
  ) as T[];
  const existingAsset = existingEntities.find(matchAsset(asset));
  if (existingAsset) {
    inodeToAssetCache[existingAsset.inode] = cloneDeep(existingAsset);
    adapter.removeOne(entities, existingAsset.id);
  }
};
 
/**
 * Search entities for matching asset and name
 * @param entities entity state
 * @param adapter entity adapter
 * @param asset asset to remove
 */
export const renameAssetEntity = <
  T extends Asset & {
    id: string;
    inode: string;
    filename: string;
    name: string;
  }
>(
  entities: EntityState<T, string>,
  adapter: EntityAdapter<T, string>,
  asset: Asset,
  newFilename: string
) => {
  const existingEntities = entities.ids.map(
    (id) => entities.entities[id]
  ) as T[];
  const existingAsset = existingEntities.find(matchAsset(asset));
  Iif (existingAsset) {
    inodeToAssetCache[existingAsset.inode] = cloneDeep(existingAsset);
    adapter.updateOne(entities, {
      id: existingAsset.id,
      changes: {
        filename: newFilename,
        name: assetNameFromFilename(newFilename),
      } as Partial<T>,
    });
  }
};
 
export const updateEntitySymbol = <T extends { id: string; symbol?: string }>(
  state: EntitiesState,
  entities: EntityState<T, string>,
  adapter: EntityAdapter<T, string>,
  id: string,
  inputSymbol: string
) => {
  const entity = entities.entities[id];
  Iif (!entity || entity.symbol === inputSymbol) {
    // Entity not found or symbol unchanged
    return;
  }
  const symbol = genEntitySymbol(state, inputSymbol);
  const changes = {
    symbol,
  } as Partial<T>;
  adapter.updateOne(entities, {
    id,
    changes,
  });
};
 
export const isSlope = (value: number) => {
  return COLLISION_SLOPE_VALUES.includes(value);
};
 
export const updateCustomEventArgs = (
  customEvent: CustomEventNormalized,
  scriptEventLookup: Record<string, ScriptEventNormalized>,
  scriptEventDefs: ScriptEventDefs
) => {
  const variables = {} as Record<string, CustomEventVariable>;
  const actors = {} as Record<string, CustomEventActor>;
  const oldVariables = customEvent.variables;
  const oldActors = customEvent.actors;
 
  walkNormalizedScript(
    customEvent.script,
    scriptEventLookup,
    undefined,
    (scriptEvent) => {
      const args = scriptEvent.args;
      Iif (!args) return;
      Object.keys(args).forEach((arg) => {
        const addActor = (actor: string) => {
          const letter = String.fromCharCode(
            "A".charCodeAt(0) + parseInt(actor)
          );
          actors[actor] = {
            id: actor,
            name: oldActors[actor]?.name || `${l10n("FIELD_ACTOR")} ${letter}`,
          };
        };
        const addVariable = (variable: string) => {
          const letter = String.fromCharCode(
            "A".charCodeAt(0) + parseInt(variable[1])
          );
          variables[variable] = {
            id: variable,
            name: oldVariables[variable]?.name || `Variable ${letter}`,
            passByReference: oldVariables[variable]?.passByReference ?? true,
          };
        };
        const addPropertyActor = (property: string) => {
          const actor = property && property.replace(/:.*/, "");
          Iif (actor !== "player" && actor !== "$self$") {
            const letter = String.fromCharCode(
              "A".charCodeAt(0) + parseInt(actor)
            );
            actors[actor] = {
              id: actor,
              name: oldActors[actor]?.name || `Actor ${letter}`,
            };
          }
        };
 
        Iif (isActorField(scriptEvent.command, arg, args, scriptEventDefs)) {
          const actor = args[arg];
          Iif (
            actor &&
            actor !== "player" &&
            actor !== "$self$" &&
            typeof actor === "string"
          ) {
            addActor(actor);
          }
        }
 
        Iif (isVariableField(scriptEvent.command, arg, args, scriptEventDefs)) {
          const variable = args[arg];
          if (
            isUnionVariableValue(variable) &&
            variable.value &&
            isVariableCustomEvent(variable.value)
          ) {
            addVariable(variable.value);
          } else Iif (
            typeof variable === "string" &&
            isVariableCustomEvent(variable)
          ) {
            addVariable(variable);
          }
        }
        Iif (isPropertyField(scriptEvent.command, arg, args, scriptEventDefs)) {
          const property = args[arg];
          if (isUnionPropertyValue(property) && property.value) {
            addPropertyActor(property.value);
          } else Iif (typeof property === "string") {
            addPropertyActor(property);
          }
        }
        Iif (
          isScriptValueField(scriptEvent.command, arg, args, scriptEventDefs)
        ) {
          const value = isScriptValue(args[arg])
            ? (args[arg] as ScriptValue)
            : undefined;
          const actors = value ? extractScriptValueActorIds(value) : [];
          const variables = value ? extractScriptValueVariables(value) : [];
          for (const actor of actors) {
            addPropertyActor(actor);
          }
          for (const variable of variables) {
            Iif (isVariableCustomEvent(variable)) {
              addVariable(variable);
            }
          }
        }
      });
      Iif (args.text || args.expression) {
        let text;
        if (args.text) {
          text = Array.isArray(args.text) ? args.text.join() : args.text;
        } else Iif (args.expression) {
          text = args.expression;
        }
        Iif (text && typeof text === "string") {
          const variablePtrs = text.match(/\$V[0-9]\$/g);
          Iif (variablePtrs) {
            variablePtrs.forEach((variablePtr: string) => {
              const variable = variablePtr[2];
              const letter = String.fromCharCode(
                "A".charCodeAt(0) + parseInt(variable, 10)
              ).toUpperCase();
              const variableId = `V${variable}`;
              variables[variableId] = {
                id: variableId,
                name: oldVariables[variableId]?.name || `Variable ${letter}`,
                passByReference:
                  oldVariables[variableId]?.passByReference ?? true,
              };
            });
          }
        }
      }
    }
  );
 
  customEvent.variables = sortByKey(variables);
  customEvent.actors = actors;
};
 
export const updateAllCustomEventsArgs = (
  customEvents: CustomEventNormalized[],
  scriptEventLookup: Record<string, ScriptEventNormalized>,
  scriptEventDefs: ScriptEventDefs
) => {
  for (const customEvent of customEvents) {
    updateCustomEventArgs(customEvent, scriptEventLookup, scriptEventDefs);
  }
};
 
export const validScriptEvent = (scriptEvent: ScriptEvent): boolean => {
  return !!(scriptEvent && scriptEvent.id);
};
 
export const sceneFixNulls = (scene: Scene): Scene => {
  const newScene = { ...scene };
  walkSceneScriptsKeys((key) => {
    newScene[key] = filterEvents(newScene[key], validScriptEvent);
  });
  return newScene;
};
 
export const actorFixNulls = <T extends Actor | ActorPrefab>(actor: T): T => {
  const newActor = { ...actor };
  walkActorScriptsKeys((key) => {
    newActor[key] = filterEvents(newActor[key], validScriptEvent);
  });
  return newActor;
};
 
export const triggerFixNulls = <T extends Trigger | TriggerPrefab>(
  trigger: T
): T => {
  const newTrigger = { ...trigger };
  walkTriggerScriptsKeys((key) => {
    newTrigger[key] = filterEvents(newTrigger[key], validScriptEvent);
  });
  return newTrigger;
};
 
export const scriptFixNulls = (script: CustomEvent): CustomEvent => {
  return { ...script, script: filterEvents(script.script, validScriptEvent) };
};