Skip to content

Commit

Permalink
Start updating Canvas and Grid types for v12. Fix `MeasuredTempla…
Browse files Browse the repository at this point in the history
  • Loading branch information
In3luki authored and CarlosFdez committed May 29, 2024
1 parent 3a46d39 commit 6aacae2
Show file tree
Hide file tree
Showing 45 changed files with 1,177 additions and 482 deletions.
6 changes: 3 additions & 3 deletions src/module/apps/scene-darkness-adjuster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class SceneDarknessAdjuster extends Application {

this.#slider = noUiSlider.create(slider, {
range: { min: 0, max: 1 },
start: [0.25, game.scenes.viewed.darkness, 0.75],
start: [0.25, game.scenes.viewed.environment.darknessLevel, 0.75],
connect: [true, false, false, true],
behaviour: "snap-unconstrained-snap",
pips: {
Expand Down Expand Up @@ -97,7 +97,7 @@ export class SceneDarknessAdjuster extends Application {
this.#slider.on("slide", (values, thumbNumber) => {
if (thumbNumber === 1 && canvas.scene) {
this.#noRefreshHook = true;
canvas.colorManager.initialize({ darknessLevel: Number(values[1]) });
canvas.environment.initialize({ environment: { darknessLevel: Number(values[1]) } });
canvas.app.ticker.add(() => {
this.#noRefreshHook = false;
});
Expand All @@ -110,7 +110,7 @@ export class SceneDarknessAdjuster extends Application {
const newValue = Number(values[1]);
await canvas.scene.update(
{ darkness: newValue },
{ animateDarkness: Math.round(5000 * Math.abs(canvas.scene.darkness - newValue)) },
{ animateDarkness: Math.round(5000 * Math.abs(canvas.scene.environment.darknessLevel - newValue)) },
);
}
});
Expand Down
4 changes: 2 additions & 2 deletions src/module/canvas/effect-area-square.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ export class EffectAreaSquare extends PIXI.Rectangle {
if (this.x < 0 || this.y < 0) return;

if (this.active) {
canvas.grid.grid.highlightGridPosition(layer, {
canvas.interface.grid.highlightPosition(layer.name, {
x: this.x,
y: this.y,
border: border?.color,
color: highlight.color,
alpha: highlight.alpha,
});
} else {
canvas.grid.grid.highlightGridPosition(layer, {
canvas.interface.grid.highlightPosition(layer.name, {
x: this.x,
y: this.y,
border: 0x000000,
Expand Down
28 changes: 16 additions & 12 deletions src/module/canvas/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ function measureDistanceCuboid(
): number {
if (!canvas.grid) return NaN;
if (canvas.grid.type !== CONST.GRID_TYPES.SQUARE) {
return canvas.grid.measureDistance(r0, r1);
return canvas.grid.measurePath([r0, r1]).distance;
}

const gridWidth = canvas.grid.grid.w;
const gridWidth = canvas.grid.sizeX;

const distance = {
dx: 0,
Expand Down Expand Up @@ -120,7 +120,7 @@ function measureDistanceCuboid(
*/
function measureDistance(p0: Point, p1: Point): number {
if (canvas.grid.type !== CONST.GRID_TYPES.SQUARE) {
return canvas.grid.measureDistance(p0, p1);
return canvas.grid.measurePath([p0, p1]).distance;
}

return measureDistanceOnGrid(new Ray(p0, p1));
Expand Down Expand Up @@ -169,13 +169,15 @@ function highlightGrid({
object,
colors,
document,
snappingMode = CONST.GRID_SNAPPING_MODES.CENTER,
collisionType = "move",
preview = false,
}: HighlightGridParams): void {
// Only highlight for objects that are non-previews (have IDs)
if (!object.id && !preview) return;

const { grid, dimensions } = canvas;
const dimensions = canvas.dimensions;
const grid = canvas.interface.grid;
if (!(grid && dimensions)) return;

// Set data defaults
Expand All @@ -186,11 +188,12 @@ function highlightGrid({
const highlightLayer = grid.getHighlightLayer(object.highlightId)?.clear();
if (!highlightLayer) return;

const [cx, cy] = grid.getCenter(document.x, document.y);
const [col0, row0] = grid.grid.getGridPositionFromPixels(cx, cy);
const center = canvas.grid.getCenterPoint({ x: document.x, y: document.y });
const { i: col0, j: row0 } = canvas.grid.getOffset({ x: center.x, y: center.y });

const minAngle = (360 + ((direction - angle * 0.5) % 360)) % 360;
const maxAngle = (360 + ((direction + angle * 0.5) % 360)) % 360;
const snappedOrigin = canvas.grid.getSnappedPosition(document.x, document.y, object.layer.gridPrecision);
const snappedOrigin = canvas.grid.getSnappedPoint({ x: document.x, y: document.y }, { mode: snappingMode });
const withinAngle = (min: number, max: number, value: number) => {
min = (360 + (min % 360)) % 360;
max = (360 + (max % 360)) % 360;
Expand Down Expand Up @@ -223,8 +226,8 @@ function highlightGrid({
const padding = Math.clamped(document.width ?? 0, 1.5, 2);
const docDistance = document.distance ?? 0;
const padded = (docDistance * padding) / dimensions.distance;
const rowCount = Math.ceil(padded / (dimensions.size / grid.h));
const columnCount = Math.ceil(padded / (dimensions.size / grid.w));
const rowCount = Math.ceil(padded / (dimensions.size / canvas.grid.sizeX));
const columnCount = Math.ceil(padded / (dimensions.size / canvas.grid.sizeY));

// If this is an emanation, measure from the outer squares of the token's space
const offsetEmanationOrigin = (destination: Point): Point => {
Expand All @@ -248,7 +251,7 @@ function highlightGrid({
for (let a = -columnCount; a < columnCount; a++) {
for (let b = -rowCount; b < rowCount; b++) {
// Position of cell's top-left corner, in pixels
const [gx, gy] = canvas.grid.grid.getPixelsFromGridPosition(col0 + a, row0 + b);
const { x: gx, y: gy } = canvas.grid.getTopLeftPoint({ i: col0 + a, j: row0 + b });
// Position of cell's center in pixels
const destination = {
x: gx + dimensions.size * 0.5,
Expand Down Expand Up @@ -283,7 +286,7 @@ function highlightGrid({
});

if (hasCollision) {
grid.grid.highlightGridPosition(highlightLayer, {
grid.highlightPosition(highlightLayer.name, {
x: gx,
y: gy,
border: 0x000001,
Expand All @@ -295,7 +298,7 @@ function highlightGrid({
.lineTo(gx + dimensions.size, gy + dimensions.size)
.endFill();
} else {
grid.grid.highlightGridPosition(highlightLayer, {
grid.highlightPosition(highlightLayer.name, {
x: gx,
y: gy,
border: colors.border,
Expand All @@ -320,6 +323,7 @@ interface HighlightGridParams {
direction?: number;
width: number | null;
}>;
snappingMode?: number;
collisionType?: WallRestrictionType;
preview?: boolean;
}
Expand Down
29 changes: 17 additions & 12 deletions src/module/canvas/layer/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ export class TemplateLayerPF2e<
/** Preview event listeners that can be referenced across methods */
#previewListeners: TemplatePreviewEventListeners | null = null;

#gridPrecision = 2;
#snappingMode: number = CONST.GRID_SNAPPING_MODES.CENTER;

override get gridPrecision(): number {
return this.#gridPrecision;
get snappingMode(): number {
return this.#snappingMode;
}

/** Set a grid-snapping precision appropriate for an effect area type */
/** Set a grid-snapping mode appropriate for an effect area type */
snapFor(areaShape: EffectAreaShape | null): void {
if (areaShape && canvas.grid.type === CONST.GRID_TYPES.SQUARE) {
this.#gridPrecision = areaShape === "burst" ? 1 : 2;
this.#snappingMode =
areaShape === "burst" ? CONST.GRID_SNAPPING_MODES.CORNER : CONST.GRID_SNAPPING_MODES.CENTER;
} else {
this.#gridPrecision = 2;
this.#snappingMode = CONST.GRID_SNAPPING_MODES.CENTER;
}
}

Expand All @@ -38,15 +39,16 @@ export class TemplateLayerPF2e<
return super._onDragLeftMove(event);
}

const { destination, layerDragState, preview: template, origin } = event.interactionData;
const dragState = layerDragState ?? 0;
if (!template || template.destroyed || dragState === 0) return;
const { destination, preview: template, origin } = event.interactionData;
if (!template || template.destroyed) return;

this.snapFor(template.areaShape);
const dimensions = canvas.dimensions;

// Snap the destination to the grid
const { x, y } = canvas.grid.getSnappedPosition(destination.x, destination.y, this.gridPrecision);
const { x, y } = canvas.grid.getSnappedPoint(destination, {
mode: this.#snappingMode,
});
destination.x = x;
destination.y = y;
const ray = new Ray(origin, destination);
Expand All @@ -66,7 +68,6 @@ export class TemplateLayerPF2e<

// Draw the pending shape
template.refresh();
event.interactionData.layerDragState = 2;
}

protected override _onMouseWheel(event: WheelEvent): Promise<TObject["document"] | undefined> | void {
Expand Down Expand Up @@ -134,7 +135,11 @@ export class TemplateLayerPF2e<
preview.snapForShape();
const { document, position } = preview;
this.#deactivatePreviewListeners(initialLayer, event);
document.updateSource(canvas.grid.getSnappedPosition(position.x, position.y, this.gridPrecision));
document.updateSource(
canvas.grid.getSnappedPoint(position, {
mode: this.#snappingMode,
}),
);
canvas.scene?.createEmbeddedDocuments("MeasuredTemplate", [document.toObject()]);
},
rightdown: (event: PIXI.FederatedPointerEvent): void => {
Expand Down
5 changes: 3 additions & 2 deletions src/module/canvas/measured-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class MeasuredTemplatePF2e<

// Refrain from highlighting if not visible
if (!this.isVisible) {
canvas.grid.getHighlightLayer(this.highlightId)?.clear();
canvas.interface.grid.getHighlightLayer(this.highlightId)?.clear();
return;
}

Expand All @@ -48,8 +48,9 @@ class MeasuredTemplatePF2e<
areaShape: this.areaShape,
object: this,
document: this.document,
colors: { border: this.borderColor, fill: this.fillColor },
colors: { border: Number(this.document.borderColor), fill: Number(this.document.fillColor) },
preview: true,
snappingMode: this.layer.snappingMode,
});
}

Expand Down
6 changes: 4 additions & 2 deletions src/module/canvas/token/aura/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ export class AuraRenderers extends Map<string, AuraRenderer> {

if (showBordersHighlights && (this.token.hover || this.token.layer.highlightObjects)) {
const { highlightId } = this;
const highlight = canvas.grid.highlightLayers[highlightId] ?? canvas.grid.addHighlightLayer(highlightId);
const highlight =
canvas.interface.grid.highlightLayers[highlightId] ??
canvas.interface.grid.addHighlightLayer(highlightId);
highlight.clear();
for (const aura of this.values()) {
aura.highlight();
Expand Down Expand Up @@ -113,6 +115,6 @@ export class AuraRenderers extends Map<string, AuraRenderer> {
}

clearHighlights(): void {
canvas.grid.destroyHighlightLayer(this.highlightId);
canvas.interface.grid.destroyHighlightLayer(this.highlightId);
}
}
6 changes: 3 additions & 3 deletions src/module/canvas/token/aura/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class AuraRenderer extends PIXI.Graphics implements TokenAuraData {

/** ID of `GridHighlight` container for this aura's token */
get highlightLayer(): GridHighlight | null {
return canvas.grid?.getHighlightLayer(this.token.highlightId) ?? null;
return canvas.interface.grid?.getHighlightLayer(this.token.highlightId) ?? null;
}

/** The squares covered by this aura */
Expand Down Expand Up @@ -141,7 +141,7 @@ class AuraRenderer extends PIXI.Graphics implements TokenAuraData {
.endFill();
this.textureContainer.position.set(bounds.x + radiusPixels, bounds.y + radiusPixels);

canvas.grid.grid.addChild(this.textureContainer);
canvas.interface.grid.addChild(this.textureContainer);
}

/** Highlight the affected grid squares of this aura and indicate the radius */
Expand Down Expand Up @@ -192,7 +192,7 @@ class AuraRenderer extends PIXI.Graphics implements TokenAuraData {
super.destroy(options);

if (this.textureContainer) {
canvas.grid.grid.removeChild(this.textureContainer);
canvas.interface.grid.removeChild(this.textureContainer);
if (!this.textureContainer.destroyed) this.textureContainer.destroy();
}
}
Expand Down
20 changes: 14 additions & 6 deletions src/module/canvas/token/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { EffectPF2e } from "@item";
import type { UserPF2e } from "@module/user/document.ts";
import type { TokenDocumentPF2e } from "@scene";
import * as R from "remeda";
import type { GridMeasurePathWaypoint } from "types/foundry/client/pixi/grid/base.d.ts";
import { measureDistanceCuboid, type CanvasPF2e, type TokenLayerPF2e } from "../index.ts";
import { HearingSource } from "../perception/hearing-source.ts";
import { AuraRenderers } from "./aura/index.ts";
Expand Down Expand Up @@ -35,12 +36,12 @@ class TokenPF2e<TDocument extends TokenDocumentPF2e = TokenDocumentPF2e> extends
if (this.document.hidden && !game.user.isGM) return false;

// Some tokens are always visible
if (!canvas.effects.visibility.tokenVision || this.controlled) return true;
if (!canvas.visibility.tokenVision || this.controlled) return true;

// Otherwise, test visibility against current sight polygons
if (canvas.effects.visionSources.get(this.sourceId)?.active) return true;
const tolerance = Math.floor(0.35 * Math.min(this.w, this.h));
return canvas.effects.visibility.testVisibility(this.center, { tolerance, object: this });
return canvas.visibility.testVisibility(this.center, { tolerance, object: this });
}

/** Is this token currently animating? */
Expand Down Expand Up @@ -77,10 +78,13 @@ class TokenPF2e<TDocument extends TokenDocumentPF2e = TokenDocumentPF2e> extends
get mechanicalBounds(): PIXI.Rectangle {
const bounds = super.bounds;
if (this.document.width < 1) {
const position = canvas.grid.getTopLeft(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
const position = canvas.grid.getTopLeftPoint({
x: bounds.x + bounds.width / 2,
y: bounds.y + bounds.height / 2,
});
return new PIXI.Rectangle(
position[0],
position[1],
position.x,
position.y,
Math.max(canvas.grid.size, bounds.width),
Math.max(canvas.grid.size, bounds.height),
);
Expand Down Expand Up @@ -453,7 +457,11 @@ class TokenPF2e<TDocument extends TokenDocumentPF2e = TokenDocumentPF2e> extends
if (this === target) return 0;

if (canvas.grid.type !== CONST.GRID_TYPES.SQUARE) {
return canvas.grid.measureDistance(this.position, target.position);
const waypoints: GridMeasurePathWaypoint[] = [
{ x: this.x, y: this.y },
{ x: target.x, y: target.y },
];
return canvas.grid.measurePath(waypoints).distance;
}

const selfElevation = this.document.elevation;
Expand Down
6 changes: 3 additions & 3 deletions src/module/scene/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class ScenePF2e extends Scene {
}

get lightLevel(): number {
return 1 - this.darkness;
return 1 - this.environment.darknessLevel;
}

get isBright(): boolean {
Expand Down Expand Up @@ -82,8 +82,8 @@ class ScenePF2e extends Scene {
);

if (this.rulesBasedVision) {
this.globalLight = true;
this.globalLightThreshold = 1 - (LightLevels.DARKNESS + 0.001);
this.environment.globalLight.enabled = true;
this.environment.globalLight.darkness.max = 1 - (LightLevels.DARKNESS + 0.001);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/module/scene/token-document/clown-car.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class PartyClownCar {
!placeable.checkCollision(s.center, { type: "move", mode: "any" }),
)
.reverse(), // Favor positions on the right
(s) => canvas.grid.measureDistance(center, s.center),
(s) => canvas.grid.measurePath([center, s.center]).distance,
);
}
}
Expand Down
9 changes: 6 additions & 3 deletions src/module/scene/token-document/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,13 @@ class TokenDocumentPF2e<TParent extends ScenePF2e | null = ScenePF2e | null> ext
get mechanicalBounds(): PIXI.Rectangle {
const bounds = this.bounds;
if (this.width < 1) {
const position = canvas.grid.getTopLeft(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
const position = canvas.grid.getTopLeftPoint({
x: bounds.x + bounds.width / 2,
y: bounds.y + bounds.height / 2,
});
return new PIXI.Rectangle(
position[0],
position[1],
position.x,
position.y,
Math.max(canvas.grid.size, bounds.width),
Math.max(canvas.grid.size, bounds.height),
);
Expand Down
2 changes: 1 addition & 1 deletion src/module/system/settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ export function registerSettings(): void {
if (ui.controls && canvas.activeLayer) {
ui.controls.initialize({ layer: canvas.activeLayer.constructor.layerOptions.name });
}
canvas.colorManager.initialize();
canvas.environment.initialize();
canvas.perception.update({ initializeVision: true }, true);
},
});
Expand Down
Loading

0 comments on commit 6aacae2

Please sign in to comment.