All files / src/lib/compiler compileEntityEvents.ts

82.54% Statements 52/63
53.49% Branches 46/86
100% Functions 3/3
81.67% Lines 49/60

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  9x               9x     9x 9x 9x                                               9x                                 58x   58x                             58x             10x                 58x   58x   58x       58x   58x 58x 58x 58x       58x 35x 35x   23x       58x               9x           82x   82x 98x 98x         98x 86x   86x 86x 86x                   86x 86x                             86x 11x   12x 5x 5x 5x   5x 7x             7x 5x 5x 2x                   9x   9x  
import type { ScriptEvent } from "shared/lib/entities/entitiesTypes";
import ScriptBuilder, {
  ScriptBuilderEntity,
  ScriptBuilderEntityType,
  ScriptBuilderOptions,
  ScriptOutput,
} from "./scriptBuilder";
import { PrecompiledScene } from "./generateGBVMData";
import { ScriptEventHandlers } from "lib/scriptEventsHandlers/handlerTypes";
import { LATEST_PROJECT_VERSION } from "lib/project/migration/migrateProjectResources";
import { SpriteModeSetting } from "shared/lib/resources/types";
 
const STRING_NOT_FOUND = "STRING_NOT_FOUND";
const VARIABLE_NOT_FOUND = "VARIABLE_NOT_FOUND";
const COMPILE_TIMEOUT = 1000;
 
type ScriptLocation = {
  actor?: string | undefined;
  scriptType: "scene" | "actor" | "trigger" | "customEvent";
  scene: string;
};
 
type CompileEntityEventsOptions = Partial<ScriptBuilderOptions> & {
  scriptEventHandlers: ScriptEventHandlers;
  output: ScriptOutput;
  branch: boolean;
  loop: boolean;
  lock: boolean;
  isFunction: boolean;
  scene: PrecompiledScene;
  sceneIndex: number;
  entity?: ScriptBuilderEntity;
  entityType: string;
  entityIndex: number;
  debugEnabled: boolean;
  warnings: (msg: string) => void;
};
 
const compileEntityEvents = (
  scriptSymbolName: string,
  input: ScriptEvent[] = [],
  options: CompileEntityEventsOptions,
) => {
  const {
    output = [],
    branch = false,
    scene,
    sceneIndex,
    entity,
    entityType,
    entityIndex,
    warnings,
    loop,
    lock,
    isFunction,
  } = options;
 
  const location: ScriptLocation = {
    ...(scene && {
      scene: scene.name || `Scene ${sceneIndex + 1}`,
    }),
    ...(entityType && {
      scriptType: entityType,
    }),
    ...(entityType === "actor" && {
      actor: entity?.name || `Actor ${entityIndex + 1}`,
    }),
    ...(entityType === "trigger" && {
      actor: entity?.name || `Trigger ${entityIndex + 1}`,
    }),
  };
 
  const helpers = {
    ...options,
    scriptSymbolName,
    compileEvents: (
      scriptBuilder: ScriptBuilder,
      childInput: ScriptEvent[],
    ) => {
      compileEventsWithScriptBuilder(
        scriptBuilder,
        childInput,
        location,
        warnings,
      );
    },
  };
 
  const scriptBuilder = new ScriptBuilder(output, helpers);
 
  const loopId = loop ? scriptBuilder.getNextLabel() : "";
 
  Iif (loop && input.length > 0) {
    scriptBuilder._label(loopId);
  }
 
  compileEventsWithScriptBuilder(scriptBuilder, input, location, warnings);
 
  try {
    if (!branch) {
      scriptBuilder._packLocals();
      Iif (loop && input.length > 0 && output.length > 1) {
        scriptBuilder.idle();
        scriptBuilder._jump(loopId);
      }
      if (isFunction) {
        scriptBuilder.unreserveLocals();
        scriptBuilder.returnFar();
      } else {
        scriptBuilder.scriptEnd();
      }
    }
 
    return scriptBuilder.toScriptString(scriptSymbolName, lock);
  } catch (e) {
    throw new Error(
      `Compiling failed with error "${e}". ${JSON.stringify(location)}`,
    );
  }
};
 
export const compileEventsWithScriptBuilder = (
  scriptBuilder: ScriptBuilder,
  subInput: ScriptEvent[] = [],
  location: ScriptLocation,
  warnings: (msg: string) => void,
) => {
  const { scriptEventHandlers, scriptSymbolName } = scriptBuilder.options;
 
  for (let i = 0; i < subInput.length; i++) {
    const command = subInput[i].command;
    Iif (subInput[i].args?.__comment) {
      // Skip commented events
      // eslint-disable-next-line no-continue
      continue;
    }
    if (scriptEventHandlers[command]) {
      scriptBuilder.addDebugSymbol(scriptSymbolName, subInput[i].id);
 
      try {
        const startTime = Date.now();
        scriptEventHandlers[command]?.compile(
          { ...subInput[i].args, ...subInput[i].children },
          {
            LATEST_PROJECT_VERSION: LATEST_PROJECT_VERSION,
            ...scriptBuilder.options,
            ...scriptBuilder,
            scriptSymbolName,
            event: subInput[i],
          },
        );
        const timeTaken = Date.now() - startTime;
        Iif (timeTaken > COMPILE_TIMEOUT) {
          warnings(
            `Plugin "${command}" took ${timeTaken}ms (recommended <${COMPILE_TIMEOUT}ms). ${JSON.stringify(
              location,
            )}`,
          );
        }
      } catch (e) {
        console.error(e);
        throw new Error(
          `Compiling "${command}" failed with error "${e}". ${JSON.stringify(
            location,
          )}`,
        );
      }
      if (scriptEventHandlers[command]?.isConditional) {
        scriptBuilder.addDebugEndSymbol(scriptSymbolName, subInput[i].id);
      }
    } else if (command === "INTERNAL_SET_CONTEXT") {
      const args = subInput[i].args ?? {};
      scriptBuilder.options.entity = args.entity as ScriptBuilderEntity;
      scriptBuilder.options.entityType =
        args.entityType as ScriptBuilderEntityType;
      scriptBuilder.options.entityScriptKey = String(args.scriptKey);
    } else Iif (command === "INTERNAL_IF_PARAM") {
      const args = subInput[i].args;
      scriptBuilder.ifParamValue(
        args?.parameter as number,
        args?.value as number,
        subInput[i]?.children?.true,
      );
    } else if (command === "INTERNAL_SET_SPRITE_MODE") {
      const args = subInput[i].args;
      scriptBuilder.setSpriteMode(args?.mode as SpriteModeSetting);
    } else Iif (command !== "EVENT_END") {
      warnings(
        `No compiler for command "${command}". Are you missing a plugin? ${JSON.stringify(
          location,
        )}`,
      );
    }
  }
};
 
export default compileEntityEvents;
 
export { STRING_NOT_FOUND, VARIABLE_NOT_FOUND };