First Commit

This commit is contained in:
2025-08-07 20:20:36 +02:00
parent 025d539fc5
commit 21f637fcec
37 changed files with 4620 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

69
README.md Normal file
View File

@@ -0,0 +1,69 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { globalIgnores } from 'eslint/config'
export default tseslint.config([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hammer</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3375
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

29
package.json Normal file
View File

@@ -0,0 +1,29 @@
{
"name": "hammer",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0",
"eslint": "^9.30.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.35.1",
"vite": "^7.0.4"
}
}

1
public/vite.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

167
src/App.tsx Normal file
View File

@@ -0,0 +1,167 @@
import { useEffect, useRef } from "react"
import { Hammer } from "./classes/Hammer";
function App() {
// ? elements
// * Canvas
const canvas = useRef(null);
// * Buttons
const button_set_tilesheet = useRef(null);
const button_import_map = useRef(null);
// * Divs
const div_progress_bar = useRef(null);
const div_progress = useRef(null);
const div_view_tiles = useRef(null);
// * Input (a part)
const inputFileTilesheet = useRef<HTMLInputElement>(null);
const inputFileMap = useRef<HTMLInputElement>(null);
// ? hammer
const hammerRef = useRef<Hammer | null>(null);
useEffect(() => {
hammerRef.current = new Hammer();
hammerRef.current.helements.setElement("canvas", canvas.current);
hammerRef.current.helements.setElement("button_set_tilesheet", button_set_tilesheet.current);
hammerRef.current.helements.setElement("button_import_map", button_import_map.current);
hammerRef.current.helements.setElement("div_progress_bar", div_progress_bar.current);
hammerRef.current.helements.setElement("div_progress", div_progress.current);
hammerRef.current.helements.setElement("div_view_tiles", div_view_tiles.current);
return () => {
hammerRef.current?.hevent.destroy();
}
}, []);
// ? functions
const handleLoadTilesheet = () => {
if (hammerRef.current != null) {
const files = inputFileTilesheet.current?.files;
if (files && files?.length > 0) {
hammerRef.current.loadTileSheet(files[0]);
}
}
}
const handleLoadMap = async () => {
if (hammerRef.current != null) {
const files = inputFileMap.current?.files;
if (files && files.length > 0) {
hammerRef.current.hconsole.push("Importing the current map...");
// ? Verif du format
let filenameSplit = files[0].name.split(".");
if (!["tmpx"].includes(filenameSplit[filenameSplit.length - 1])) {
return hammerRef.current.hconsole.push("File format invalid !", "ERROR")
};
try {
let reader = new FileReader();
reader.readAsText(files[0], "UTF-8");
reader.onload = (evt) => {
if (evt.target) {
const data = JSON.parse(evt.target.result as string);
if (hammerRef.current) {
const tl = new Image();
tl.src = data.tilesheet;
tl.onload = () => {
if (hammerRef.current) {
hammerRef.current.setTileSheet(tl);
hammerRef.current.tileMap = data.map;
}
};
}
}
}
} catch (error) {
hammerRef.current.hconsole.push("Error importing map.", "ERROR");
}
}
}
}
return (
<>
<div ref={div_progress_bar} className="progress-bar nodisplay">
<div ref={div_progress} className="progress"></div>
</div>
<div className="div-hammer-container">
<div className="tools">
<button onClick={() => inputFileMap.current?.click()} ref={button_import_map}><img src="/src/assets/images/import.png" alt="import" />
<span>Import Map (I)</span>
<input type="file" id="inputFileMap" ref={inputFileMap} onChange={handleLoadMap} className="nodisplay" accept=".tmpx" />
</button>
<button onClick={() => { hammerRef.current && hammerRef.current.mapToJson() }}>
<img src="/src/assets/images/save.png" alt="save" />
<span>Save local copy (ctrl + s)</span>
</button>
<hr />
<button onClick={() => inputFileTilesheet.current?.click()} ref={button_set_tilesheet}>
<img src="/src/assets/images/palet.png" alt="palet" />
<span>Upload Tilesheet (U)</span>
<input type="file" id="inputFileTS" ref={inputFileTilesheet} onChange={handleLoadTilesheet} className="nodisplay" accept="image/png, image/jpg, image/jpeg" />
</button>
<button onClick={() => { if (hammerRef.current) { hammerRef.current.tool = "draw"; } }}>
<img src="/src/assets/images/pen.png" alt="pen" />
<span>Draw (D)</span>
</button>
<button onClick={() => { if (hammerRef.current) { hammerRef.current.tool = "eraser"; } }}>
<img src="/src/assets/images/erase.png" alt="erase" />
<span>Erase (E)</span>
</button>
<button>
<img src="/src/assets/images/bucket.png" alt="bucket" />
<span>Bucket (B)</span>
</button>
<button>
<img src="/src/assets/images/rect.png" alt="rect" />
<span>Rectangle (R)</span>
</button>
<button>
<img src="/src/assets/images/measure.png" alt="measure" />
<span>Measure (M)</span>
</button>
<hr />
<button>
<img src="/src/assets/images/center.png" alt="center" onClick={() => hammerRef.current && hammerRef.current.centerView()} />
<span>Center view (C)</span>
</button>
</div>
<div className="div-container-map">
<div className="container-tiles">
<div ref={div_view_tiles} className="div-scroll-tiles">
</div>
</div>
<div className="div-container-view">
<div className="div-canvas-container">
<canvas ref={canvas} id="canvasHammer"></canvas>
</div>
<div className="div-console" contentEditable="true">
</div>
</div>
</div>
</div>
</>
)
}
export default App

BIN
src/assets/images/bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 B

BIN
src/assets/images/erase.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 B

BIN
src/assets/images/palet.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

BIN
src/assets/images/pen.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 B

BIN
src/assets/images/rect.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 B

BIN
src/assets/images/save.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 B

View File

@@ -0,0 +1,176 @@
import { FloorToMultiple } from "../utils/math";
import type { EditorManager } from "./EditorManager";
import type { EventsManager } from "./EventManager";
import type { HammerConsole } from "./HammerConsole";
import type { Tile } from "./Tile";
export class CanvasManager {
canvas: HTMLCanvasElement | null = null;
hevent: EventsManager;
hconsole: HammerConsole;
heditor: EditorManager;
zoom: number = 0.5;
canvasOffset = { x: 0, y: 0 };
CanvasRectSelectPosition: { x: number, y: number } | null = null
realMousePosition: { x: number, y: number } | null = null;
mousePositionMap: { x: number, y: number } | null = null;
canvasMoveClick: boolean = false;
constructor(hevent: EventsManager, hconsole : HammerConsole, heditor : EditorManager) {
this.hevent = hevent;
this.hconsole = hconsole;
this.heditor = heditor;
}
setCanvas(canvas: HTMLCanvasElement) {
this.canvas = canvas;
this.hevent.addEvent(this.canvas, "mouseleave", () => this.CanvasRectSelectPosition = null);
this.hevent.addEvent(this.canvas, "mousemove", (e) => {
this.updateCursor(e.clientX, e.clientY);
let pos = { x: e.clientX, y: e.clientY };
if (this.realMousePosition != null && this.canvasMoveClick) {
this.canvasOffset.x += Math.round((pos.x - this.realMousePosition.x) * this.zoom);
this.canvasOffset.y += Math.round((pos.y - this.realMousePosition.y) * this.zoom);
}
this.realMousePosition = { x: pos.x, y: pos.y };
});
// ? Gerer le zoom
this.hevent.addEvent(this.canvas, "wheel", (e) => {
e.preventDefault();
const zoomIntensity = 0.009 ;
const delta = e.deltaY < 0 ? 1 - zoomIntensity : 1 + zoomIntensity;
this.zoom *= delta;
console.log(this.zoom);
if (this.zoom > 1.5) {
this.zoom = 1.5;
}
if (this.zoom < 0.05) {
this.zoom = 0.05;
}
this.updateCursor(e.clientX, e.clientY);
});
// ? Activer le mouvement du monde
this.hevent.addEvent(this.canvas, "mousedown", (e) => this.canvasMoveClick = e.button == 2 && true);
// ? Desactiver le mouvement du monde
this.hevent.addEvent(document.body, "mouseup", (e) => this.canvasMoveClick = e.button == 2 && false);
// ? Gestion des clicks pour les tools
this.hevent.addEvent(this.canvas, "click", () => {
if (this.heditor.tool == "draw") {
const tilespos = this.heditor.tileMap.filter((t) => (t.x == this.mousePositionMap?.x && t.y == this.mousePositionMap?.y));
if (this.mousePositionMap && tilespos.length < 2) {
if (tilespos.length == 1 && tilespos[0].tile == this.heditor.selected_tile) return;
this.heditor.tileMap.push({ tile: this.heditor.selected_tile, x: this.mousePositionMap.x, y: this.mousePositionMap.y });
this.hconsole.push(`Tile (${this.mousePositionMap.x / 16}, ${this.mousePositionMap.y / 16}) placed !`);
}
} else if (this.heditor.tool == "eraser") {
this.heditor.tileMap = this.heditor.tileMap.filter((t) => !(t.x == this.mousePositionMap?.x && t.y == this.mousePositionMap?.y));
if (this.mousePositionMap) {
this.hconsole.push(`Tile (${this.mousePositionMap.x / 16}, ${this.mousePositionMap.y / 16}) deleted !`);
}
}
});
}
updateCursor(x: number, y: number) {
if (this.canvas) {
const pos = {
x: ((x - this.canvas.getClientRects()[0].left) * this.zoom) - (this.canvasOffset.x % 16),
y: ((y - this.canvas.getClientRects()[0].top) * this.zoom) - (this.canvasOffset.y % 16)
}
this.CanvasRectSelectPosition = FloorToMultiple(pos, 16, 16);
const pos1 = {
x: ((x - this.canvas.getClientRects()[0].left) * this.zoom) - this.canvasOffset.x,
y: ((y - this.canvas.getClientRects()[0].top) * this.zoom) - this.canvasOffset.y
}
this.mousePositionMap = FloorToMultiple(pos1, 16, 16);
}
}
update() {
if (this.canvas) {
this.canvas.style.cursor = this.canvasMoveClick ? "grab" : ""
const width = this.canvas.getClientRects()[0].width;
const height = this.canvas.getClientRects()[0].height;
this.canvas.width = width * this.zoom;
this.canvas.height = height * this.zoom;
this.canvas.style.width = `${width}px`;
this.canvas.style.height = `${height}px`;
}
}
draw(tiles: Tile[], tileMap: { x: number, y: number, tile: number }[], emptyTile: Tile) {
if (this.canvas) {
const ctx = this.canvas.getContext("2d");
const width = this.canvas.getClientRects()[0].width;
const height = this.canvas.getClientRects()[0].height;
if (ctx) {
// ? Reset le canvas
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// ? afficher le centre de la map
ctx.strokeStyle = "white";
ctx.globalAlpha = 0.3;
ctx.beginPath();
ctx.moveTo(0 + this.canvasOffset.x, 0 + this.canvasOffset.y - 32);
ctx.lineTo(0 + this.canvasOffset.x, 0 + this.canvasOffset.y + 32);
ctx.stroke();
ctx.moveTo(0 + this.canvasOffset.x - 32, 0 + this.canvasOffset.y);
ctx.lineTo(0 + this.canvasOffset.x + 32, 0 + this.canvasOffset.y);
ctx.stroke();
// ? Gestion des tiles
ctx.globalAlpha = 1;
// * Exemple :
// if (this.tiles.length > 0) {
// if (this.emptyTile && this.emptyTile.tile) {
// ctx.drawImage(this.emptyTile.tile, (16 * 0) + this.canvasOffset.x, (16 * 0) + this.canvasOffset.y, 16, 16);
// }
// }
if (tiles.length !== 0) {
tileMap.forEach((t) => {
if (t.x + this.canvasOffset.x >= -16 && t.x + this.canvasOffset.x <= width * this.zoom && t.y + this.canvasOffset.y >= -16 && t.y + this.canvasOffset.y <= height * this.zoom) {
if (tiles.length >= t.tile + 1) {
const ti = tiles[t.tile].tile;
if (ti) {
ctx.drawImage(ti, t.x + this.canvasOffset.x, t.y + this.canvasOffset.y, 16, 16);
}
} else {
if (emptyTile && emptyTile.tile) {
ctx.drawImage(emptyTile.tile, t.x + this.canvasOffset.x, t.y + this.canvasOffset.y, 16, 16);
}
}
}
});
}
// ? Afficher la position du curseur :
if (this.CanvasRectSelectPosition != null) {
ctx.fillStyle = "white";
ctx.globalAlpha = 0.2
ctx.fillRect(this.CanvasRectSelectPosition.x + (this.canvasOffset.x % 16), this.CanvasRectSelectPosition.y + (this.canvasOffset.y % 16), 16, 16);
}
}
}
}
centerView() {
if (this.canvas) {
const width = this.canvas.getClientRects()[0].width;
const height = this.canvas.getClientRects()[0].height;
this.canvasOffset.x = Math.round(width / 2 * this.zoom);
this.canvasOffset.y = Math.round(height / 2 * this.zoom);
}
}
}

View File

@@ -0,0 +1,6 @@
export class EditorManager {
tool : "draw" | "eraser" = "draw";
selected_tile: number = 0;
displayImageEaster: boolean = false;
tileMap: { x: number, y: number, tile: number }[] = [];
}

View File

@@ -0,0 +1,32 @@
import type { EventsManager } from "./EventManager";
export class ElementManager {
loaded = false;
elements: {
canvas : HTMLCanvasElement | null;
button_set_tilesheet: HTMLButtonElement | null;
button_import_map: HTMLButtonElement | null;
div_progress_bar : HTMLDivElement | null;
div_progress : HTMLDivElement | null;
div_view_tiles: HTMLDivElement | null;
} = {
canvas: null,
button_set_tilesheet: null,
button_import_map: null,
div_progress_bar: null,
div_progress: null,
div_view_tiles: null,
};
constructor(eventManager: EventsManager) {
eventManager.addEvent(document, "DOMContentLoaded", () => {
this.loaded = true;
});
}
setElement(name: keyof ElementManager["elements"], el: null) {
this.elements[name] = el;
}
}

View File

@@ -0,0 +1,17 @@
export class EventsManager {
events: { target: EventTarget, type: string, handler: EventListenerOrEventListenerObject }[] = [];
addEvent<K extends keyof DocumentEventMap>(target: EventTarget, type: K, handler: (e: DocumentEventMap[K]) => void) {
// @ts-expect-error
this.events.push({ target, type, handler });
// @ts-expect-error
target.addEventListener(type, handler);
}
destroy() {
this.events.forEach((e) => {
e.target.removeEventListener(e.type, e.handler);
});
}
}

176
src/classes/Hammer.ts Normal file
View File

@@ -0,0 +1,176 @@
import { DownloadTextFile, IsFilenameFormat } from "../utils/file";
import { ImageToString, WaitImgByFile } from "../utils/image";
import { CanvasManager } from "./CanvasManager";
import { EditorManager } from "./EditorManager";
import { ElementManager } from "./ElementManager";
import { EventsManager } from "./EventManager";
import { HammerConsole } from "./HammerConsole";
import { HammerLoader } from "./HammerLoader";
import { Tile } from "./Tile";
export class Hammer {
canvas: HTMLCanvasElement | null = null;
inputTileSheet: HTMLInputElement | null = null;
tilesheet: HTMLImageElement | null = null;
tiles: Tile[] = [];
emptyTile: Tile | null = null;
// * utils
hconsole: HammerConsole = new HammerConsole();
hevent: EventsManager = new EventsManager();
helements: ElementManager = new ElementManager(this.hevent);
hloader: HammerLoader = new HammerLoader(this.helements);
heditor : EditorManager = new EditorManager();
hcanvas: CanvasManager = new CanvasManager(this.hevent, this.hconsole, this.heditor);
constructor() {
// ? Desactiver le context menu
this.hevent.addEvent(document, "contextmenu", (e) => e.preventDefault());
// ? Raccourcis clavier
this.hevent.addEvent(document, "keydown", (e: KeyboardEvent) => {
const keypress = e.key;
if (keypress === "c") {
e.preventDefault();
this.hcanvas.centerView();
} else if (keypress === "u") {
e.preventDefault();
this.helements.elements.button_set_tilesheet?.click();
} else if (keypress === "e") {
e.preventDefault();
this.heditor.tool = "eraser";
} else if (keypress === "d") {
e.preventDefault();
this.heditor.tool = "draw";
} else if (keypress === "F9") {
e.preventDefault();
this.heditor.displayImageEaster = !this.heditor.displayImageEaster;
this.hconsole.push("It's a Easter egg! Value : " + this.heditor.displayImageEaster, "DEBUG");
} else if (e.ctrlKey && keypress == "s") {
e.preventDefault();
this.mapToJson();
}
});
// ? Lancer l'affichage du canvas
this.resetTiles();
this.displayCanvas();
// ? Load de la tile empty
const imgemp = new Image();
imgemp.src = "/src/assets/images/missing_texture.png";
imgemp.onload = async () => {
this.emptyTile = new Tile(0, 0, imgemp);
await this.emptyTile.loadTile();
};
}
mapToJson() {
if (this.tilesheet == null) return this.hconsole.push("Tilesheet not exist !", "ERROR");
const tilesheet_string = ImageToString(this.tilesheet);
if (tilesheet_string)
DownloadTextFile(JSON.stringify({ tilesheet: tilesheet_string, map: this.heditor.tileMap }), "my_map.tmpx");
else
return this.hconsole.push("An error has occurred !", "ERROR");
}
resetTiles() {
if (this.helements.elements.div_view_tiles)
this.helements.elements.div_view_tiles.innerHTML = "";
this.tiles = [];
this.tilesheet = null;
}
async displayCanvas() {
if (this.canvas != null && this.emptyTile) {
// ? Update le canvas
this.hcanvas.update();
// ? Affichage des datas
this.hcanvas.draw(this.tiles, this.heditor.tileMap, this.emptyTile);
} else {
// ? charger le canvas
this.canvas = this.helements.elements.canvas;
if (this.canvas != null) {
this.hcanvas.setCanvas(this.canvas);
this.hcanvas.centerView();
}
}
// ? Relancer la function
requestAnimationFrame(this.displayCanvas.bind(this));
}
async loadTileSheet(file: File) {
// ? Verif du format
if (!IsFilenameFormat(["png", "jpg", "jpeg"], file.name)) {
this.hloader.reset();
return this.hconsole.push("File format invalid !", "ERROR")
};
// ? Generer une image sur base du fichier
await this.setTileSheet(await WaitImgByFile(file));
}
async setTileSheet(img: HTMLImageElement) {
// ? Save le tilesheet
this.tilesheet = img;
// ? desactiver le bouton pour add des ts
if (this.helements.elements.button_set_tilesheet)
this.helements.elements.button_set_tilesheet.disabled = true;
if (this.helements.elements.button_import_map)
this.helements.elements.button_import_map.disabled = true;
// ? Reset l'ancien ts
this.resetTiles();
// ? Recup le nombre
const tilesMax = Math.floor(img.width / 16) * Math.floor(img.height / 16);
this.hloader.loadingMax = tilesMax;
this.hloader.setValue(0);
// ? Loader les tiles
let i = 0;
for (let x = 0; x < img.width; x += 16) {
for (let y = 0; y < img.height; y += 16) {
const t = new Tile(x, y, img);
await t.loadTile();
if (!t.fullyTransparent) {
this.tiles.push(t);
if (this.heditor.displayImageEaster) {
this.heditor.tileMap.push({ tile: this.tiles.length - 1, x, y });
}
const tile = t.tile;
if (tile) {
const id = this.tiles.length - 1;
tile.id = "t_" + id;
tile.addEventListener("click", () => {
this.heditor.selected_tile = id;
});
t.tile && this.helements.elements.div_view_tiles?.appendChild(tile);
}
}
i++;
this.hconsole.push("Loading tile (" + i + "/" + tilesMax + ")", "INFO", "LOADER");
this.hloader.setValue(i);
}
}
// ? Log et remettre tous correctement
this.hconsole.push(`TileSheet Loaded ! (${this.tiles.length} tiles)`, "INFO");
this.hloader.reset();
if (this.helements.elements.button_set_tilesheet)
this.helements.elements.button_set_tilesheet.disabled = false;
if (this.helements.elements.button_import_map)
this.helements.elements.button_import_map.disabled = false;
}
}

View File

@@ -0,0 +1,38 @@
export class HammerConsole {
div: HTMLDivElement | null = null;
initialHeight: number = 0;
lastP: HTMLParagraphElement | null = null;
constructor() {
this.div = document.querySelector(".div-console");
if (this.div) {
this.initialHeight = this.div.scrollHeight;
}
}
push(text: string, status: "INFO" | "ERROR" | "WARN" | "DEBUG" = "INFO", type: "NORMAL" | "LOADER" = "NORMAL") {
if (this.div == null) {
this.div = document.querySelector(".div-console");
}
let p = this.lastP;
if (this.lastP == null || type == "NORMAL") {
p = document.createElement("p");
} else {
p = this.lastP;
}
p.style.color = (
status == "INFO" ? 'white' :
status == "DEBUG" ? 'blue' :
status == "ERROR" ? 'red' : 'yellow'
);
p.textContent = `[${status}] ` + text;
this.lastP = type == "LOADER" ? p : null;
this.div?.appendChild(p);
if (this.div) {
this.div.scrollTop = this.div.scrollHeight;
}
}
}

View File

@@ -0,0 +1,31 @@
import type { ElementManager } from "./ElementManager";
export class HammerLoader {
loadingMax: number = 0;
loadingValue: number = 0;
elements: ElementManager;
constructor(elements : ElementManager) {
this.elements = elements;
}
setValue(value: number) {
this.loadingValue = value;
const progress = this.elements.elements.div_progress;
const progressValue = this.elements.elements.div_progress_bar;
if (progress && progressValue) {
progressValue.classList.remove("nodisplay");
progress.style.width = ((this.loadingValue / this.loadingMax) * 100) + "%";
}
}
reset() {
this.loadingValue = 0;
const progress = this.elements.elements.div_progress;
const progressValue = this.elements.elements.div_progress_bar;
if (progress && progressValue) {
progressValue.classList.add("nodisplay");
progress.style.width = "0%";
}
}
}

36
src/classes/Tile.ts Normal file
View File

@@ -0,0 +1,36 @@
export class Tile {
x: number;
y: number;
tilesheet: HTMLImageElement;
tile: HTMLImageElement | null = null;
fullyTransparent: boolean = true;
constructor(x: number, y: number, tilesheet: HTMLImageElement) {
this.x = x;
this.y = y;
this.tilesheet = tilesheet;
}
async loadTile() {
const canvas = new OffscreenCanvas(16, 16);
const ctx = canvas.getContext("2d");
ctx?.drawImage(this.tilesheet, this.x, this.y, 16, 16, 0, 0, 16, 16);
const img = document.createElement("img");
const blob = await canvas.convertToBlob();
img.src = URL.createObjectURL(blob);
// img.loading = "eager";
this.tile = img;
if (ctx) {
const data = ctx.getImageData(0, 0, 16, 16).data;
for (let i = 3; i < data.length; i += 4) {
if (data[i] !== 0) {
this.fullyTransparent = false;
break;
}
}
}
}
}

287
src/index.css Normal file
View File

@@ -0,0 +1,287 @@
* {
margin: 0;
padding: 0;
text-decoration: none;
}
body {
background: black;
font-family: Arial, Helvetica, sans-serif;
}
.div-hammer-container {
display: flex;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
flex-direction: column;
gap: 0;
}
.tools {
position: relative;
background: #2e2e2e;
padding: 8px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
gap: 8px;
z-index: 2;
}
.tools button {
height: 100%;
border: none;
outline: none;
padding: 4px;
z-index: 2;
cursor: pointer;
width: 42px;
height: 42px;
position: relative;
background: #575757;
}
.tools button:hover {
background: #555555;
box-shadow: inset 0px 0px 0px 2.5px #6b6b6b;
}
.tools button.select {
background: #868686;
box-shadow: inset 0px 0px 0px 2.5px #353535;
}
.tools button img {
width: 32px;
height: 32px;
image-rendering: pixelated;
}
.tools button span {
display: none;
position: absolute;
top: 50px;
left: 0;
white-space: nowrap;
background: #2b2b2b;
padding: 4px;
color: #e4e4e4;
font-size: 12px;
}
.tools button:hover span {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
flex-direction: row;
}
.tools hr {
height: 100%;
width: 1px;
border: none;
border-radius: 0;
background-color: white;
}
.div-container-map {
position: relative;
flex-direction: row;
display: flex;
flex: 1 0 0;
gap: 0;
}
.div-container-map .container-tiles {
position: relative;
padding: 16px;
width: calc(350px - 16px * 2);
min-width: 350px;
background: #222222;
}
.div-container-map .container-tiles .div-scroll-tiles {
width: 100%;
height: 500px;
position: relative;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
justify-items: flex-start;
justify-content: flex-start;
align-content: flex-start;
overflow: hidden;
overflow-y: auto;
}
.div-container-map .container-tiles .div-scroll-tiles:empty::after {
content: "Add a tileSheet to your scene";
position: absolute;
color: #777;
font-style: italic;
padding: 1rem;
text-align: center;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
body {
--sb-track-color: #222222;
--sb-thumb-color: #adadad;
--sb-size: 14px;
}
.div-container-map .container-tiles .div-scroll-tiles::-webkit-scrollbar {
width: var(--sb-size)
}
.div-container-map .container-tiles .div-scroll-tiles::-webkit-scrollbar-track {
background: var(--sb-track-color);
border-radius: 1px;
}
.div-container-map .container-tiles .div-scroll-tiles::-webkit-scrollbar-thumb {
background: var(--sb-thumb-color);
border-radius: 1px;
}
@supports not selector(::-webkit-scrollbar) {
.div-container-map .container-tiles .div-scroll-tiles {
scrollbar-color: var(--sb-thumb-color) var(--sb-track-color);
}
}
.div-container-map .container-tiles .div-scroll-tiles img {
width: calc(100% / 5);
aspect-ratio: 1 / 1;
image-rendering: pixelated;
}
.div-container-map .container-tiles .div-scroll-tiles img:hover {
box-shadow: inset 0px 0px 0px 2.5px #6b6b6b;
opacity: .8;
background: #424242;
}
.div-container-map .container-tiles .div-scroll-tiles img:active {
box-shadow: inset 0px 0px 0px 2.5px #888888;
background: #5a5a5a;
}
.div-container-map .div-container-view {
flex: 1 0 0;
display: flex;
position: relative;
flex-direction: column;
gap: 0;
}
canvas {
position: relative;
image-rendering: pixelated;
flex: 1 0 0;
background: url(/src/assets/images/bg.png);
background-size: 16px;
background-repeat: repeat;
box-sizing: border-box;
}
.div-canvas-container {
flex: 1 0 0;
display: flex;
}
.div-container-map .div-container-view .div-console {
background-color: black;
flex: 1 0 0;
display: flex;
position: relative;
flex-direction: column;
outline: none;
max-height: 350px;
overflow: hidden;
overflow-y: auto;
padding: 8px;
color: white;
}
.div-container-map .div-container-view .div-console img {
width: 50px;
image-rendering: pixelated;
}
.div-container-map .div-container-view .div-console:empty::after {
content: "Oh no, meow… the catsole is empti~ :3";
position: absolute;
color: #777;
font-style: italic;
padding: 1rem;
text-align: center;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
body {
--sb-track-console-color: #000000;
--sb-thumb-console-color: rgb(255, 255, 255);
--sb-size-console: 14px;
}
.div-container-map .div-container-view .div-console::-webkit-scrollbar {
width: var(--sb-size-console)
}
.div-container-map .div-container-view .div-console::-webkit-scrollbar-track {
background: var(--sb-track-console-color);
border-radius: 1px;
}
.div-container-map .div-container-view .div-console::-webkit-scrollbar-thumb {
background: var(--sb-thumb-console-color);
border-radius: 1px;
}
.nodisplay {
display: none !important;
}
.progress-bar {
position: fixed;
pointer-events: none;
user-select: none;
background-color: rgb(19, 19, 19);
width: 100%;
height: 25px;
left: 0;
z-index: 2;
bottom: 0;
}
.progress-bar .progress {
width: 0%;
height: 100%;
position: absolute;
left: 0;
transition: width 300ms linear;
top: 0;
background: rgb(114, 114, 255);
}
button:disabled {
cursor: not-allowed;
opacity: .5;
}

10
src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

16
src/utils/file.ts Normal file
View File

@@ -0,0 +1,16 @@
export function DownloadTextFile(content : string, name : string) {
const blob = new Blob([content], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
export function IsFilenameFormat(format : string[], filename : string) {
const filenameSplit = filename.split(".");
return format.includes(filenameSplit[filenameSplit.length - 1]);
}

21
src/utils/image.ts Normal file
View File

@@ -0,0 +1,21 @@
export function WaitImgByFile(file : File) : Promise < HTMLImageElement > {
return new Promise((resolv, reject) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = () => resolv(img);
img.onerror = reject;
});
}
export function ImageToString(img : HTMLImageElement) {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
if(!ctx)
return null;
ctx.drawImage(img, 0, 0);
return canvas.toDataURL();
}

6
src/utils/math.ts Normal file
View File

@@ -0,0 +1,6 @@
export function FloorToMultiple(vec2: { x: number, y: number }, multipleX = 16, multipleY = 16) {
return {
x: Math.floor(vec2.x / multipleX) * multipleX,
y: Math.floor(vec2.y / multipleY) * multipleY
};
}

1
src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

27
tsconfig.app.json Normal file
View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

25
tsconfig.node.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

7
vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})