1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2026-03-02 03:39:21 +00:00

Get rid of 'builtins' file since its useless and causes performance issues

This commit is contained in:
tobspr
2020-06-27 10:51:52 +02:00
parent 14246929b3
commit 2e266f5f21
60 changed files with 256 additions and 403 deletions

View File

@@ -1,6 +1,5 @@
import { GameRoot } from "./root";
import { globalConfig, IS_DEBUG } from "../core/config";
import { Math_max } from "../core/builtins";
import { createLogger } from "../core/logging";
// How important it is that a savegame is created
@@ -29,7 +28,7 @@ export class AutomaticSave {
}
setSaveImportance(importance) {
this.saveImportance = Math_max(this.saveImportance, importance);
this.saveImportance = Math.max(this.saveImportance, importance);
}
doSave() {
@@ -54,7 +53,7 @@ export class AutomaticSave {
}
// Check when the last save was, but make sure that if it fails, we don't spam
const lastSaveTime = Math_max(this.lastSaveAttempt, this.root.savegame.getRealLastUpdate());
const lastSaveTime = Math.max(this.lastSaveAttempt, this.root.savegame.getRealLastUpdate());
const secondsSinceLastSave = (Date.now() - lastSaveTime) / 1000.0;
let shouldSave = false;

View File

@@ -1,4 +1,3 @@
import { Math_min, Math_max } from "../core/builtins";
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { createLogger } from "../core/logging";
@@ -538,7 +537,7 @@ export class BeltPath extends BasicSerializableObject {
} else {
// Seems this item is on the first path (so all good), so just make sure it doesn't
// have a nextDistance which is bigger than the total path length
const clampedDistanceToNext = Math_min(itemPos + distanceToNext, firstPathLength) - itemPos;
const clampedDistanceToNext = Math.min(itemPos + distanceToNext, firstPathLength) - itemPos;
if (clampedDistanceToNext < distanceToNext) {
DEBUG &&
logger.log(
@@ -938,9 +937,9 @@ export class BeltPath extends BasicSerializableObject {
const nextDistanceAndItem = this.items[i];
const minimumSpacing = minimumDistance;
const takeAway = Math_max(
const takeAway = Math.max(
0,
Math_min(remainingAmount, nextDistanceAndItem[_nextDistance] - minimumSpacing)
Math.min(remainingAmount, nextDistanceAndItem[_nextDistance] - minimumSpacing)
);
remainingAmount -= takeAway;
@@ -984,7 +983,7 @@ export class BeltPath extends BasicSerializableObject {
if (currentLength + localLength >= progress || i === this.entityPath.length - 1) {
// Min required here due to floating point issues
const localProgress = Math_min(1.0, progress - currentLength);
const localProgress = Math.min(1.0, progress - currentLength);
assert(localProgress >= 0.0, "Invalid local progress: " + localProgress);
const localSpace = beltComp.transformBeltToLocalSpace(localProgress);

View File

@@ -5,7 +5,6 @@ import { Vector } from "../core/vector";
import { Entity } from "./entity";
import { GameRoot } from "./root";
import { findNiceIntegerValue } from "../core/utils";
import { Math_pow } from "../core/builtins";
import { blueprintShape } from "./upgrades";
import { globalConfig } from "../core/config";
@@ -58,7 +57,7 @@ export class Blueprint {
if (G_IS_DEV && globalConfig.debug.blueprintsNoCost) {
return 0;
}
return findNiceIntegerValue(4 * Math_pow(this.entities.length, 1.1));
return findNiceIntegerValue(4 * Math.pow(this.entities.length, 1.1));
}
/**

View File

@@ -1,12 +1,3 @@
import {
Math_abs,
Math_ceil,
Math_floor,
Math_max,
Math_min,
Math_random,
performanceNow,
} from "../core/builtins";
import { clickDetectorGlobals } from "../core/click_detector";
import { globalConfig, SUPPORT_TOUCH } from "../core/config";
import { createLogger } from "../core/logging";
@@ -137,8 +128,8 @@ export class Camera extends BasicSerializableObject {
addScreenShake(amount) {
const currentShakeAmount = this.currentShake.length();
const scale = 1 / (1 + 3 * currentShakeAmount);
this.currentShake.x = this.currentShake.x + 2 * (Math_random() - 0.5) * scale * amount;
this.currentShake.y = this.currentShake.y + 2 * (Math_random() - 0.5) * scale * amount;
this.currentShake.x = this.currentShake.x + 2 * (Math.random() - 0.5) * scale * amount;
this.currentShake.y = this.currentShake.y + 2 * (Math.random() - 0.5) * scale * amount;
}
/**
@@ -181,7 +172,7 @@ export class Camera extends BasicSerializableObject {
const zoomLevelX = this.root.gameWidth / desiredWorldSpaceWidth;
const zoomLevelY = this.root.gameHeight / desiredWorldSpaceWidth;
const finalLevel = Math_min(zoomLevelX, zoomLevelY);
const finalLevel = Math.min(zoomLevelX, zoomLevelY);
assert(
Number.isFinite(finalLevel) && finalLevel > 0,
"Invalid zoom level computed for initial zoom: " + finalLevel
@@ -292,10 +283,10 @@ export class Camera extends BasicSerializableObject {
*/
getVisibleRect() {
return Rectangle.fromTRBL(
Math_floor(this.getViewportTop()),
Math_ceil(this.getViewportRight()),
Math_ceil(this.getViewportBottom()),
Math_floor(this.getViewportLeft())
Math.floor(this.getViewportTop()),
Math.ceil(this.getViewportRight()),
Math.ceil(this.getViewportBottom()),
Math.floor(this.getViewportLeft())
);
}
@@ -426,7 +417,7 @@ export class Camera extends BasicSerializableObject {
* should get ignored
*/
checkPreventDoubleMouse() {
if (performanceNow() - clickDetectorGlobals.lastTouchTime < 1000.0) {
if (performance.now() - clickDetectorGlobals.lastTouchTime < 1000.0) {
return false;
}
return true;
@@ -531,7 +522,7 @@ export class Camera extends BasicSerializableObject {
// event.stopPropagation();
}
clickDetectorGlobals.lastTouchTime = performanceNow();
clickDetectorGlobals.lastTouchTime = performance.now();
this.touchPostMoveVelocity = new Vector(0, 0);
if (event.touches.length === 1) {
@@ -565,7 +556,7 @@ export class Camera extends BasicSerializableObject {
// event.stopPropagation();
}
clickDetectorGlobals.lastTouchTime = performanceNow();
clickDetectorGlobals.lastTouchTime = performance.now();
if (event.touches.length === 1) {
const touch = event.touches[0];
@@ -585,7 +576,7 @@ export class Camera extends BasicSerializableObject {
const thisDistance = newPinchPositions[0].distance(newPinchPositions[1]);
// IMPORTANT to do math max here to avoid NaN and causing an invalid zoom level
const difference = thisDistance / Math_max(0.001, lastDistance);
const difference = thisDistance / Math.max(0.001, lastDistance);
// Find old center of zoom
let oldCenter = this.lastPinchPositions[0].centerPoint(this.lastPinchPositions[1]);
@@ -645,7 +636,7 @@ export class Camera extends BasicSerializableObject {
}
}
clickDetectorGlobals.lastTouchTime = performanceNow();
clickDetectorGlobals.lastTouchTime = performance.now();
if (event.changedTouches.length === 0) {
logger.warn("Touch end without changed touches");
}
@@ -753,7 +744,7 @@ export class Camera extends BasicSerializableObject {
* @param {number} dt Delta time in milliseconds
*/
update(dt) {
dt = Math_min(dt, 33);
dt = Math.min(dt, 33);
this.cameraUpdateTimeBucket += dt;
// Simulate movement of N FPS
@@ -861,7 +852,7 @@ export class Camera extends BasicSerializableObject {
internalUpdateZooming(now, dt) {
if (!this.currentlyPinching && this.desiredZoom !== null) {
const diff = this.zoomLevel - this.desiredZoom;
if (Math_abs(diff) > 0.0001) {
if (Math.abs(diff) > 0.0001) {
let fade = 0.94;
if (diff > 0) {
// Zoom out faster than in
@@ -889,7 +880,7 @@ export class Camera extends BasicSerializableObject {
const length = diff.length();
const tolerance = 1 / this.zoomLevel;
if (length > tolerance) {
const movement = diff.multiplyScalar(Math_min(1, dt * 0.008));
const movement = diff.multiplyScalar(Math.min(1, dt * 0.008));
this.center.x += movement.x;
this.center.y += movement.y;
} else {
@@ -905,7 +896,7 @@ export class Camera extends BasicSerializableObject {
*/
internalUpdateKeyboardForce(now, dt) {
if (!this.currentlyMoving && this.desiredCenter == null) {
const limitingDimension = Math_min(this.root.gameWidth, this.root.gameHeight);
const limitingDimension = Math.min(this.root.gameWidth, this.root.gameHeight);
const moveAmount = ((limitingDimension / 2048) * dt) / this.zoomLevel;

View File

@@ -1,11 +1,10 @@
import { Math_cos, Math_PI, Math_sin } from "../../core/builtins";
import { enumDirection, Vector } from "../../core/vector";
import { types } from "../../savegame/serialization";
import { BeltPath } from "../belt_path";
import { Component } from "../component";
import { Entity } from "../entity";
export const curvedBeltLength = /* Math_PI / 4 */ 0.78;
export const curvedBeltLength = /* Math.PI / 4 */ 0.78;
export class BeltComponent extends Component {
static getId() {
@@ -65,13 +64,13 @@ export class BeltComponent extends Component {
case enumDirection.right: {
assert(progress <= curvedBeltLength + 0.02, "Invalid progress 2: " + progress);
const arcProgress = (progress / curvedBeltLength) * 0.5 * Math_PI;
return new Vector(0.5 - 0.5 * Math_cos(arcProgress), 0.5 - 0.5 * Math_sin(arcProgress));
const arcProgress = (progress / curvedBeltLength) * 0.5 * Math.PI;
return new Vector(0.5 - 0.5 * Math.cos(arcProgress), 0.5 - 0.5 * Math.sin(arcProgress));
}
case enumDirection.left: {
assert(progress <= curvedBeltLength + 0.02, "Invalid progress 3: " + progress);
const arcProgress = (progress / curvedBeltLength) * 0.5 * Math_PI;
return new Vector(-0.5 + 0.5 * Math_cos(arcProgress), 0.5 - 0.5 * Math_sin(arcProgress));
const arcProgress = (progress / curvedBeltLength) * 0.5 * Math.PI;
return new Vector(-0.5 + 0.5 * Math.cos(arcProgress), 0.5 - 0.5 * Math.sin(arcProgress));
}
default:
assertAlways(false, "Invalid belt direction: " + this.direction);

View File

@@ -1,4 +1,3 @@
import { Math_radians } from "../../core/builtins";
import { globalConfig } from "../../core/config";
import { DrawParameters } from "../../core/draw_parameters";
import { Rectangle } from "../../core/rectangle";
@@ -253,7 +252,7 @@ export class StaticMapEntityComponent extends Component {
const rotationCenterY = worldY + globalConfig.halfTileSize;
parameters.context.translate(rotationCenterX, rotationCenterY);
parameters.context.rotate(Math_radians(this.rotation));
parameters.context.rotate(Math.radians(this.rotation));
sprite.drawCached(
parameters,
@@ -264,7 +263,7 @@ export class StaticMapEntityComponent extends Component {
false
);
parameters.context.rotate(-Math_radians(this.rotation));
parameters.context.rotate(-Math.radians(this.rotation));
parameters.context.translate(-rotationCenterX, -rotationCenterY);
}
}

View File

@@ -5,7 +5,6 @@ import { Application } from "../application";
import { BufferMaintainer } from "../core/buffer_maintainer";
import { disableImageSmoothing, enableImageSmoothing, registerCanvas } from "../core/buffer_utils";
import { Math_random } from "../core/builtins";
import { globalConfig } from "../core/config";
import { getDeviceDPI, resizeHighDPICanvas } from "../core/dpi_manager";
import { DrawParameters } from "../core/draw_parameters";
@@ -443,7 +442,7 @@ export class GameCore {
for (let i = 0; i < 1e8; ++i) {
sum += i;
}
if (Math_random() > 0.95) {
if (Math.random() > 0.95) {
console.log(sum);
}
}

View File

@@ -1,7 +1,6 @@
import { GameRoot } from "./root";
import { createLogger } from "../core/logging";
import { globalConfig } from "../core/config";
import { performanceNow, Math_min, Math_round, Math_max } from "../core/builtins";
import { round3Digits } from "../core/utils";
const logger = createLogger("dynamic_tickrate");
@@ -35,7 +34,7 @@ export class DynamicTickrate {
onFrameRendered() {
++this.accumulatedFps;
const now = performanceNow();
const now = performance.now();
const timeDuration = now - this.accumulatedFpsLastUpdate;
if (timeDuration > fpsAccumulationTime) {
const avgFps = (this.accumulatedFps / fpsAccumulationTime) * 1000;
@@ -65,7 +64,7 @@ export class DynamicTickrate {
}
const desiredFps = this.root.app.settings.getDesiredFps();
this.setTickRate(Math_round(Math_min(desiredFps, this.currentTickRate * 1.2)));
this.setTickRate(Math.round(Math.min(desiredFps, this.currentTickRate * 1.2)));
}
/**
@@ -77,7 +76,7 @@ export class DynamicTickrate {
}
const desiredFps = this.root.app.settings.getDesiredFps();
this.setTickRate(Math_round(Math_max(desiredFps / 2, this.currentTickRate * 0.8)));
this.setTickRate(Math.round(Math.max(desiredFps / 2, this.currentTickRate * 0.8)));
}
/**
@@ -85,7 +84,7 @@ export class DynamicTickrate {
*/
beginTick() {
assert(this.currentTickStart === null, "BeginTick called twice");
this.currentTickStart = performanceNow();
this.currentTickStart = performance.now();
if (this.capturedTicks.length > this.currentTickRate * 2) {
// Take only a portion of the ticks
@@ -119,7 +118,7 @@ export class DynamicTickrate {
*/
endTick() {
assert(this.currentTickStart !== null, "EndTick called without BeginTick");
const duration = performanceNow() - this.currentTickStart;
const duration = performance.now() - this.currentTickStart;
this.capturedTicks.push(duration);
this.currentTickStart = null;
}

View File

@@ -10,7 +10,6 @@ import { BasicSerializableObject, types } from "../savegame/serialization";
import { EntityComponentStorage } from "./entity_components";
import { Loader } from "../core/loader";
import { drawRotatedSprite } from "../core/draw_utils";
import { Math_radians } from "../core/builtins";
import { gComponentRegistry } from "../core/global_registries";
export class Entity extends BasicSerializableObject {
@@ -166,7 +165,7 @@ export class Entity extends BasicSerializableObject {
const slotTile = staticComp.localTileToWorld(slot.pos);
const direction = staticComp.localDirectionToWorld(slot.direction);
const directionVector = enumDirectionToVector[direction];
const angle = Math_radians(enumDirectionToAngle[direction]);
const angle = Math.radians(enumDirectionToAngle[direction]);
context.globalAlpha = slot.item ? 1 : 0.2;
drawRotatedSprite({
@@ -189,7 +188,7 @@ export class Entity extends BasicSerializableObject {
for (let k = 0; k < slot.directions.length; ++k) {
const direction = staticComp.localDirectionToWorld(slot.directions[k]);
const directionVector = enumDirectionToVector[direction];
const angle = Math_radians(enumDirectionToAngle[direction] + 180);
const angle = Math.radians(enumDirectionToAngle[direction] + 180);
context.globalAlpha = 0.4;
drawRotatedSprite({
parameters,

View File

@@ -8,8 +8,6 @@ import { GameSystem } from "./game_system";
import { arrayDelete, arrayDeleteValue } from "../core/utils";
import { DrawParameters } from "../core/draw_parameters";
import { globalConfig } from "../core/config";
import { Math_floor, Math_ceil } from "../core/builtins";
export class GameSystemWithFilter extends GameSystem {
/**
* Constructs a new game system with the given component filter. It will process
@@ -71,11 +69,11 @@ export class GameSystemWithFilter extends GameSystem {
let seenUids = new Set();
const chunkStartX = Math_floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math_floor(minY / globalConfig.mapChunkSize);
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math_ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math_ceil(maxY / globalConfig.mapChunkSize);
const chunkEndX = Math.ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.ceil(maxY / globalConfig.mapChunkSize);
const requiredComponents = this.requiredComponentIds;

View File

@@ -1,4 +1,3 @@
import { Math_random } from "../core/builtins";
import { globalConfig } from "../core/config";
import { queryParamOptions } from "../core/query_parameters";
import { clamp, findNiceIntegerValue, randomChoice, randomInt } from "../core/utils";
@@ -336,14 +335,14 @@ export class HubGoals extends BasicSerializableObject {
}
// Sometimes shapes are missing
if (Math_random() > 0.85) {
if (Math.random() > 0.85) {
layer[randomInt(0, 3)] = null;
}
// Sometimes they actually are missing *two* ones!
// Make sure at max only one layer is missing it though, otherwise we could
// create an uncreateable shape
if (Math_random() > 0.95 && !anyIsMissingTwo) {
if (Math.random() > 0.95 && !anyIsMissingTwo) {
layer[randomInt(0, 3)] = null;
anyIsMissingTwo = true;
}

View File

@@ -1,4 +1,3 @@
import { Math_radians } from "../../../core/builtins";
import { globalConfig } from "../../../core/config";
import { DrawParameters } from "../../../core/draw_parameters";
import { drawRotatedSprite } from "../../../core/draw_utils";
@@ -368,7 +367,7 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic {
sprite: this.lockIndicatorSprite,
x: worldPos.x,
y: worldPos.y,
angle: Math_radians(rotation),
angle: Math.radians(rotation),
size: 12,
offsetY:
-globalConfig.halfTileSize -
@@ -432,7 +431,7 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic {
sprite,
x: acceptorSlotWsPos.x,
y: acceptorSlotWsPos.y,
angle: Math_radians(enumDirectionToAngle[enumInvertedDirections[worldDirection]]),
angle: Math.radians(enumDirectionToAngle[enumInvertedDirections[worldDirection]]),
size: 13,
offsetY: offsetShift + 13,
});
@@ -478,7 +477,7 @@ export class HUDBuildingPlacer extends HUDBuildingPlacerLogic {
sprite,
x: ejectorSLotWsPos.x,
y: ejectorSLotWsPos.y,
angle: Math_radians(enumDirectionToAngle[ejectorSlotWsDirection]),
angle: Math.radians(enumDirectionToAngle[ejectorSlotWsDirection]),
size: 13,
offsetY: offsetShift,
});

View File

@@ -1,4 +1,3 @@
import { Math_abs, Math_degrees, Math_round } from "../../../core/builtins";
import { globalConfig } from "../../../core/config";
import { gMetaBuildingRegistry } from "../../../core/global_registries";
import { Signal, STOP_PROPAGATION } from "../../../core/signal";
@@ -565,10 +564,10 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart {
// Place from start to corner
const pathToCorner = this.currentDirectionLockCorner.sub(startTile);
const deltaToCorner = pathToCorner.normalize().round();
const lengthToCorner = Math_round(pathToCorner.length());
const lengthToCorner = Math.round(pathToCorner.length());
let currentPos = startTile.copy();
let rotation = (Math.round(Math_degrees(deltaToCorner.angle()) / 90) * 90 + 360) % 360;
let rotation = (Math.round(Math.degrees(deltaToCorner.angle()) / 90) * 90 + 360) % 360;
if (lengthToCorner > 0) {
for (let i = 0; i < lengthToCorner; ++i) {
@@ -583,10 +582,10 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart {
// Place from corner to end
const pathFromCorner = mouseTile.sub(this.currentDirectionLockCorner);
const deltaFromCorner = pathFromCorner.normalize().round();
const lengthFromCorner = Math_round(pathFromCorner.length());
const lengthFromCorner = Math.round(pathFromCorner.length());
if (lengthFromCorner > 0) {
rotation = (Math.round(Math_degrees(deltaFromCorner.angle()) / 90) * 90 + 360) % 360;
rotation = (Math.round(Math.degrees(deltaFromCorner.angle()) / 90) * 90 + 360) % 360;
for (let i = 0; i < lengthFromCorner + 1; ++i) {
result.push({
tile: currentPos.copy(),
@@ -722,7 +721,7 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart {
).pressed
) {
const delta = newPos.sub(oldPos);
const angleDeg = Math_degrees(delta.angle());
const angleDeg = Math.degrees(delta.angle());
this.currentBaseRotation = (Math.round(angleDeg / 90) * 90 + 360) % 360;
// Holding alt inverts the placement
@@ -737,8 +736,8 @@ export class HUDBuildingPlacerLogic extends BaseHUDPart {
let x1 = newPos.x;
let y1 = newPos.y;
var dx = Math_abs(x1 - x0);
var dy = Math_abs(y1 - y0);
var dx = Math.abs(x1 - x0);
var dy = Math.abs(y1 - y0);
var sx = x0 < x1 ? 1 : -1;
var sy = y0 < y1 ? 1 : -1;
var err = dx - dy;

View File

@@ -1,6 +1,5 @@
import { BaseHUDPart } from "../base_hud_part";
import { makeDiv, round3Digits, round2Digits } from "../../../core/utils";
import { Math_round } from "../../../core/builtins";
import { DynamicDomAttach } from "../dynamic_dom_attach";
import { KEYMAPPINGS } from "../../key_action_mapper";
@@ -34,7 +33,7 @@ export class HUDDebugInfo extends BaseHUDPart {
this.tickRateElement.innerText = "Tickrate: " + this.root.dynamicTickrate.currentTickRate;
this.fpsElement.innerText =
"FPS: " +
Math_round(this.root.dynamicTickrate.averageFps) +
Math.round(this.root.dynamicTickrate.averageFps) +
" (" +
round2Digits(1000 / this.root.dynamicTickrate.averageFps) +
" ms)";

View File

@@ -1,4 +1,3 @@
import { Math_max } from "../../../core/builtins";
import { ClickDetector } from "../../../core/click_detector";
import { formatBigNumber, makeDiv, arrayDelete, arrayDeleteValue } from "../../../core/utils";
import { ShapeDefinition } from "../../shape_definition";

View File

@@ -1,6 +1,5 @@
import { DynamicDomAttach } from "../dynamic_dom_attach";
import { BaseHUDPart } from "../base_hud_part";
import { performanceNow } from "../../../core/builtins";
import { makeDiv } from "../../../core/utils";
import { Signal } from "../../../core/signal";
import { InputReceiver } from "../../../core/input_receiver";
@@ -62,15 +61,15 @@ export class HUDProcessingOverlay extends BaseHUDPart {
}
processSync() {
const now = performanceNow();
const now = performance.now();
while (this.tasks.length > 0) {
const workload = this.tasks[0];
workload.call();
this.tasks.shift();
}
const duration = performanceNow() - now;
const duration = performance.now() - now;
if (duration > 100) {
logger.log("Tasks done slow (SYNC!) within", (performanceNow() - now).toFixed(2), "ms");
logger.log("Tasks done slow (SYNC!) within", (performance.now() - now).toFixed(2), "ms");
}
}
@@ -89,15 +88,15 @@ export class HUDProcessingOverlay extends BaseHUDPart {
}
this.computeTimeout = setTimeout(() => {
const now = performanceNow();
const now = performance.now();
while (this.tasks.length > 0) {
const workload = this.tasks[0];
workload.call();
this.tasks.shift();
}
const duration = performanceNow() - now;
const duration = performance.now() - now;
if (duration > 100) {
logger.log("Tasks done slow within", (performanceNow() - now).toFixed(2), "ms");
logger.log("Tasks done slow within", (performance.now() - now).toFixed(2), "ms");
}
this.domWatcher.update(false);

View File

@@ -5,7 +5,6 @@ import { T } from "../../../translations";
import { createLogger } from "../../../core/logging";
import { StaticMapEntityComponent } from "../../components/static_map_entity";
import { Vector } from "../../../core/vector";
import { Math_max, Math_min, Math_floor } from "../../../core/builtins";
import { makeOffscreenBuffer } from "../../../core/buffer_utils";
import { DrawParameters } from "../../../core/draw_parameters";
import { Rectangle } from "../../../core/rectangle";
@@ -43,11 +42,11 @@ export class HUDScreenshotExporter extends BaseHUDPart {
const maxTile = new Vector(0, 0);
for (let i = 0; i < staticEntities.length; ++i) {
const bounds = staticEntities[i].components.StaticMapEntity.getTileSpaceBounds();
minTile.x = Math_min(minTile.x, bounds.x);
minTile.y = Math_min(minTile.y, bounds.y);
minTile.x = Math.min(minTile.x, bounds.x);
minTile.y = Math.min(minTile.y, bounds.y);
maxTile.x = Math_max(maxTile.x, bounds.x + bounds.w);
maxTile.y = Math_max(maxTile.y, bounds.y + bounds.h);
maxTile.x = Math.max(maxTile.x, bounds.x + bounds.w);
maxTile.y = Math.max(maxTile.y, bounds.y + bounds.h);
}
const minChunk = minTile.divideScalar(globalConfig.mapChunkSize).floor();
@@ -57,10 +56,10 @@ export class HUDScreenshotExporter extends BaseHUDPart {
logger.log("Dimensions:", dimensions);
let chunkSizePixels = 128;
const maxDimensions = Math_max(dimensions.x, dimensions.y);
const maxDimensions = Math.max(dimensions.x, dimensions.y);
if (maxDimensions > 128) {
chunkSizePixels = Math_max(1, Math_floor(128 * (128 / maxDimensions)));
chunkSizePixels = Math.max(1, Math.floor(128 * (128 / maxDimensions)));
}
logger.log("ChunkSizePixels:", chunkSizePixels);

View File

@@ -1,4 +1,3 @@
import { Math_min } from "../../../core/builtins";
import { ClickDetector } from "../../../core/click_detector";
import { InputReceiver } from "../../../core/input_receiver";
import { formatBigNumber, makeDiv } from "../../../core/utils";
@@ -178,7 +177,7 @@ export class HUDShop extends BaseHUDPart {
const { progressLabel, progressBar, definition, required } = handle.requireIndexToElement[i];
const haveAmount = this.root.hubGoals.getShapesStored(definition);
const progress = Math_min(haveAmount / required, 1.0);
const progress = Math.min(haveAmount / required, 1.0);
progressLabel.innerText = formatBigNumber(haveAmount) + " / " + formatBigNumber(required);
progressBar.style.width = progress * 100.0 + "%";

View File

@@ -1,4 +1,3 @@
import { Math_min } from "../../../core/builtins";
import { InputReceiver } from "../../../core/input_receiver";
import { makeButton, makeDiv, removeAllChildren, capitalizeFirstLetter } from "../../../core/utils";
import { KeyActionMapper, KEYMAPPINGS } from "../../key_action_mapper";
@@ -179,7 +178,7 @@ export class HUDStatistics extends BaseHUDPart {
let rendered = new Set();
for (let i = 0; i < Math_min(entries.length, 200); ++i) {
for (let i = 0; i < Math.min(entries.length, 200); ++i) {
const entry = entries[i];
const shapeKey = entry[0];

View File

@@ -1,5 +1,4 @@
import { makeOffscreenBuffer } from "../../../core/buffer_utils";
import { Math_max, Math_PI, Math_radians } from "../../../core/builtins";
import { globalConfig, IS_DEMO } from "../../../core/config";
import { DrawParameters } from "../../../core/draw_parameters";
import { Loader } from "../../../core/loader";
@@ -270,7 +269,7 @@ export class HUDWaypoints extends BaseHUDPart {
center: { x: position.x, y: position.y },
// Make sure the zoom is *just* a bit above the zoom level where the map overview
// starts, so you always see all buildings
zoomLevel: Math_max(this.root.camera.zoomLevel, globalConfig.mapChunkOverviewMinZoom + 0.05),
zoomLevel: Math.max(this.root.camera.zoomLevel, globalConfig.mapChunkOverviewMinZoom + 0.05),
});
// Sort waypoints by name
@@ -419,7 +418,7 @@ export class HUDWaypoints extends BaseHUDPart {
if (this.currentCompassOpacity > 0.01) {
context.globalAlpha = this.currentCompassOpacity;
const angle = cameraPos.angle() + Math_radians(45) + Math_PI / 2;
const angle = cameraPos.angle() + Math.radians(45) + Math.PI / 2;
context.translate(dims / 2, dims / 2);
context.rotate(angle);
this.directionIndicatorSprite.drawCentered(context, 0, 0, indicatorSize);

View File

@@ -1,7 +1,6 @@
import { GameRoot } from "../root";
import { globalConfig } from "../../core/config";
import { Vector, mixVector } from "../../core/vector";
import { performanceNow } from "../../core/builtins";
import { lerp } from "../../core/utils";
/* dev:start */
@@ -87,7 +86,7 @@ export class TrailerMaker {
if (!nextMarker.startTime) {
console.log("Starting to approach", nextMarker.pos);
nextMarker.startTime = performanceNow() / 1000.0;
nextMarker.startTime = performance.now() / 1000.0;
}
const speed =
@@ -98,7 +97,7 @@ export class TrailerMaker {
// this.currentPlaybackOrigin.distance(Vector.fromSerializedObject(nextMarker.pos)) / speed;
const time = nextMarker.time;
const progress = (performanceNow() / 1000.0 - nextMarker.startTime) / time;
const progress = (performance.now() / 1000.0 - nextMarker.startTime) / time;
if (progress > 1.0) {
if (nextMarker.wait > 0) {

View File

@@ -7,8 +7,6 @@ import { Application } from "../application";
import { Signal, STOP_PROPAGATION } from "../core/signal";
import { IS_MOBILE } from "../core/config";
import { T } from "../translations";
import { JSON_stringify } from "../core/builtins";
function key(str) {
return str.toUpperCase().charCodeAt(0);
}
@@ -446,7 +444,7 @@ export class KeyActionMapper {
getBinding(binding) {
// @ts-ignore
const id = binding.id;
assert(id, "Not a valid keybinding: " + JSON_stringify(binding));
assert(id, "Not a valid keybinding: " + JSON.stringify(binding));
assert(this.keybindings[id], "Keybinding " + id + " not known!");
return this.keybindings[id];
}

View File

@@ -3,7 +3,6 @@ import { Entity } from "./entity";
import { Vector, enumDirectionToVector, enumDirection } from "../core/vector";
import { MetaBuilding } from "./meta_building";
import { StaticMapEntityComponent } from "./components/static_map_entity";
import { Math_abs, performanceNow } from "../core/builtins";
import { createLogger } from "../core/logging";
import { MetaBeltBaseBuilding, arrayBeltVariantToRotation } from "./buildings/belt_base";
import { SOUNDS } from "../platform/sound";
@@ -199,9 +198,9 @@ export class GameLogic {
logger.warn("Running bulk operation ...");
assert(!this.root.bulkOperationRunning, "Can not run two bulk operations twice");
this.root.bulkOperationRunning = true;
const now = performanceNow();
const now = performance.now();
const returnValue = operation();
const duration = performanceNow() - now;
const duration = performance.now() - now;
logger.log("Done in", round2Digits(duration), "ms");
assert(this.root.bulkOperationRunning, "Bulk operation = false while bulk operation was running");
this.root.bulkOperationRunning = false;
@@ -244,7 +243,7 @@ export class GameLogic {
for (let dx = -1; dx <= 1; ++dx) {
for (let dy = -1; dy <= 1; ++dy) {
if (Math_abs(dx) + Math_abs(dy) !== 1) {
if (Math.abs(dx) + Math.abs(dy) !== 1) {
continue;
}

View File

@@ -5,7 +5,6 @@ import { GameRoot } from "./root";
import { globalConfig } from "../core/config";
import { Vector } from "../core/vector";
import { Entity } from "./entity";
import { Math_floor } from "../core/builtins";
import { createLogger } from "../core/logging";
import { BaseItem } from "./base_item";
import { MapChunkView } from "./map_chunk_view";
@@ -71,8 +70,8 @@ export class BaseMap extends BasicSerializableObject {
* @returns {MapChunkView}
*/
getOrCreateChunkAtTile(tileX, tileY) {
const chunkX = Math_floor(tileX / globalConfig.mapChunkSize);
const chunkY = Math_floor(tileY / globalConfig.mapChunkSize);
const chunkX = Math.floor(tileX / globalConfig.mapChunkSize);
const chunkY = Math.floor(tileY / globalConfig.mapChunkSize);
return this.getChunk(chunkX, chunkY, true);
}
@@ -83,8 +82,8 @@ export class BaseMap extends BasicSerializableObject {
* @returns {MapChunkView?}
*/
getChunkAtTileOrNull(tileX, tileY) {
const chunkX = Math_floor(tileX / globalConfig.mapChunkSize);
const chunkY = Math_floor(tileY / globalConfig.mapChunkSize);
const chunkX = Math.floor(tileX / globalConfig.mapChunkSize);
const chunkY = Math.floor(tileY / globalConfig.mapChunkSize);
return this.getChunk(chunkX, chunkY, false);
}

View File

@@ -2,7 +2,6 @@
import { GameRoot } from "./root";
/* typehints:end */
import { Math_ceil, Math_max, Math_min, Math_round } from "../core/builtins";
import { globalConfig } from "../core/config";
import { createLogger } from "../core/logging";
import { clamp, fastArrayDeleteValueIfContained, make2DUndefinedArray } from "../core/utils";
@@ -66,7 +65,7 @@ export class MapChunk {
* @param {number=} overrideY Override the Y position of the patch
*/
internalGeneratePatch(rng, patchSize, item, overrideX = null, overrideY = null) {
const border = Math_ceil(patchSize / 2 + 3);
const border = Math.ceil(patchSize / 2 + 3);
// Find a position within the chunk which is not blocked
let patchX = rng.nextIntRange(border, globalConfig.mapChunkSize - border - 1);
@@ -88,7 +87,7 @@ export class MapChunk {
for (let i = 0; i <= numCircles; ++i) {
// Determine circle parameters
const circleRadius = Math_min(1 + i, patchSize);
const circleRadius = Math.min(1 + i, patchSize);
const circleRadiusSquare = circleRadius * circleRadius;
const circleOffsetRadius = (numCircles - i) / 2 + 2;
@@ -101,8 +100,8 @@ export class MapChunk {
for (let dx = -circleRadius * circleScaleX - 2; dx <= circleRadius * circleScaleX + 2; ++dx) {
for (let dy = -circleRadius * circleScaleY - 2; dy <= circleRadius * circleScaleY + 2; ++dy) {
const x = Math_round(circleX + dx);
const y = Math_round(circleY + dy);
const x = Math.round(circleX + dx);
const y = Math.round(circleY + dy);
if (x >= 0 && x < globalConfig.mapChunkSize && y >= 0 && y <= globalConfig.mapChunkSize) {
const originalDx = dx / circleScaleX;
const originalDy = dy / circleScaleY;
@@ -158,9 +157,9 @@ export class MapChunk {
// Later there is a mix of everything
weights = {
[enumSubShape.rect]: 100,
[enumSubShape.circle]: Math_round(50 + clamp(distanceToOriginInChunks * 2, 0, 50)),
[enumSubShape.star]: Math_round(20 + clamp(distanceToOriginInChunks, 0, 30)),
[enumSubShape.windmill]: Math_round(6 + clamp(distanceToOriginInChunks / 2, 0, 20)),
[enumSubShape.circle]: Math.round(50 + clamp(distanceToOriginInChunks * 2, 0, 50)),
[enumSubShape.star]: Math.round(20 + clamp(distanceToOriginInChunks, 0, 30)),
[enumSubShape.windmill]: Math.round(6 + clamp(distanceToOriginInChunks / 2, 0, 20)),
};
if (distanceToOriginInChunks < 7) {
@@ -239,20 +238,20 @@ export class MapChunk {
}
const chunkCenter = new Vector(this.x, this.y).addScalar(0.5);
const distanceToOriginInChunks = Math_round(chunkCenter.length());
const distanceToOriginInChunks = Math.round(chunkCenter.length());
// Determine how likely it is that there is a color patch
const colorPatchChance = 0.9 - clamp(distanceToOriginInChunks / 25, 0, 1) * 0.5;
if (rng.next() < colorPatchChance / 4) {
const colorPatchSize = Math_max(2, Math_round(1 + clamp(distanceToOriginInChunks / 8, 0, 4)));
const colorPatchSize = Math.max(2, Math.round(1 + clamp(distanceToOriginInChunks / 8, 0, 4)));
this.internalGenerateColorPatch(rng, colorPatchSize, distanceToOriginInChunks);
}
// Determine how likely it is that there is a shape patch
const shapePatchChance = 0.9 - clamp(distanceToOriginInChunks / 25, 0, 1) * 0.5;
if (rng.next() < shapePatchChance / 4) {
const shapePatchSize = Math_max(2, Math_round(1 + clamp(distanceToOriginInChunks / 8, 0, 4)));
const shapePatchSize = Math.max(2, Math.round(1 + clamp(distanceToOriginInChunks / 8, 0, 4)));
this.internalGenerateShapePatch(rng, shapePatchSize, distanceToOriginInChunks);
}
}

View File

@@ -3,7 +3,6 @@ import { GameRoot } from "./root";
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { round1Digit } from "../core/utils";
import { Math_max, Math_round } from "../core/builtins";
import { Rectangle } from "../core/rectangle";
import { createLogger } from "../core/logging";
import { smoothenDpi } from "../core/dpi_manager";

View File

@@ -1,4 +1,3 @@
import { Math_max, Math_min, Math_floor, Math_ceil } from "../core/builtins";
import { globalConfig } from "../core/config";
import { DrawParameters } from "../core/draw_parameters";
import { BaseMap } from "./map";
@@ -142,11 +141,11 @@ export class MapView extends BaseMap {
const minX = left - border;
const maxX = right + border - 1;
const chunkStartX = Math_floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math_floor(minY / globalConfig.mapChunkSize);
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math_ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math_ceil(maxY / globalConfig.mapChunkSize);
const chunkEndX = Math.ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.ceil(maxY / globalConfig.mapChunkSize);
// Render y from top down for proper blending
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {
@@ -196,11 +195,11 @@ export class MapView extends BaseMap {
const minX = left - border;
const maxX = right + border - 1;
const chunkStartX = Math_floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math_floor(minY / globalConfig.mapChunkSize);
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math_ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math_ceil(maxY / globalConfig.mapChunkSize);
const chunkEndX = Math.ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.ceil(maxY / globalConfig.mapChunkSize);
// Render y from top down for proper blending
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {
@@ -223,11 +222,11 @@ export class MapView extends BaseMap {
const minX = left - border;
const maxX = right + border - 1;
const chunkStartX = Math_floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math_floor(minY / globalConfig.mapChunkSize);
const chunkStartX = Math.floor(minX / globalConfig.mapChunkSize);
const chunkStartY = Math.floor(minY / globalConfig.mapChunkSize);
const chunkEndX = Math_ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math_ceil(maxY / globalConfig.mapChunkSize);
const chunkEndX = Math.ceil(maxX / globalConfig.mapChunkSize);
const chunkEndY = Math.ceil(maxY / globalConfig.mapChunkSize);
// Render y from top down for proper blending
for (let chunkX = chunkStartX; chunkX <= chunkEndX; ++chunkX) {

View File

@@ -1,5 +1,4 @@
import { makeOffscreenBuffer } from "../core/buffer_utils";
import { JSON_parse, JSON_stringify, Math_max, Math_PI, Math_radians } from "../core/builtins";
import { globalConfig } from "../core/config";
import { smoothenDpi } from "../core/dpi_manager";
import { DrawParameters } from "../core/draw_parameters";
@@ -235,7 +234,7 @@ export class ShapeDefinition extends BasicSerializableObject {
* @returns {Array<ShapeLayer>}
*/
internalCloneLayers() {
return JSON_parse(JSON_stringify(this.layers));
return JSON.parse(JSON.stringify(this.layers));
}
/**
@@ -340,7 +339,7 @@ export class ShapeDefinition extends BasicSerializableObject {
for (let layerIndex = 0; layerIndex < this.layers.length; ++layerIndex) {
const quadrants = this.layers[layerIndex];
const layerScale = Math_max(0.1, 0.9 - layerIndex * 0.22);
const layerScale = Math.max(0.1, 0.9 - layerIndex * 0.22);
for (let quadrantIndex = 0; quadrantIndex < 4; ++quadrantIndex) {
if (!quadrants[quadrantIndex]) {
@@ -352,7 +351,7 @@ export class ShapeDefinition extends BasicSerializableObject {
const centerQuadrantX = quadrantPos.x * quadrantHalfSize;
const centerQuadrantY = quadrantPos.y * quadrantHalfSize;
const rotation = Math_radians(quadrantIndex * 90);
const rotation = Math.radians(quadrantIndex * 90);
context.translate(centerQuadrantX, centerQuadrantY);
context.rotate(rotation);
@@ -414,7 +413,7 @@ export class ShapeDefinition extends BasicSerializableObject {
insetPadding + -quadrantHalfSize,
-insetPadding + quadrantHalfSize,
quadrantSize * layerScale,
-Math_PI * 0.5,
-Math.PI * 0.5,
0
);
context.closePath();

View File

@@ -1,4 +1,3 @@
import { Math_min } from "../../core/builtins";
import { globalConfig } from "../../core/config";
import { DrawParameters } from "../../core/draw_parameters";
import { gMetaBuildingRegistry } from "../../core/global_registries";
@@ -482,7 +481,7 @@ export class BeltSystem extends GameSystemWithFilter {
}
// Limit speed to avoid belts going backwards
const speedMultiplier = Math_min(this.root.hubGoals.getBeltBaseSpeed(), 10);
const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10);
// SYNC with systems/item_acceptor.js:drawEntityUnderlays!
// 126 / 42 is the exact animation speed of the png animation

View File

@@ -6,7 +6,6 @@ import { enumDirectionToVector, enumDirectionToAngle } from "../../core/vector";
import { ItemAcceptorComponent } from "../components/item_acceptor";
import { Loader } from "../../core/loader";
import { drawRotatedSprite } from "../../core/draw_utils";
import { Math_radians, Math_min } from "../../core/builtins";
import { BELT_ANIM_COUNT } from "./belt";
export class ItemAcceptorSystem extends GameSystemWithFilter {
@@ -98,7 +97,7 @@ export class ItemAcceptorSystem extends GameSystemWithFilter {
}
// Limit speed to avoid belts going backwards
const speedMultiplier = Math_min(this.root.hubGoals.getBeltBaseSpeed(), 10);
const speedMultiplier = Math.min(this.root.hubGoals.getBeltBaseSpeed(), 10);
const underlays = acceptorComp.beltUnderlays;
for (let i = 0; i < underlays.length; ++i) {
@@ -118,7 +117,7 @@ export class ItemAcceptorSystem extends GameSystemWithFilter {
sprite: this.underlayBeltSprites[animationIndex % this.underlayBeltSprites.length],
x: (transformedPos.x + 0.5) * globalConfig.tileSize,
y: (transformedPos.y + 0.5) * globalConfig.tileSize,
angle: Math_radians(angle),
angle: Math.radians(angle),
size: globalConfig.tileSize,
});
}

View File

@@ -1,4 +1,3 @@
import { Math_min } from "../../core/builtins";
import { globalConfig } from "../../core/config";
import { DrawParameters } from "../../core/draw_parameters";
import { createLogger } from "../../core/logging";
@@ -207,7 +206,7 @@ export class ItemEjectorSystem extends GameSystemWithFilter {
const targetEntity = sourceSlot.cachedTargetEntity;
// Advance items on the slot
sourceSlot.progress = Math_min(1, sourceSlot.progress + progressGrowth);
sourceSlot.progress = Math.min(1, sourceSlot.progress + progressGrowth);
// Check if we are still in the process of ejecting, can't proceed then
if (sourceSlot.progress < 1.0) {

View File

@@ -1,4 +1,3 @@
import { Math_max } from "../../core/builtins";
import { globalConfig } from "../../core/config";
import { BaseItem } from "../base_item";
import { enumColorMixingResults } from "../colors";
@@ -21,7 +20,7 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
const ejectorComp = entity.components.ItemEjector;
// First of all, process the current recipe
processorComp.secondsUntilEject = Math_max(
processorComp.secondsUntilEject = Math.max(
0,
processorComp.secondsUntilEject - this.root.dynamicTickrate.deltaSeconds
);

View File

@@ -1,4 +1,3 @@
import { Math_max } from "../../core/builtins";
import { globalConfig } from "../../core/config";
import { Loader } from "../../core/loader";
import {
@@ -40,7 +39,7 @@ export class UndergroundBeltSystem extends GameSystemWithFilter {
// Decrease remaining time of all items in belt
for (let k = 0; k < pendingItems.length; ++k) {
const item = pendingItems[k];
item[1] = Math_max(0, item[1] - delta);
item[1] = Math.max(0, item[1] - delta);
if (G_IS_DEV && globalConfig.debug.instantBelts) {
item[1] = 0;
}

View File

@@ -6,7 +6,6 @@ import { types, BasicSerializableObject } from "../../savegame/serialization";
import { RegularGameSpeed } from "./regular_game_speed";
import { BaseGameSpeed } from "./base_game_speed";
import { PausedGameSpeed } from "./paused_game_speed";
import { performanceNow, Math_max } from "../../core/builtins";
import { FastForwardGameSpeed } from "./fast_forward_game_speed";
import { gGameSpeedRegistry } from "../../core/global_registries";
import { globalConfig } from "../../core/config";
@@ -55,7 +54,7 @@ export class GameTime extends BasicSerializableObject {
* Fetches the new "real" time, called from the core once per frame, since performance now() is kinda slow
*/
updateRealtimeNow() {
this.realtimeSeconds = performanceNow() / 1000.0 + this.realtimeAdjust;
this.realtimeSeconds = performance.now() / 1000.0 + this.realtimeAdjust;
}
/**
@@ -104,7 +103,7 @@ export class GameTime extends BasicSerializableObject {
}
// Check for too big pile of updates -> reduce it to 1
let maxLogicSteps = Math_max(
let maxLogicSteps = Math.max(
3,
(this.speed.getMaxLogicStepsInQueue() * this.root.dynamicTickrate.currentTickRate) / 60
);
@@ -209,7 +208,7 @@ export class GameTime extends BasicSerializableObject {
}
// Adjust realtime now difference so they match
this.realtimeAdjust = this.realtimeSeconds - performanceNow() / 1000.0;
this.realtimeAdjust = this.realtimeSeconds - performance.now() / 1000.0;
this.updateRealtimeNow();
// Make sure we have a quantizied time