mirror of
https://github.com/Terncode/pixel.horse.git
synced 2026-12-03 05:10:04 +01:00
Add entity picker to map editor
This commit is contained in:
1 parent
4193a7a7b6
commit
8d4d3f663e
11 files changed
+659
-11
No files matched your search
@@ -0,0 +1,120 @@
|
||||
import * as entities from '../common/entities';
|
||||
import { Entity, EntityWorldState, defaultDrawOptions, Rect, PaletteManager } from '../common/interfaces';
|
||||
import { setPaletteManager } from '../common/mixins';
|
||||
import { mockPaletteManager } from '../common/ponyInfo';
|
||||
import { addRects } from '../common/rect';
|
||||
import { toScreenX, toScreenYWithZ } from '../common/positionUtils';
|
||||
import { drawCanvas } from '../graphics/contextSpriteBatch';
|
||||
import { TRANSPARENT } from '../common/colors';
|
||||
import { paletteSpriteSheet } from '../generated/sprites';
|
||||
|
||||
export function createEntitiesFromName(
|
||||
name: string, x: number, y: number, paletteManager: PaletteManager, worldState: EntityWorldState
|
||||
): Entity[] {
|
||||
const factory = (entities as any)[name];
|
||||
|
||||
if (typeof factory !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
setPaletteManager(paletteManager);
|
||||
|
||||
try {
|
||||
const created = typeof factory.type === 'number' ? factory(x, y, {}, worldState) : factory(x, y);
|
||||
const list: Entity[] = Array.isArray(created) ? created : [created];
|
||||
return list.filter(e => e && typeof e.type === 'number');
|
||||
}
|
||||
catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function getScreenBounds(entity: Entity): Rect | undefined {
|
||||
const bounds = entity.bounds;
|
||||
|
||||
if (!entity.draw || !bounds || bounds.w <= 0 || bounds.h <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
x: toScreenX(entity.x) + bounds.x,
|
||||
y: toScreenYWithZ(entity.y, entity.z) + bounds.y,
|
||||
w: bounds.w,
|
||||
h: bounds.h,
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_PREVIEW_SIZE = 512;
|
||||
const previewCache = new Map<string, HTMLCanvasElement | null>();
|
||||
|
||||
export function getEntityPreview(name: string, worldState: EntityWorldState): HTMLCanvasElement | null {
|
||||
const key = `${name}:${worldState.season}`;
|
||||
let preview = previewCache.get(key);
|
||||
|
||||
if (preview === undefined) {
|
||||
preview = renderEntityPreview(name, worldState);
|
||||
previewCache.set(key, preview);
|
||||
}
|
||||
|
||||
return preview;
|
||||
}
|
||||
|
||||
export function hasEntityPreview(name: string, worldState: EntityWorldState) {
|
||||
return previewCache.has(`${name}:${worldState.season}`);
|
||||
}
|
||||
|
||||
function renderEntityPreview(name: string, worldState: EntityWorldState): HTMLCanvasElement | null {
|
||||
const list = createEntitiesFromName(name, 0, 0, mockPaletteManager, worldState);
|
||||
const parts: { entity: Entity; bounds: Rect; }[] = [];
|
||||
|
||||
for (const entity of list) {
|
||||
const bounds = getScreenBounds(entity);
|
||||
|
||||
if (bounds) {
|
||||
parts.push({ entity, bounds });
|
||||
}
|
||||
}
|
||||
|
||||
if (!parts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const total = parts.map(p => p.bounds).reduce(addRects);
|
||||
const width = Math.min(Math.ceil(total.w), MAX_PREVIEW_SIZE);
|
||||
const height = Math.min(Math.ceil(total.h), MAX_PREVIEW_SIZE);
|
||||
|
||||
if (width <= 0 || height <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return drawCanvas(width, height, paletteSpriteSheet, undefined, batch => {
|
||||
batch.translate(-Math.floor(total.x), -Math.floor(total.y));
|
||||
const options = { ...defaultDrawOptions, shadowColor: TRANSPARENT, season: worldState.season };
|
||||
|
||||
for (const { entity } of parts) {
|
||||
entity.draw!(batch, options);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
console.warn(`failed to render preview of ${name}`, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function drawPreviewToCanvas(target: HTMLCanvasElement, preview: HTMLCanvasElement | null) {
|
||||
const context = target.getContext('2d')!;
|
||||
const { width, height } = target;
|
||||
context.clearRect(0, 0, width, height);
|
||||
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scale = Math.min(width / preview.width, height / preview.height, 2);
|
||||
const w = preview.width * scale;
|
||||
const h = preview.height * scale;
|
||||
context.imageSmoothingEnabled = scale < 1;
|
||||
context.drawImage(preview, Math.round((width - w) / 2), Math.round((height - h) / 2), w, h);
|
||||
}
|
||||
+70
-1
@@ -52,6 +52,7 @@ import { ClientSocketService } from '../components/services/gameService';
|
||||
import { attachDebugMethod, initFeatureFlags, updateRangeIndicator, initLogger, log, getSaysTime } from './clientUtils';
|
||||
import { restorePlayerPosition, savePlayerPosition } from './sec';
|
||||
import { drawEntityLights, drawEntityLightSprites, drawMap, drawDebugRegions } from './draw';
|
||||
import { createEntitiesFromName } from './entityPreview';
|
||||
import { updateTileSets, initializeTileHeightmaps, getTile } from '../common/tileUtils';
|
||||
import {
|
||||
downAction, upAction, turnHeadAction, boopAction, interact, toggleWall, editorMoveEntities,
|
||||
@@ -173,6 +174,8 @@ export class PonyTownGame implements Game {
|
||||
selectedEntities: [] as Entity[],
|
||||
customLight: false,
|
||||
lightColor: 'ffffff',
|
||||
placing: false,
|
||||
snapToTile: false,
|
||||
};
|
||||
incompleteSays: IncompleteSay[] = [];
|
||||
shadowColor = SHADOW_COLOR;
|
||||
@@ -269,6 +272,9 @@ export class PonyTownGame implements Game {
|
||||
private element?: HTMLElement;
|
||||
private showWallPlaceholder = false;
|
||||
private highlightEntity?: Entity;
|
||||
private editorGhost: Entity[] = [];
|
||||
private editorGhostKey = '';
|
||||
private editorGhostOffsets: { x: number; y: number; }[] = [];
|
||||
placeEntity = 0;
|
||||
placeTile = 0;
|
||||
constructor(
|
||||
@@ -1009,6 +1015,10 @@ export class PonyTownGame implements Game {
|
||||
editorDragEntities(this, hover, input.isPressed(Key.MOUSE_BUTTON2));
|
||||
}
|
||||
|
||||
if (BETA) {
|
||||
this.updateEditorGhost(hover);
|
||||
}
|
||||
|
||||
if (hasFlag(this.map.flags, MapFlags.EditableEntities)) {
|
||||
if (player.hold === removeEntitiesTool.type) {
|
||||
this.highlightEntity = pickEntities(this.map, hover, true, false, true)[0];
|
||||
@@ -1039,6 +1049,10 @@ export class PonyTownGame implements Game {
|
||||
if (BETA && this.editor.selectingEntities) {
|
||||
editorSelectEntities(this, hover, shift);
|
||||
}
|
||||
else if (BETA && this.isEditorPlacing) {
|
||||
const { x, y } = this.getEditorPlacePosition(hover);
|
||||
server.editorAction({ type: 'place', entity: this.editor.type, x, y });
|
||||
}
|
||||
else if (pickedEntity && (!holdingTool || !editableMap || hasFlag(pickedEntity.flags, EntityFlags.IgnoreTool))) {
|
||||
if (pickedEntity.type === PONY_TYPE) {
|
||||
this.select(pickedEntity as Pony);
|
||||
@@ -1096,7 +1110,10 @@ export class PonyTownGame implements Game {
|
||||
}
|
||||
|
||||
if (BETA && input.wasPressed(Key.MOUSE_BUTTON2)) {
|
||||
if (this.editor.selectingEntities) {
|
||||
if (this.isEditorPlacing) {
|
||||
this.editor.placing = false;
|
||||
}
|
||||
else if (this.editor.selectingEntities) {
|
||||
editorMoveEntities(this, hover);
|
||||
}
|
||||
else if (this.mod) {
|
||||
@@ -1788,11 +1805,63 @@ export class PonyTownGame implements Game {
|
||||
this.highlightEntity.draw(paletteBatch, this.drawOptions);
|
||||
paletteBatch.end();
|
||||
}
|
||||
|
||||
if (BETA && this.editorGhost.length && this.isEditorPlacing) {
|
||||
gl.uniform4fv(mapPaletteShader.uniforms.lighting, highlightColor);
|
||||
paletteBatch.begin();
|
||||
|
||||
for (const entity of this.editorGhost) {
|
||||
if (entity.draw) {
|
||||
entity.draw(paletteBatch, this.drawOptions);
|
||||
}
|
||||
}
|
||||
|
||||
paletteBatch.end();
|
||||
}
|
||||
}
|
||||
if (TIMING) {
|
||||
timeEnd();
|
||||
}
|
||||
}
|
||||
get isEditorPlacing() {
|
||||
return this.mod && this.editor.placing && !this.editor.selectingEntities && this.editor.tile === -1;
|
||||
}
|
||||
getEditorPlacePosition(hover: { x: number; y: number; }) {
|
||||
if (this.editor.snapToTile) {
|
||||
return { x: Math.floor(hover.x) + 0.5, y: Math.floor(hover.y) + 0.5 };
|
||||
}
|
||||
else {
|
||||
return { x: roundPositionX(hover.x), y: roundPositionY(hover.y) };
|
||||
}
|
||||
}
|
||||
private releaseEditorGhost() {
|
||||
this.editorGhost.forEach(releaseEntity);
|
||||
this.editorGhost = [];
|
||||
this.editorGhostKey = '';
|
||||
}
|
||||
private updateEditorGhost(hover: { x: number; y: number; }) {
|
||||
if (!this.isEditorPlacing || hover.x < 0 || isOutsideMap(hover.x, hover.y, this.map)) {
|
||||
if (this.editorGhost.length) {
|
||||
this.releaseEditorGhost();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { x, y } = this.getEditorPlacePosition(hover);
|
||||
const key = `${this.editor.type}:${this.season}`;
|
||||
|
||||
if (this.editorGhostKey !== key) {
|
||||
this.releaseEditorGhost();
|
||||
this.editorGhost = createEntitiesFromName(this.editor.type, 0, 0, this.paletteManager, this);
|
||||
this.editorGhostOffsets = this.editorGhost.map(e => ({ x: e.x, y: e.y }));
|
||||
this.editorGhostKey = key;
|
||||
}
|
||||
|
||||
this.editorGhost.forEach((entity, i) => {
|
||||
entity.x = x + this.editorGhostOffsets[i].x;
|
||||
entity.y = y + this.editorGhostOffsets[i].y;
|
||||
});
|
||||
}
|
||||
private updateCameraShift() {
|
||||
if (isMobile) {
|
||||
const isKeyboardOpen = !!document.activeElement && /input/i.test(document.activeElement.tagName);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { About } from './about/about';
|
||||
import { Account } from './account/account';
|
||||
import { Character } from './character/character';
|
||||
import { EditorBox } from './editor-box/editor-box';
|
||||
import { EntityPicker, EntityPreviewCanvas } from './entity-picker/entity-picker';
|
||||
|
||||
import { AuthGuard } from '../services/authGuard';
|
||||
import { RollbarService, rollbarFactory, RollbarErrorHandler } from '../services/rollbarErrorHandler';
|
||||
@@ -52,6 +53,8 @@ export const routes: Routes = [
|
||||
Account,
|
||||
Character,
|
||||
EditorBox,
|
||||
EntityPicker,
|
||||
EntityPreviewCanvas,
|
||||
],
|
||||
providers: [
|
||||
provideZoneChangeDetection(),
|
||||
|
||||
@@ -62,13 +62,23 @@
|
||||
.col-3
|
||||
input.form-control([(ngModel)]="entityLightSpriteY" type="number")
|
||||
|
||||
.input-group.input-group-sm
|
||||
input.form-control([(ngModel)]="editorEntity" placeholder="entity")
|
||||
.input-group-append(dropdown)
|
||||
button.btn.btn-default.dropdown-toggle(dropdownToggle)
|
||||
.dropdown-menu(*dropdownMenu style="max-height: 90vh; column-width: 100px; font-size: 10px;")
|
||||
a.dropdown-item(*ngFor="let e of editorEntities" (click)="editorEntity = e")
|
||||
| {{e}}
|
||||
.editor-entity-group.position-relative
|
||||
.btn-group
|
||||
button.btn.btn-sm.btn-default.d-flex.align-items-center(
|
||||
(click)="togglePicker()" [class.active]="showPicker" title="Pick entity")
|
||||
canvas.editor-entity-preview.me-1([entityPreview]="editorEntity" [worldState]="game" width="20" height="20")
|
||||
span.editor-entity-name {{editorEntity}}
|
||||
button.btn.btn-sm.btn-default(
|
||||
[btnHighlight]="placing" (click)="togglePlacing()"
|
||||
title="Place entities with left click (right click to stop)")
|
||||
fa-icon([icon]="placeIcon" [fixedWidth]="true")
|
||||
entity-picker.editor-entity-picker(
|
||||
*ngIf="showPicker"
|
||||
[names]="editorEntities"
|
||||
[selected]="editorEntity"
|
||||
[worldState]="game"
|
||||
(selectedChange)="pickEntity($event)"
|
||||
(close)="showPicker = false")
|
||||
|
||||
.dropdown.ms-1(dropdown)
|
||||
button.btn.btn-sm.btn-default.dropdown-toggle(dropdownToggle)
|
||||
@@ -80,6 +90,11 @@
|
||||
| Clear all entities
|
||||
a.dropdown-item((click)="listEntities()" title="List all placed entities in console")
|
||||
| List entities
|
||||
a.dropdown-item((click)="toggleSnap(); $event.stopPropagation()" title="Place entities in the center of tiles")
|
||||
fa-icon.me-1([icon]="editor.snapToTile ? checkIcon : emptyIcon" [fixedWidth]="true")
|
||||
| Snap to tile
|
||||
a.dropdown-item((click)="saveMap()" title="Save map and its seasonal layers to store folder")
|
||||
| Save map
|
||||
div(*ngIf="dev")
|
||||
h6.dropdown-header Show (numpad 4)
|
||||
a.dropdown-item(*ngFor="let field of showFields" (click)="toggleShow(field); $event.stopPropagation()")
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
.editor-entity-preview {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
|
||||
.editor-entity-name {
|
||||
max-width: 140px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.editor-entity-picker {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
margin-top: 4px;
|
||||
z-index: 1000;
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
import { Component, NgZone, ChangeDetectionStrategy } from '@angular/core';
|
||||
import { uniq } from 'lodash';
|
||||
import { faEdit, faCog, faDrawPolygon, faTrash, emptyIcon, faCheck } from '../../../client/icons';
|
||||
import { faEdit, faCog, faDrawPolygon, faTrash, emptyIcon, faCheck, faPaintbrush } from '../../../client/icons';
|
||||
import { PonyTownGame, engines } from '../../../client/game';
|
||||
import { StorageService } from '../../services/storageService';
|
||||
import { Model, getEntityNameFromType, getEntityNames } from '../../services/model';
|
||||
import { getAlpha, withAlpha, colorToHexRGB, parseColor } from '../../../common/color';
|
||||
import { BLACK } from '../../../common/colors';
|
||||
import { Entity, Engine, EngineInfo, DebugFlags, tileTypeNames } from '../../../common/interfaces';
|
||||
import { Entity, Engine, EngineInfo, DebugFlags, tileTypeNames, ChatType } from '../../../common/interfaces';
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.Eager,
|
||||
standalone: false,
|
||||
selector: 'editor-box',
|
||||
templateUrl: 'editor-box.pug',
|
||||
styleUrls: ['editor-box.scss'],
|
||||
})
|
||||
export class EditorBox {
|
||||
readonly dev = DEVELOPMENT;
|
||||
@@ -21,20 +22,23 @@ export class EditorBox {
|
||||
readonly selectIcon = faDrawPolygon;
|
||||
readonly deleteIcon = faTrash;
|
||||
readonly checkIcon = faCheck;
|
||||
readonly placeIcon = faPaintbrush;
|
||||
readonly emptyIcon = emptyIcon;
|
||||
readonly tiles = ['---', ...tileTypeNames];
|
||||
readonly engines = engines;
|
||||
readonly editorEntities: string[];
|
||||
readonly showFields: (keyof DebugFlags)[] = ['id', 'bounds', 'collider', 'cover', 'interact', 'trigger'];
|
||||
showPicker = false;
|
||||
private showEditor = false;
|
||||
constructor(
|
||||
public model: Model,
|
||||
private game: PonyTownGame,
|
||||
public game: PonyTownGame,
|
||||
private storage: StorageService,
|
||||
private zone: NgZone,
|
||||
) {
|
||||
this.game.editor.type = this.storage.getItem('editor-entity') || 'rock';
|
||||
this.showEditor = this.storage.getBoolean('show-editor');
|
||||
this.game.editor.snapToTile = this.storage.getBoolean('editor-snap');
|
||||
this.editorEntities = getEntityNames().slice().sort();
|
||||
}
|
||||
get editor() {
|
||||
@@ -56,6 +60,40 @@ export class EditorBox {
|
||||
this.game.editor.type = value;
|
||||
this.storage.setItem('editor-entity', value);
|
||||
}
|
||||
get placing() {
|
||||
return this.game.editor.placing;
|
||||
}
|
||||
togglePicker() {
|
||||
this.showPicker = !this.showPicker;
|
||||
}
|
||||
pickEntity(name: string) {
|
||||
this.editorEntity = name;
|
||||
this.game.editor.placing = true;
|
||||
this.game.editor.selectingEntities = false;
|
||||
this.game.editor.tile = -1;
|
||||
}
|
||||
togglePlacing() {
|
||||
this.game.editor.placing = !this.game.editor.placing;
|
||||
|
||||
if (this.game.editor.placing) {
|
||||
this.game.editor.selectingEntities = false;
|
||||
this.game.editor.tile = -1;
|
||||
}
|
||||
}
|
||||
toggleSnap() {
|
||||
this.game.editor.snapToTile = !this.game.editor.snapToTile;
|
||||
this.storage.setBoolean('editor-snap', this.game.editor.snapToTile);
|
||||
}
|
||||
saveMap() {
|
||||
const name = prompt('Save map as (saved to store folder)', 'map');
|
||||
|
||||
if (name && /^[a-z0-9_-]+$/i.test(name)) {
|
||||
this.game.send(server => server.say(0, `/savemap ${name}`, ChatType.Say));
|
||||
}
|
||||
else if (name) {
|
||||
alert('Invalid file name, use only letters, numbers, dashes and underscores');
|
||||
}
|
||||
}
|
||||
get editorTile() {
|
||||
return this.game.editor.tile;
|
||||
}
|
||||
@@ -182,6 +220,10 @@ export class EditorBox {
|
||||
toggleSelecting() {
|
||||
this.selectingEntities = !this.selectingEntities;
|
||||
|
||||
if (this.selectingEntities) {
|
||||
this.game.editor.placing = false;
|
||||
}
|
||||
|
||||
if (!this.selectingEntities) {
|
||||
this.editor.selectedEntities.length = 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
.entity-picker
|
||||
.entity-picker-header.d-flex.align-items-center.p-1
|
||||
.input-group.input-group-sm.flex-grow-1
|
||||
span.input-group-text
|
||||
fa-icon([icon]="searchIcon" [fixedWidth]="true")
|
||||
input.form-control(
|
||||
#searchInput
|
||||
[ngModel]="search"
|
||||
(ngModelChange)="setSearch($event)"
|
||||
(keydown)="keydown($event)"
|
||||
placeholder="search entities"
|
||||
aria-label="Search entities")
|
||||
span.text-muted.small.mx-2 {{filtered.length}}
|
||||
button.btn.btn-sm.btn-default((click)="closePicker()" title="Close" aria-label="Close")
|
||||
fa-icon([icon]="closeIcon" [fixedWidth]="true")
|
||||
.entity-picker-list(#list)
|
||||
button.entity-picker-item(
|
||||
*ngFor="let name of filtered; trackBy: trackByName"
|
||||
type="button"
|
||||
[class.active]="name === selected"
|
||||
[title]="name"
|
||||
(click)="select(name)")
|
||||
canvas([entityPreview]="name" [worldState]="worldState" width="64" height="64")
|
||||
.entity-picker-name {{name}}
|
||||
.text-muted.text-center.p-3.w-100(*ngIf="!filtered.length") no entities found
|
||||
@@ -0,0 +1,77 @@
|
||||
@import '../../../../styles/partials/variables';
|
||||
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.entity-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 420px;
|
||||
max-width: calc(100vw - 20px);
|
||||
height: 60vh;
|
||||
background: $dark-bg;
|
||||
border: 1px solid $border-color;
|
||||
border-radius: $border-radius-lg;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.entity-picker-list {
|
||||
flex: 1 1 auto;
|
||||
overflow-y: auto;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(76px, 1fr));
|
||||
grid-auto-rows: 92px;
|
||||
gap: 4px;
|
||||
padding: 4px;
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.entity-picker-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
padding: 2px;
|
||||
color: $body-color;
|
||||
background: $body-bg;
|
||||
border: 1px solid transparent;
|
||||
border-radius: $border-radius-sm;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
border-color: $border-color;
|
||||
background: lighten($body-bg, 5%);
|
||||
}
|
||||
|
||||
&.active {
|
||||
border-color: $link-color;
|
||||
background: lighten($body-bg, 8%);
|
||||
}
|
||||
|
||||
canvas {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
image-rendering: pixelated;
|
||||
background: repeating-conic-gradient(#3a3a3a 0% 25%, #444 0% 50%) 50% / 16px 16px;
|
||||
|
||||
&.entity-preview-empty {
|
||||
background: #2a2a2a;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.entity-picker-name {
|
||||
width: 100%;
|
||||
margin-top: 2px;
|
||||
font-size: 10px;
|
||||
line-height: 1.2;
|
||||
text-align: center;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.input-group-text {
|
||||
color: #000;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import {
|
||||
Component, ChangeDetectionStrategy, Input, Output, EventEmitter, ElementRef, NgZone, OnDestroy, AfterViewInit,
|
||||
ViewChild, Directive, DoCheck, inject, OnChanges, ChangeDetectorRef
|
||||
} from '@angular/core';
|
||||
import { faTimes, faSearch } from '../../../client/icons';
|
||||
import { EntityWorldState, defaultWorldState } from '../../../common/interfaces';
|
||||
import { getEntityPreview, drawPreviewToCanvas, hasEntityPreview } from '../../../client/entityPreview';
|
||||
import { loadAndInitSpriteSheets } from '../../../client/loadSprites';
|
||||
|
||||
const FRAME_BUDGET = 8;
|
||||
|
||||
class PreviewScheduler {
|
||||
private queue: EntityPreviewCanvas[] = [];
|
||||
private frame = 0;
|
||||
ready = false;
|
||||
constructor(private zone: NgZone) {
|
||||
loadAndInitSpriteSheets().then(() => {
|
||||
this.ready = true;
|
||||
this.schedule();
|
||||
});
|
||||
}
|
||||
add(canvas: EntityPreviewCanvas) {
|
||||
if (this.queue.indexOf(canvas) === -1) {
|
||||
this.queue.push(canvas);
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
remove(canvas: EntityPreviewCanvas) {
|
||||
const index = this.queue.indexOf(canvas);
|
||||
|
||||
if (index !== -1) {
|
||||
this.queue.splice(index, 1);
|
||||
}
|
||||
}
|
||||
private schedule() {
|
||||
if (this.ready && !this.frame && this.queue.length) {
|
||||
this.zone.runOutsideAngular(() => this.frame = requestAnimationFrame(this.process));
|
||||
}
|
||||
}
|
||||
private process = () => {
|
||||
this.frame = 0;
|
||||
const start = performance.now();
|
||||
|
||||
while (this.queue.length && performance.now() - start < FRAME_BUDGET) {
|
||||
this.queue.shift()!.draw();
|
||||
}
|
||||
|
||||
this.schedule();
|
||||
};
|
||||
}
|
||||
|
||||
let scheduler: PreviewScheduler | undefined;
|
||||
|
||||
function getScheduler(zone: NgZone) {
|
||||
return scheduler || (scheduler = new PreviewScheduler(zone));
|
||||
}
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
standalone: false,
|
||||
selector: 'entity-picker',
|
||||
templateUrl: 'entity-picker.pug',
|
||||
styleUrls: ['entity-picker.scss'],
|
||||
})
|
||||
export class EntityPicker implements OnChanges, AfterViewInit, OnDestroy {
|
||||
readonly closeIcon = faTimes;
|
||||
readonly searchIcon = faSearch;
|
||||
@Input() names: string[] = [];
|
||||
@Input() selected = '';
|
||||
@Input() worldState: EntityWorldState = defaultWorldState;
|
||||
@Output() selectedChange = new EventEmitter<string>();
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@ViewChild('list', { static: true }) list!: ElementRef<HTMLElement>;
|
||||
@ViewChild('searchInput', { static: true }) searchInput!: ElementRef<HTMLInputElement>;
|
||||
search = '';
|
||||
filtered: string[] = [];
|
||||
observer?: IntersectionObserver;
|
||||
private observed = new Map<Element, EntityPreviewCanvas>();
|
||||
constructor(private zone: NgZone, private cd: ChangeDetectorRef) {
|
||||
}
|
||||
ngOnChanges() {
|
||||
this.updateFiltered();
|
||||
}
|
||||
ngAfterViewInit() {
|
||||
this.zone.runOutsideAngular(() => {
|
||||
this.observer = new IntersectionObserver(entries => {
|
||||
for (const entry of entries) {
|
||||
const canvas = this.observed.get(entry.target);
|
||||
|
||||
if (canvas) {
|
||||
canvas.setVisible(entry.isIntersecting);
|
||||
}
|
||||
}
|
||||
}, { root: this.list.nativeElement, rootMargin: '150px 0px' });
|
||||
|
||||
this.observed.forEach((_, element) => this.observer!.observe(element));
|
||||
});
|
||||
|
||||
setTimeout(() => this.searchInput.nativeElement.focus());
|
||||
}
|
||||
ngOnDestroy() {
|
||||
if (this.observer) {
|
||||
this.observer.disconnect();
|
||||
}
|
||||
}
|
||||
setSearch(value: string) {
|
||||
this.search = value || '';
|
||||
this.updateFiltered();
|
||||
this.cd.detectChanges();
|
||||
}
|
||||
select(name: string) {
|
||||
this.selected = name;
|
||||
this.zone.run(() => this.selectedChange.emit(name));
|
||||
this.cd.detectChanges();
|
||||
}
|
||||
private updateFiltered() {
|
||||
const words = this.search.toLowerCase().split(/\s+/).filter(x => !!x);
|
||||
this.filtered = (this.names || []).filter(name => {
|
||||
const lower = name.toLowerCase();
|
||||
return words.every(w => lower.indexOf(w) !== -1);
|
||||
});
|
||||
}
|
||||
closePicker() {
|
||||
this.zone.run(() => this.close.emit());
|
||||
}
|
||||
keydown(e: KeyboardEvent) {
|
||||
e.stopPropagation();
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
this.closePicker();
|
||||
}
|
||||
else if (e.key === 'Enter' && this.filtered.length) {
|
||||
this.select(this.filtered[0]);
|
||||
}
|
||||
}
|
||||
trackByName(_: number, name: string) {
|
||||
return name;
|
||||
}
|
||||
observe(canvas: EntityPreviewCanvas) {
|
||||
const element = canvas.element.nativeElement;
|
||||
this.observed.set(element, canvas);
|
||||
|
||||
if (this.observer) {
|
||||
this.observer.observe(element);
|
||||
}
|
||||
}
|
||||
unobserve(canvas: EntityPreviewCanvas) {
|
||||
const element = canvas.element.nativeElement;
|
||||
this.observed.delete(element);
|
||||
|
||||
if (this.observer) {
|
||||
this.observer.unobserve(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Directive({
|
||||
standalone: false,
|
||||
selector: 'canvas[entityPreview]',
|
||||
})
|
||||
export class EntityPreviewCanvas implements DoCheck, OnDestroy {
|
||||
@Input() entityPreview = '';
|
||||
@Input() worldState: EntityWorldState = defaultWorldState;
|
||||
private visible: boolean;
|
||||
private drawn = '';
|
||||
private scheduler: PreviewScheduler;
|
||||
readonly element: ElementRef<HTMLCanvasElement> = inject(ElementRef);
|
||||
private picker = inject(EntityPicker, { optional: true });
|
||||
constructor() {
|
||||
this.scheduler = getScheduler(inject(NgZone));
|
||||
this.visible = !this.picker;
|
||||
|
||||
if (this.picker) {
|
||||
this.picker.observe(this);
|
||||
}
|
||||
}
|
||||
ngDoCheck() {
|
||||
this.update();
|
||||
}
|
||||
ngOnDestroy() {
|
||||
this.scheduler.remove(this);
|
||||
|
||||
if (this.picker) {
|
||||
this.picker.unobserve(this);
|
||||
}
|
||||
}
|
||||
setVisible(visible: boolean) {
|
||||
this.visible = visible;
|
||||
this.update();
|
||||
}
|
||||
draw() {
|
||||
const key = this.key;
|
||||
|
||||
if (this.visible && this.drawn !== key) {
|
||||
this.drawn = key;
|
||||
const preview = getEntityPreview(this.entityPreview, this.worldState);
|
||||
drawPreviewToCanvas(this.element.nativeElement, preview);
|
||||
this.element.nativeElement.classList.toggle('entity-preview-empty', !preview);
|
||||
}
|
||||
}
|
||||
private get key() {
|
||||
return `${this.entityPreview}:${this.worldState.season}`;
|
||||
}
|
||||
private update() {
|
||||
if (!this.visible) {
|
||||
this.scheduler.remove(this);
|
||||
}
|
||||
else if (this.drawn !== this.key) {
|
||||
if (this.scheduler.ready && hasEntityPreview(this.entityPreview, this.worldState)) {
|
||||
this.draw();
|
||||
}
|
||||
else {
|
||||
this.scheduler.add(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -681,6 +681,9 @@ export class ServerActions implements IServerActions, SocketServer {
|
||||
|
||||
switch (action.type) {
|
||||
case 'place':
|
||||
validateNumber(action.x, 'x');
|
||||
validateNumber(action.y, 'y');
|
||||
|
||||
if (includes(allEntities, action.entity)) {
|
||||
const name = action.entity;
|
||||
const entity = (entities as any)[name](action.x, action.y);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { loadSprites } from '../lib';
|
||||
import { expect } from 'chai';
|
||||
import * as entities from '../../common/entities';
|
||||
import { defaultWorldState } from '../../common/interfaces';
|
||||
import { Season } from '../../common/commonInterfaces';
|
||||
import { mockPaletteManager } from '../../common/ponyInfo';
|
||||
import { allEntities } from '../../server/api/account';
|
||||
import { createEntitiesFromName, getEntityPreview, hasEntityPreview } from '../../client/entityPreview';
|
||||
|
||||
describe('entityPreview', () => {
|
||||
before(loadSprites);
|
||||
|
||||
describe('createEntitiesFromName()', () => {
|
||||
it('creates entity at given position', () => {
|
||||
const [entity] = createEntitiesFromName('barrel', 1, 2, mockPaletteManager, defaultWorldState);
|
||||
|
||||
expect(entity.type).equal(entities.barrel.type);
|
||||
expect(entity.x).equal(1);
|
||||
expect(entity.y).equal(2);
|
||||
});
|
||||
|
||||
it('creates all parts of multi part entities', () => {
|
||||
expect(createEntitiesFromName('tree', 0, 0, mockPaletteManager, defaultWorldState).length).greaterThan(1);
|
||||
});
|
||||
|
||||
it('returns empty list for unknown name', () => {
|
||||
expect(createEntitiesFromName('not-an-entity', 0, 0, mockPaletteManager, defaultWorldState)).eql([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getEntityPreview()', () => {
|
||||
it('renders preview of an entity', () => {
|
||||
const preview = getEntityPreview('barrel', defaultWorldState)!;
|
||||
|
||||
expect(preview).not.equal(null);
|
||||
expect(preview.width).greaterThan(0);
|
||||
expect(preview.height).greaterThan(0);
|
||||
});
|
||||
|
||||
it('returns null for entities that are not drawn', () => {
|
||||
expect(getEntityPreview('triggerDoor', defaultWorldState)).equal(null);
|
||||
});
|
||||
|
||||
it('caches previews per season', () => {
|
||||
const summer = getEntityPreview('tree', { season: Season.Summer });
|
||||
|
||||
expect(getEntityPreview('tree', { season: Season.Summer })).equal(summer);
|
||||
expect(hasEntityPreview('tree', { season: Season.Winter })).equal(false);
|
||||
});
|
||||
|
||||
it('renders all editor entities without errors', () => {
|
||||
for (const name of allEntities) {
|
||||
expect(() => getEntityPreview(name, defaultWorldState), name).not.throw();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user