introduce prettierrc formatting

This commit is contained in:
John Gatward
2026-03-31 22:19:53 +01:00
parent 415b76532a
commit 7c58ce135c
100 changed files with 85618 additions and 11596 deletions
+16
View File
@@ -0,0 +1,16 @@
*.ice
node_modules
dist
*.min.js
*.wasm
*.data
archive/
tutorials/
projects/game_of_life.html
projects/oscillations_in_3d.html
thin_ice/fs
thin_ice/obj
flocking/pkg
cellular_automata/static
+6
View File
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"tabWidth": 2,
"semi": true,
"trailingComma": "es5"
}
+3 -3
View File
@@ -17,7 +17,7 @@ body {
} }
.nf-code { .nf-code {
font-family: "Fraunces", serif; font-family: 'Fraunces', serif;
font-size: clamp(7rem, 22vw, 16rem); font-size: clamp(7rem, 22vw, 16rem);
font-weight: 600; font-weight: 600;
line-height: 1; line-height: 1;
@@ -44,7 +44,7 @@ body {
.nf-eyebrow::before, .nf-eyebrow::before,
.nf-eyebrow::after { .nf-eyebrow::after {
content: ""; content: '';
display: block; display: block;
height: 1px; height: 1px;
width: 3rem; width: 3rem;
@@ -53,7 +53,7 @@ body {
} }
.nf-heading { .nf-heading {
font-family: "Fraunces", serif; font-family: 'Fraunces', serif;
font-size: clamp(1.6rem, 4vw, 2.8rem); font-size: clamp(1.6rem, 4vw, 2.8rem);
font-weight: 600; font-weight: 600;
color: var(--text); color: var(--text);
+19 -19
View File
@@ -1,22 +1,22 @@
(function () { (function () {
const pathEl = document.getElementById('typed-path'); const pathEl = document.getElementById('typed-path');
const responseEl = document.getElementById('nf-response'); const responseEl = document.getElementById('nf-response');
const hintEl = document.getElementById('nf-hint'); const hintEl = document.getElementById('nf-hint');
const href = globalThis.location.href; const href = globalThis.location.href;
const path = (href.length >= 45) ? href.substring(0, 45) : href; const path = href.length >= 45 ? href.substring(0, 45) : href;
let i = 0; let i = 0;
const interval = setInterval(() => { const interval = setInterval(() => {
if (i < path.length) { if (i < path.length) {
pathEl.textContent += path[i++]; pathEl.textContent += path[i++];
} else { } else {
clearInterval(interval); clearInterval(interval);
setTimeout(() => { setTimeout(() => {
responseEl.style.opacity = '1'; responseEl.style.opacity = '1';
setTimeout(() => { setTimeout(() => {
hintEl.style.opacity = '1'; hintEl.style.opacity = '1';
}, 400); }, 400);
}, 300); }, 300);
} }
}, 45); }, 45);
})(); })();
+473 -444
View File
File diff suppressed because it is too large Load Diff
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../prettier/bin/prettier.cjs
+24
View File
@@ -0,0 +1,24 @@
{
"name": "havox",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/prettier": {
"version": "3.8.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz",
"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
Copyright © James Long and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+104
View File
@@ -0,0 +1,104 @@
[![Prettier Banner](https://unpkg.com/prettier-logo@1.0.3/images/prettier-banner-light.svg)](https://prettier.io)
<h2 align="center">Opinionated Code Formatter</h2>
<p align="center">
<em>
JavaScript
· TypeScript
· Flow
· JSX
· JSON
</em>
<br />
<em>
CSS
· SCSS
· Less
</em>
<br />
<em>
HTML
· Vue
· Angular
</em>
<br />
<em>
GraphQL
· Markdown
· YAML
</em>
<br />
<em>
<a href="https://prettier.io/docs/plugins">
Your favorite language?
</a>
</em>
</p>
<p align="center">
<a href="https://github.com/prettier/prettier/actions?query=branch%3Amain">
<img alt="CI Status" src="https://img.shields.io/github/check-runs/prettier/prettier/main?style=flat-square&label=CI"></a>
<a href="https://codecov.io/gh/prettier/prettier">
<img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/prettier/prettier.svg?style=flat-square"></a>
<a href="https://x.com/acdlite/status/974390255393505280">
<img alt="Blazing Fast" src="https://img.shields.io/badge/speed-blazing%20%F0%9F%94%A5-brightgreen.svg?style=flat-square"></a>
<br/>
<a href="https://www.npmjs.com/package/prettier">
<img alt="npm version" src="https://img.shields.io/npm/v/prettier.svg?style=flat-square"></a>
<a href="https://www.npmjs.com/package/prettier">
<img alt="weekly downloads from npm" src="https://img.shields.io/npm/dw/prettier.svg?style=flat-square"></a>
<a href="https://github.com/prettier/prettier#badge">
<img alt="code style: prettier" src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square"></a>
<a href="https://x.com/intent/follow?screen_name=PrettierCode">
<img alt="Follow Prettier on X" src="https://img.shields.io/badge/%40PrettierCode-9f9f9f?style=flat-square&logo=x&labelColor=555"></a>
</p>
## Intro
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
### Input
<!-- prettier-ignore -->
```js
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
### Output
```js
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne(),
);
```
Prettier can be run [in your editor](https://prettier.io/docs/editors) on-save, in a [pre-commit hook](https://prettier.io/docs/precommit), or in [CI environments](https://prettier.io/docs/cli#list-different) to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!
---
**[Documentation](https://prettier.io/docs/)**
[Install](https://prettier.io/docs/install) ·
[Options](https://prettier.io/docs/options) ·
[CLI](https://prettier.io/docs/cli) ·
[API](https://prettier.io/docs/api)
**[Playground](https://prettier.io/playground/)**
---
## Badge
Show the world you're using _Prettier_ → [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
```md
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
```
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md).
+6059
View File
File diff suppressed because it is too large Load Diff
Generated Vendored Executable
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env node
"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = function(cb, mod) {
return function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
};
// node_modules/semver-compare/index.js
var require_semver_compare = __commonJS({
"node_modules/semver-compare/index.js": function(exports2, module2) {
module2.exports = function cmp(a, b) {
var pa = a.split(".");
var pb = b.split(".");
for (var i = 0; i < 3; i++) {
var na = Number(pa[i]);
var nb = Number(pb[i]);
if (na > nb) return 1;
if (nb > na) return -1;
if (!isNaN(na) && isNaN(nb)) return 1;
if (isNaN(na) && !isNaN(nb)) return -1;
}
return 0;
};
}
});
// node_modules/please-upgrade-node/index.js
var require_please_upgrade_node = __commonJS({
"node_modules/please-upgrade-node/index.js": function(exports2, module2) {
var semverCompare = require_semver_compare();
module2.exports = function pleaseUpgradeNode2(pkg, opts) {
var opts = opts || {};
var requiredVersion = pkg.engines.node.replace(">=", "");
var currentVersion = process.version.replace("v", "");
if (semverCompare(currentVersion, requiredVersion) === -1) {
if (opts.message) {
console.error(opts.message(requiredVersion));
} else {
console.error(
pkg.name + " requires at least version " + requiredVersion + " of Node, please upgrade"
);
}
if (opts.hasOwnProperty("exitCode")) {
process.exit(opts.exitCode);
} else {
process.exit(1);
}
}
};
}
});
// bin/prettier.cjs
var nodeModule = require("module");
if (typeof nodeModule.enableCompileCache === "function") {
nodeModule.enableCompileCache();
}
var pleaseUpgradeNode = require_please_upgrade_node();
var packageJson = require("../package.json");
pleaseUpgradeNode(packageJson);
var dynamicImport = new Function("module", "return import(module)");
var promise;
var index = process.argv.indexOf("--experimental-cli");
if (process.env.PRETTIER_EXPERIMENTAL_CLI || index !== -1) {
if (index !== -1) {
process.argv.splice(index, 1);
}
promise = dynamicImport("../internal/experimental-cli.mjs").then(
function(cli) {
return cli.__promise;
}
);
} else {
promise = dynamicImport("../internal/legacy-cli.mjs").then(function runCli(cli) {
return cli.run();
});
}
module.exports.__promise = promise;
+254
View File
@@ -0,0 +1,254 @@
// https://github.com/prettier/prettier/blob/next/src/document/public.js
export namespace builders {
type DocCommand =
| Align
| BreakParent
| Cursor
| Fill
| Group
| IfBreak
| Indent
| IndentIfBreak
| Label
| Line
| LineSuffix
| LineSuffixBoundary
| Trim;
type Doc = string | Doc[] | DocCommand;
interface Align {
type: "align";
contents: Doc;
n: number | string | { type: "root" };
}
interface BreakParent {
type: "break-parent";
}
interface Cursor {
type: "cursor";
placeholder: symbol;
}
interface Fill {
type: "fill";
parts: Doc[];
}
interface Group {
type: "group";
id?: symbol;
contents: Doc;
break: boolean;
expandedStates: Doc[];
}
interface HardlineWithoutBreakParent extends Line {
hard: true;
}
interface IfBreak {
type: "if-break";
breakContents: Doc;
flatContents: Doc;
}
interface Indent {
type: "indent";
contents: Doc;
}
interface IndentIfBreak {
type: "indent-if-break";
}
interface Label {
type: "label";
label: any;
contents: Doc;
}
interface Line {
type: "line";
soft?: boolean | undefined;
hard?: boolean | undefined;
literal?: boolean | undefined;
}
interface LineSuffix {
type: "line-suffix";
contents: Doc;
}
interface LineSuffixBoundary {
type: "line-suffix-boundary";
}
interface LiterallineWithoutBreakParent extends Line {
hard: true;
literal: true;
}
type LiteralLine = [LiterallineWithoutBreakParent, BreakParent];
interface Softline extends Line {
soft: true;
}
type Hardline = [HardlineWithoutBreakParent, BreakParent];
interface Trim {
type: "trim";
}
interface GroupOptions {
shouldBreak?: boolean | undefined;
id?: symbol | undefined;
}
function addAlignmentToDoc(doc: Doc, size: number, tabWidth: number): Doc;
/** @see [align](https://github.com/prettier/prettier/blob/main/commands.md#align) */
function align(widthOrString: Align["n"], doc: Doc): Align;
/** @see [breakParent](https://github.com/prettier/prettier/blob/main/commands.md#breakparent) */
const breakParent: BreakParent;
/** @see [conditionalGroup](https://github.com/prettier/prettier/blob/main/commands.md#conditionalgroup) */
function conditionalGroup(alternatives: Doc[], options?: GroupOptions): Group;
/** @see [dedent](https://github.com/prettier/prettier/blob/main/commands.md#dedent) */
function dedent(doc: Doc): Align;
/** @see [dedentToRoot](https://github.com/prettier/prettier/blob/main/commands.md#dedenttoroot) */
function dedentToRoot(doc: Doc): Align;
/** @see [fill](https://github.com/prettier/prettier/blob/main/commands.md#fill) */
function fill(docs: Doc[]): Fill;
/** @see [group](https://github.com/prettier/prettier/blob/main/commands.md#group) */
function group(doc: Doc, opts?: GroupOptions): Group;
/** @see [hardline](https://github.com/prettier/prettier/blob/main/commands.md#hardline) */
const hardline: Hardline;
/** @see [hardlineWithoutBreakParent](https://github.com/prettier/prettier/blob/main/commands.md#hardlinewithoutbreakparent-and-literallinewithoutbreakparent) */
const hardlineWithoutBreakParent: HardlineWithoutBreakParent;
/** @see [ifBreak](https://github.com/prettier/prettier/blob/main/commands.md#ifbreak) */
function ifBreak(
ifBreak: Doc,
noBreak?: Doc,
options?: { groupId?: symbol | undefined },
): IfBreak;
/** @see [indent](https://github.com/prettier/prettier/blob/main/commands.md#indent) */
function indent(doc: Doc): Indent;
/** @see [indentIfBreak](https://github.com/prettier/prettier/blob/main/commands.md#indentifbreak) */
function indentIfBreak(
doc: Doc,
opts: { groupId: symbol; negate?: boolean | undefined },
): IndentIfBreak;
/** @see [join](https://github.com/prettier/prettier/blob/main/commands.md#join) */
function join(sep: Doc, docs: Doc[]): Doc[];
/** @see [label](https://github.com/prettier/prettier/blob/main/commands.md#label) */
function label(label: any | undefined, contents: Doc): Doc;
/** @see [line](https://github.com/prettier/prettier/blob/main/commands.md#line) */
const line: Line;
/** @see [lineSuffix](https://github.com/prettier/prettier/blob/main/commands.md#linesuffix) */
function lineSuffix(suffix: Doc): LineSuffix;
/** @see [lineSuffixBoundary](https://github.com/prettier/prettier/blob/main/commands.md#linesuffixboundary) */
const lineSuffixBoundary: LineSuffixBoundary;
/** @see [literalline](https://github.com/prettier/prettier/blob/main/commands.md#literalline) */
const literalline: LiteralLine;
/** @see [literallineWithoutBreakParent](https://github.com/prettier/prettier/blob/main/commands.md#hardlinewithoutbreakparent-and-literallinewithoutbreakparent) */
const literallineWithoutBreakParent: LiterallineWithoutBreakParent;
/** @see [markAsRoot](https://github.com/prettier/prettier/blob/main/commands.md#markasroot) */
function markAsRoot(doc: Doc): Align;
/** @see [softline](https://github.com/prettier/prettier/blob/main/commands.md#softline) */
const softline: Softline;
/** @see [trim](https://github.com/prettier/prettier/blob/main/commands.md#trim) */
const trim: Trim;
/** @see [cursor](https://github.com/prettier/prettier/blob/main/commands.md#cursor) */
const cursor: Cursor;
}
export namespace printer {
function printDocToString(
doc: builders.Doc,
options: Options,
): {
formatted: string;
/**
* This property is a misnomer, and has been since the changes in
* https://github.com/prettier/prettier/pull/15709.
* The region of the document indicated by `cursorNodeStart` and `cursorNodeText` will
* sometimes actually be what lies BETWEEN a pair of leaf nodes in the AST, rather than a node.
*/
cursorNodeStart?: number | undefined;
/**
* Note that, like cursorNodeStart, this is a misnomer and may actually be the text between two
* leaf nodes in the AST instead of the text of a node.
*/
cursorNodeText?: string | undefined;
};
interface Options {
/**
* Specify the line length that the printer will wrap on.
* @default 80
*/
printWidth: number;
/**
* Specify the number of spaces per indentation-level.
* @default 2
*/
tabWidth: number;
/**
* Indent lines with tabs instead of spaces
* @default false
*/
useTabs?: boolean;
parentParser?: string | undefined;
__embeddedInHtml?: boolean | undefined;
}
}
export namespace utils {
function willBreak(doc: builders.Doc): boolean;
function traverseDoc(
doc: builders.Doc,
onEnter?: (doc: builders.Doc) => void | boolean,
onExit?: (doc: builders.Doc) => void,
shouldTraverseConditionalGroups?: boolean,
): void;
function findInDoc<T = builders.Doc>(
doc: builders.Doc,
callback: (doc: builders.Doc) => T,
defaultValue: T,
): T;
function mapDoc<T = builders.Doc>(
doc: builders.Doc,
callback: (doc: builders.Doc) => T,
): T;
function removeLines(doc: builders.Doc): builders.Doc;
function stripTrailingHardline(doc: builders.Doc): builders.Doc;
function replaceEndOfLine(
doc: builders.Doc,
replacement?: builders.Doc,
): builders.Doc;
function canBreak(doc: builders.Doc): boolean;
}
+1511
View File
File diff suppressed because one or more lines are too long
+1480
View File
File diff suppressed because one or more lines are too long
+720
View File
File diff suppressed because one or more lines are too long
+968
View File
@@ -0,0 +1,968 @@
// Copied from `@types/prettier`
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/5bb07fc4b087cb7ee91084afa6fe750551a7bbb1/types/prettier/index.d.ts
// Minimum TypeScript Version: 4.2
// Add `export {}` here to shut off automatic exporting from index.d.ts. There
// are quite a few utility types here that don't need to be shipped with the
// exported module.
export {};
import { builders, printer, utils } from "./doc.js";
export namespace doc {
export { builders, printer, utils };
}
// This utility is here to handle the case where you have an explicit union
// between string literals and the generic string type. It would normally
// resolve out to just the string type, but this generic LiteralUnion maintains
// the intellisense of the original union.
//
// It comes from this issue: microsoft/TypeScript#29729:
// https://github.com/microsoft/TypeScript/issues/29729#issuecomment-700527227
export type LiteralUnion<T extends U, U = string> =
| T
| (Pick<U, never> & { _?: never | undefined });
export type AST = any;
export type Doc = doc.builders.Doc;
// The type of elements that make up the given array T.
type ArrayElement<T> = T extends Array<infer E> ? E : never;
// A union of the properties of the given object that are arrays.
type ArrayProperties<T> = {
[K in keyof T]: NonNullable<T[K]> extends readonly any[] ? K : never;
}[keyof T];
// A union of the properties of the given array T that can be used to index it.
// If the array is a tuple, then that's going to be the explicit indices of the
// array, otherwise it's going to just be number.
type IndexProperties<T extends { length: number }> =
IsTuple<T> extends true ? Exclude<Partial<T>["length"], T["length"]> : number;
// Effectively performing T[P], except that it's telling TypeScript that it's
// safe to do this for tuples, arrays, or objects.
type IndexValue<T, P> = T extends any[]
? P extends number
? T[P]
: never
: P extends keyof T
? T[P]
: never;
// Determines if an object T is an array like string[] (in which case this
// evaluates to false) or a tuple like [string] (in which case this evaluates to
// true).
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type IsTuple<T> = T extends []
? true
: T extends [infer First, ...infer Remain]
? IsTuple<Remain>
: false;
type CallProperties<T> = T extends any[] ? IndexProperties<T> : keyof T;
type IterProperties<T> = T extends any[]
? IndexProperties<T>
: ArrayProperties<T>;
type CallCallback<T, U> = (path: AstPath<T>, index: number, value: any) => U;
type EachCallback<T> = (
path: AstPath<ArrayElement<T>>,
index: number,
value: any,
) => void;
type MapCallback<T, U> = (
path: AstPath<ArrayElement<T>>,
index: number,
value: any,
) => U;
// https://github.com/prettier/prettier/blob/next/src/common/ast-path.js
export class AstPath<T = any> {
constructor(value: T);
get key(): string | null;
get index(): number | null;
get node(): T;
get parent(): T | null;
get grandparent(): T | null;
get isInArray(): boolean;
get siblings(): T[] | null;
get next(): T | null;
get previous(): T | null;
get isFirst(): boolean;
get isLast(): boolean;
get isRoot(): boolean;
get root(): T;
get ancestors(): T[];
stack: T[];
callParent<U>(callback: (path: this) => U, count?: number): U;
/**
* @deprecated Please use `AstPath#key` or `AstPath#index`
*/
getName(): PropertyKey | null;
/**
* @deprecated Please use `AstPath#node` or `AstPath#siblings`
*/
getValue(): T;
getNode(count?: number): T | null;
getParentNode(count?: number): T | null;
match(
...predicates: Array<
(node: any, name: string | null, number: number | null) => boolean
>
): boolean;
// For each of the tree walk functions (call, each, and map) this provides 5
// strict type signatures, along with a fallback at the end if you end up
// calling more than 5 properties deep. This helps a lot with typing because
// for the majority of cases you're calling fewer than 5 properties, so the
// tree walk functions have a clearer understanding of what you're doing.
//
// Note that resolving these types is somewhat complicated, and it wasn't
// even supported until TypeScript 4.2 (before it would just say that the
// type instantiation was excessively deep and possibly infinite).
call<U>(callback: CallCallback<T, U>): U;
call<U, P1 extends CallProperties<T>>(
callback: CallCallback<IndexValue<T, P1>, U>,
prop1: P1,
): U;
call<U, P1 extends keyof T, P2 extends CallProperties<T[P1]>>(
callback: CallCallback<IndexValue<IndexValue<T, P1>, P2>, U>,
prop1: P1,
prop2: P2,
): U;
call<
U,
P1 extends keyof T,
P2 extends CallProperties<T[P1]>,
P3 extends CallProperties<IndexValue<T[P1], P2>>,
>(
callback: CallCallback<
IndexValue<IndexValue<IndexValue<T, P1>, P2>, P3>,
U
>,
prop1: P1,
prop2: P2,
prop3: P3,
): U;
call<
U,
P1 extends keyof T,
P2 extends CallProperties<T[P1]>,
P3 extends CallProperties<IndexValue<T[P1], P2>>,
P4 extends CallProperties<IndexValue<IndexValue<T[P1], P2>, P3>>,
>(
callback: CallCallback<
IndexValue<IndexValue<IndexValue<IndexValue<T, P1>, P2>, P3>, P4>,
U
>,
prop1: P1,
prop2: P2,
prop3: P3,
prop4: P4,
): U;
call<U, P extends PropertyKey>(
callback: CallCallback<any, U>,
prop1: P,
prop2: P,
prop3: P,
prop4: P,
...props: P[]
): U;
each(callback: EachCallback<T>): void;
each<P1 extends IterProperties<T>>(
callback: EachCallback<IndexValue<T, P1>>,
prop1: P1,
): void;
each<P1 extends keyof T, P2 extends IterProperties<T[P1]>>(
callback: EachCallback<IndexValue<IndexValue<T, P1>, P2>>,
prop1: P1,
prop2: P2,
): void;
each<
P1 extends keyof T,
P2 extends IterProperties<T[P1]>,
P3 extends IterProperties<IndexValue<T[P1], P2>>,
>(
callback: EachCallback<IndexValue<IndexValue<IndexValue<T, P1>, P2>, P3>>,
prop1: P1,
prop2: P2,
prop3: P3,
): void;
each<
P1 extends keyof T,
P2 extends IterProperties<T[P1]>,
P3 extends IterProperties<IndexValue<T[P1], P2>>,
P4 extends IterProperties<IndexValue<IndexValue<T[P1], P2>, P3>>,
>(
callback: EachCallback<
IndexValue<IndexValue<IndexValue<IndexValue<T, P1>, P2>, P3>, P4>
>,
prop1: P1,
prop2: P2,
prop3: P3,
prop4: P4,
): void;
each(
callback: EachCallback<any[]>,
prop1: PropertyKey,
prop2: PropertyKey,
prop3: PropertyKey,
prop4: PropertyKey,
...props: PropertyKey[]
): void;
map<U>(callback: MapCallback<T, U>): U[];
map<U, P1 extends IterProperties<T>>(
callback: MapCallback<IndexValue<T, P1>, U>,
prop1: P1,
): U[];
map<U, P1 extends keyof T, P2 extends IterProperties<T[P1]>>(
callback: MapCallback<IndexValue<IndexValue<T, P1>, P2>, U>,
prop1: P1,
prop2: P2,
): U[];
map<
U,
P1 extends keyof T,
P2 extends IterProperties<T[P1]>,
P3 extends IterProperties<IndexValue<T[P1], P2>>,
>(
callback: MapCallback<IndexValue<IndexValue<IndexValue<T, P1>, P2>, P3>, U>,
prop1: P1,
prop2: P2,
prop3: P3,
): U[];
map<
U,
P1 extends keyof T,
P2 extends IterProperties<T[P1]>,
P3 extends IterProperties<IndexValue<T[P1], P2>>,
P4 extends IterProperties<IndexValue<IndexValue<T[P1], P2>, P3>>,
>(
callback: MapCallback<
IndexValue<IndexValue<IndexValue<IndexValue<T, P1>, P2>, P3>, P4>,
U
>,
prop1: P1,
prop2: P2,
prop3: P3,
prop4: P4,
): U[];
map<U>(
callback: MapCallback<any[], U>,
prop1: PropertyKey,
prop2: PropertyKey,
prop3: PropertyKey,
prop4: PropertyKey,
...props: PropertyKey[]
): U[];
}
/** @deprecated `FastPath` was renamed to `AstPath` */
export type FastPath<T = any> = AstPath<T>;
export type BuiltInParser = (text: string, options?: any) => AST;
export type BuiltInParserName =
| "acorn"
| "angular"
| "babel-flow"
| "babel-ts"
| "babel"
| "css"
| "espree"
| "flow"
| "glimmer"
| "graphql"
| "html"
| "json-stringify"
| "json"
| "json5"
| "jsonc"
| "less"
| "lwc"
| "markdown"
| "mdx"
| "meriyah"
| "mjml"
| "scss"
| "typescript"
| "vue"
| "yaml";
export type BuiltInParsers = Record<BuiltInParserName, BuiltInParser>;
/**
* For use in `.prettierrc.js`, `.prettierrc.ts`, `.prettierrc.cjs`, `.prettierrc.cts`, `prettierrc.mjs`, `prettierrc.mts`, `prettier.config.js`, `prettier.config.ts`, `prettier.config.cjs`, `prettier.config.cts`, `prettier.config.mjs`, `prettier.config.mts`
*/
export interface Config extends Options {
overrides?: Array<{
files: string | string[];
excludeFiles?: string | string[];
options?: Options;
}>;
}
export interface Options extends Partial<RequiredOptions> {}
export interface RequiredOptions extends doc.printer.Options {
/**
* Print semicolons at the ends of statements.
* @default true
*/
semi: boolean;
/**
* Use single quotes instead of double quotes.
* @default false
*/
singleQuote: boolean;
/**
* Use single quotes in JSX.
* @default false
*/
jsxSingleQuote: boolean;
/**
* Print trailing commas wherever possible.
* @default "all"
*/
trailingComma: "none" | "es5" | "all";
/**
* Print spaces between brackets in object literals.
* @default true
*/
bracketSpacing: boolean;
/**
* How to wrap object literals.
* @default "preserve"
*/
objectWrap: "preserve" | "collapse";
/**
* Put the `>` of a multi-line HTML (HTML, JSX, Vue, Angular) element at the end of the last line instead of being
* alone on the next line (does not apply to self closing elements).
* @default false
*/
bracketSameLine: boolean;
/**
* Format only a segment of a file.
* @default 0
*/
rangeStart: number;
/**
* Format only a segment of a file.
* @default Number.POSITIVE_INFINITY
*/
rangeEnd: number;
/**
* Specify which parser to use.
*/
parser: LiteralUnion<BuiltInParserName>;
/**
* Specify the input filepath. This will be used to do parser inference.
*/
filepath: string;
/**
* Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file.
* This is very useful when gradually transitioning large, unformatted codebases to prettier.
* @default false
*/
requirePragma: boolean;
/**
* Prettier can insert a special @format marker at the top of files specifying that
* the file has been formatted with prettier. This works well when used in tandem with
* the --require-pragma option. If there is already a docblock at the top of
* the file then this option will add a newline to it with the @format marker.
* @default false
*/
insertPragma: boolean;
/**
* Prettier can allow individual files to opt out of formatting if they contain a special comment, called a pragma, at the top of the file.
* @default false
*/
checkIgnorePragma: boolean;
/**
* By default, Prettier will wrap markdown text as-is since some services use a linebreak-sensitive renderer.
* In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out.
* @default "preserve"
*/
proseWrap: "always" | "never" | "preserve";
/**
* Include parentheses around a sole arrow function parameter.
* @default "always"
*/
arrowParens: "avoid" | "always";
/**
* Provide ability to support new languages to prettier.
*/
plugins: Array<string | URL | Plugin>;
/**
* How to handle whitespaces in HTML.
* @default "css"
*/
htmlWhitespaceSensitivity: "css" | "strict" | "ignore";
/**
* Which end of line characters to apply.
* @default "lf"
*/
endOfLine: "auto" | "lf" | "crlf" | "cr";
/**
* Change when properties in objects are quoted.
* @default "as-needed"
*/
quoteProps: "as-needed" | "consistent" | "preserve";
/**
* Whether or not to indent the code inside <script> and <style> tags in Vue files.
* @default false
*/
vueIndentScriptAndStyle: boolean;
/**
* Control whether Prettier formats quoted code embedded in the file.
* @default "auto"
*/
embeddedLanguageFormatting: "auto" | "off";
/**
* Enforce single attribute per line in HTML, Vue and JSX.
* @default false
*/
singleAttributePerLine: boolean;
/**
* Where to print operators when binary expressions wrap lines.
* @default "end"
*/
experimentalOperatorPosition: "start" | "end";
/**
* Use curious ternaries, with the question mark after the condition, instead
* of on the same line as the consequent.
* @default false
*/
experimentalTernaries: boolean;
/**
* Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line.
* @default false
* @deprecated use bracketSameLine instead
*/
jsxBracketSameLine?: boolean;
/**
* Arbitrary additional values on an options object are always allowed.
*/
[_: string]: unknown;
}
export interface ParserOptions<T = any> extends RequiredOptions {
locStart: (node: T) => number;
locEnd: (node: T) => number;
originalText: string;
}
export interface Plugin<T = any> {
languages?: SupportLanguage[] | undefined;
parsers?: { [parserName: string]: Parser<T> } | undefined;
printers?: { [astFormat: string]: Printer<T> } | undefined;
options?: SupportOptions | undefined;
defaultOptions?: Partial<RequiredOptions> | undefined;
}
export interface Parser<T = any> {
parse: (text: string, options: ParserOptions<T>) => T | Promise<T>;
astFormat: string;
hasPragma?: ((text: string) => boolean) | undefined;
hasIgnorePragma?: ((text: string) => boolean) | undefined;
locStart: (node: T) => number;
locEnd: (node: T) => number;
preprocess?:
| ((text: string, options: ParserOptions<T>) => string | Promise<string>)
| undefined;
}
export interface Printer<T = any> {
print(
path: AstPath<T>,
options: ParserOptions<T>,
print: (path: AstPath<T>) => Doc,
args?: unknown,
): Doc;
printPrettierIgnored?(
path: AstPath<T>,
options: ParserOptions<T>,
print: (path: AstPath<T>) => Doc,
args?: unknown,
): Doc;
embed?:
| ((
path: AstPath,
options: Options,
) =>
| ((
textToDoc: (text: string, options: Options) => Promise<Doc>,
print: (
selector?: string | number | Array<string | number> | AstPath,
) => Doc,
path: AstPath,
options: Options,
) => Promise<Doc | undefined> | Doc | undefined)
| Doc
| null)
| undefined;
preprocess?:
| ((ast: T, options: ParserOptions<T>) => T | Promise<T>)
| undefined;
insertPragma?: (text: string) => string;
/**
* @returns `null` if you want to remove this node
* @returns `void` if you want to use modified `cloned`
* @returns anything if you want to replace the node with it
*/
massageAstNode?:
| ((original: any, cloned: any, parent: any) => any)
| undefined;
hasPrettierIgnore?: ((path: AstPath<T>) => boolean) | undefined;
canAttachComment?: ((node: T, ancestors: T[]) => boolean) | undefined;
isBlockComment?: ((node: T) => boolean) | undefined;
willPrintOwnComments?: ((path: AstPath<T>) => boolean) | undefined;
printComment?:
| ((commentPath: AstPath<T>, options: ParserOptions<T>) => Doc)
| undefined;
/**
* By default, Prettier searches all object properties (except for a few predefined ones) of each node recursively.
* This function can be provided to override that behavior.
* @param node The node whose children should be returned.
* @param options Current options.
* @returns `[]` if the node has no children or `undefined` to fall back on the default behavior.
*/
getCommentChildNodes?:
| ((node: T, options: ParserOptions<T>) => T[] | undefined)
| undefined;
handleComments?:
| {
ownLine?:
| ((
commentNode: any,
text: string,
options: ParserOptions<T>,
ast: T,
isLastComment: boolean,
) => boolean)
| undefined;
endOfLine?:
| ((
commentNode: any,
text: string,
options: ParserOptions<T>,
ast: T,
isLastComment: boolean,
) => boolean)
| undefined;
remaining?:
| ((
commentNode: any,
text: string,
options: ParserOptions<T>,
ast: T,
isLastComment: boolean,
) => boolean)
| undefined;
}
| undefined;
getVisitorKeys?:
| ((node: T, nonTraversableKeys: Set<string>) => string[])
| undefined;
}
export interface CursorOptions extends Options {
/**
* Specify where the cursor is.
*/
cursorOffset: number;
}
export interface CursorResult {
formatted: string;
cursorOffset: number;
}
/**
* `format` is used to format text using Prettier. [Options](https://prettier.io/docs/options) may be provided to override the defaults.
*/
export function format(source: string, options?: Options): Promise<string>;
/**
* `check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
* This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
*/
export function check(source: string, options?: Options): Promise<boolean>;
/**
* `formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code.
* This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
*
* The `cursorOffset` option should be provided, to specify where the cursor is.
*/
export function formatWithCursor(
source: string,
options: CursorOptions,
): Promise<CursorResult>;
export interface ResolveConfigOptions {
/**
* If set to `false`, all caching will be bypassed.
*/
useCache?: boolean | undefined;
/**
* Pass directly the path of the config file if you don't wish to search for it.
*/
config?: string | URL | undefined;
/**
* If set to `true` and an `.editorconfig` file is in your project,
* Prettier will parse it and convert its properties to the corresponding prettier configuration.
* This configuration will be overridden by `.prettierrc`, etc. Currently,
* the following EditorConfig properties are supported:
* - indent_style
* - indent_size/tab_width
* - max_line_length
*/
editorconfig?: boolean | undefined;
}
/**
* `resolveConfig` can be used to resolve configuration for a given source file,
* passing its path or url as the first argument. The config search will start at
* the directory of the file location and continue to search up the directory.
*
* A promise is returned which will resolve to:
*
* - An options object, providing a [config file](https://prettier.io/docs/configuration) was found.
* - `null`, if no file was found.
*
* The promise will be rejected if there was an error parsing the configuration file.
*/
export function resolveConfig(
fileUrlOrPath: string | URL,
options?: ResolveConfigOptions,
): Promise<Options | null>;
/**
* `resolveConfigFile` can be used to find the path of the Prettier configuration file,
* that will be used when resolving the config (i.e. when calling `resolveConfig`).
*
* A promise is returned which will resolve to:
*
* - The path of the configuration file.
* - `null`, if no file was found.
*
* The promise will be rejected if there was an error parsing the configuration file.
*/
export function resolveConfigFile(
fileUrlOrPath?: string | URL,
): Promise<string | null>;
/**
* As you repeatedly call `resolveConfig`, the file system structure will be cached for performance. This function will clear the cache.
* Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
*/
export function clearConfigCache(): Promise<void>;
export interface SupportLanguage {
name: string;
parsers: BuiltInParserName[] | string[];
group?: string | undefined;
tmScope?: string | undefined;
aceMode?: string | undefined;
codemirrorMode?: string | undefined;
codemirrorMimeType?: string | undefined;
aliases?: string[] | undefined;
extensions?: string[] | undefined;
filenames?: string[] | undefined;
linguistLanguageId?: number | undefined;
vscodeLanguageIds?: string[] | undefined;
interpreters?: string[] | undefined;
isSupported?: ((options: { filepath: string }) => boolean) | undefined;
}
export interface SupportOptionRange {
start: number;
end: number;
step: number;
}
export type SupportOptionType =
| "int"
| "string"
| "boolean"
| "choice"
| "path";
export type CoreCategoryType =
| "Config"
| "Editor"
| "Format"
| "Other"
| "Output"
| "Global"
| "Special";
export interface BaseSupportOption<Type extends SupportOptionType> {
readonly name?: string | undefined;
/**
* Usually you can use {@link CoreCategoryType}
*/
category: string;
/**
* The type of the option.
*
* When passing a type other than the ones listed below, the option is
* treated as taking any string as argument, and `--option <${type}>` will
* be displayed in --help.
*/
type: Type;
/**
* Indicate that the option is deprecated.
*
* Use a string to add an extra message to --help for the option,
* for example to suggest a replacement option.
*/
deprecated?: true | string | undefined;
/**
* Description to be displayed in --help. If omitted, the option won't be
* shown at all in --help.
*/
description?: string | undefined;
}
export interface IntSupportOption extends BaseSupportOption<"int"> {
default?: number | undefined;
array?: false | undefined;
range?: SupportOptionRange | undefined;
}
export interface IntArraySupportOption extends BaseSupportOption<"int"> {
default?: Array<{ value: number[] }> | undefined;
array: true;
}
export interface StringSupportOption extends BaseSupportOption<"string"> {
default?: string | undefined;
array?: false | undefined;
}
export interface StringArraySupportOption extends BaseSupportOption<"string"> {
default?: Array<{ value: string[] }> | undefined;
array: true;
}
export interface BooleanSupportOption extends BaseSupportOption<"boolean"> {
default?: boolean | undefined;
array?: false | undefined;
description: string;
oppositeDescription?: string | undefined;
}
export interface BooleanArraySupportOption extends BaseSupportOption<"boolean"> {
default?: Array<{ value: boolean[] }> | undefined;
array: true;
}
export interface ChoiceSupportOption<
Value = any,
> extends BaseSupportOption<"choice"> {
default?: Value | Array<{ value: Value }> | undefined;
description: string;
choices: Array<{
value: Value;
description: string;
}>;
}
export interface PathSupportOption extends BaseSupportOption<"path"> {
default?: string | undefined;
array?: false | undefined;
}
export interface PathArraySupportOption extends BaseSupportOption<"path"> {
default?: Array<{ value: string[] }> | undefined;
array: true;
}
export type SupportOption =
| IntSupportOption
| IntArraySupportOption
| StringSupportOption
| StringArraySupportOption
| BooleanSupportOption
| BooleanArraySupportOption
| ChoiceSupportOption
| PathSupportOption
| PathArraySupportOption;
export interface SupportOptions extends Record<string, SupportOption> {}
export interface SupportInfo {
languages: SupportLanguage[];
options: SupportOption[];
}
export interface FileInfoOptions {
ignorePath?: string | URL | (string | URL)[] | undefined;
withNodeModules?: boolean | undefined;
plugins?: Array<string | URL | Plugin> | undefined;
resolveConfig?: boolean | undefined;
}
export interface FileInfoResult {
ignored: boolean;
inferredParser: string | null;
}
export function getFileInfo(
file: string | URL,
options?: FileInfoOptions,
): Promise<FileInfoResult>;
export interface SupportInfoOptions {
plugins?: Array<string | URL | Plugin> | undefined;
showDeprecated?: boolean | undefined;
}
/**
* Returns an object representing the parsers, languages and file types Prettier supports for the current version.
*/
export function getSupportInfo(
options?: SupportInfoOptions,
): Promise<SupportInfo>;
/**
* `version` field in `package.json`
*/
export const version: string;
// https://github.com/prettier/prettier/blob/main/src/utilities/public.js
export namespace util {
interface SkipOptions {
backwards?: boolean | undefined;
}
type Quote = "'" | '"';
function getMaxContinuousCount(text: string, searchString: string): number;
function getStringWidth(text: string): number;
function getAlignmentSize(
text: string,
tabWidth: number,
startIndex?: number | undefined,
): number;
function getIndentSize(value: string, tabWidth: number): number;
function skipNewline(
text: string,
startIndex: number | false,
options?: SkipOptions | undefined,
): number | false;
function skipInlineComment(
text: string,
startIndex: number | false,
): number | false;
function skipTrailingComment(
text: string,
startIndex: number | false,
): number | false;
function skipTrailingComment(
text: string,
startIndex: number | false,
): number | false;
function hasNewline(
text: string,
startIndex: number,
options?: SkipOptions | undefined,
): boolean;
function hasNewlineInRange(
text: string,
startIndex: number,
endIndex: number,
): boolean;
function hasSpaces(
text: string,
startIndex: number,
options?: SkipOptions | undefined,
): boolean;
function getNextNonSpaceNonCommentCharacterIndex(
text: string,
startIndex: number,
): number | false;
function getNextNonSpaceNonCommentCharacter(
text: string,
startIndex: number,
): string;
function isNextLineEmpty(text: string, startIndex: number): boolean;
function isPreviousLineEmpty(text: string, startIndex: number): boolean;
function makeString(
rawText: string,
enclosingQuote: Quote,
unescapeUnnecessaryEscapes?: boolean | undefined,
): string;
function skip(
characters: string | RegExp,
): (
text: string,
startIndex: number | false,
options?: SkipOptions,
) => number | false;
const skipWhitespace: (
text: string,
startIndex: number | false,
options?: SkipOptions,
) => number | false;
const skipSpaces: (
text: string,
startIndex: number | false,
options?: SkipOptions,
) => number | false;
const skipToLineEnd: (
text: string,
startIndex: number | false,
options?: SkipOptions,
) => number | false;
const skipEverythingButNewLine: (
text: string,
startIndex: number | false,
options?: SkipOptions,
) => number | false;
function addLeadingComment(node: any, comment: any): void;
function addDanglingComment(node: any, comment: any, marker: any): void;
function addTrailingComment(node: any, comment: any): void;
function getPreferredQuote(
text: string,
preferredQuoteOrPreferSingleQuote: Quote | boolean,
): Quote;
}
+18793
View File
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+6229
View File
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
{
"name": "prettier",
"version": "3.8.1",
"description": "Prettier is an opinionated code formatter",
"bin": "./bin/prettier.cjs",
"repository": "prettier/prettier",
"funding": "https://github.com/prettier/prettier?sponsor=1",
"homepage": "https://prettier.io",
"author": "James Long",
"license": "MIT",
"main": "./index.cjs",
"browser": "./standalone.js",
"unpkg": "./standalone.js",
"exports": {
".": {
"types": "./index.d.ts",
"require": "./index.cjs",
"browser": {
"import": "./standalone.mjs",
"default": "./standalone.js"
},
"default": "./index.mjs"
},
"./*": "./*",
"./doc": {
"types": "./doc.d.ts",
"require": "./doc.js",
"default": "./doc.mjs"
},
"./standalone": {
"types": "./standalone.d.ts",
"require": "./standalone.js",
"default": "./standalone.mjs"
},
"./plugins/estree": {
"types": "./plugins/estree.d.ts",
"require": "./plugins/estree.js",
"default": "./plugins/estree.mjs"
},
"./plugins/babel": {
"types": "./plugins/babel.d.ts",
"require": "./plugins/babel.js",
"default": "./plugins/babel.mjs"
},
"./plugins/flow": {
"types": "./plugins/flow.d.ts",
"require": "./plugins/flow.js",
"default": "./plugins/flow.mjs"
},
"./plugins/typescript": {
"types": "./plugins/typescript.d.ts",
"require": "./plugins/typescript.js",
"default": "./plugins/typescript.mjs"
},
"./plugins/acorn": {
"types": "./plugins/acorn.d.ts",
"require": "./plugins/acorn.js",
"default": "./plugins/acorn.mjs"
},
"./plugins/meriyah": {
"types": "./plugins/meriyah.d.ts",
"require": "./plugins/meriyah.js",
"default": "./plugins/meriyah.mjs"
},
"./plugins/angular": {
"types": "./plugins/angular.d.ts",
"require": "./plugins/angular.js",
"default": "./plugins/angular.mjs"
},
"./plugins/postcss": {
"types": "./plugins/postcss.d.ts",
"require": "./plugins/postcss.js",
"default": "./plugins/postcss.mjs"
},
"./plugins/graphql": {
"types": "./plugins/graphql.d.ts",
"require": "./plugins/graphql.js",
"default": "./plugins/graphql.mjs"
},
"./plugins/markdown": {
"types": "./plugins/markdown.d.ts",
"require": "./plugins/markdown.js",
"default": "./plugins/markdown.mjs"
},
"./plugins/glimmer": {
"types": "./plugins/glimmer.d.ts",
"require": "./plugins/glimmer.js",
"default": "./plugins/glimmer.mjs"
},
"./plugins/html": {
"types": "./plugins/html.d.ts",
"require": "./plugins/html.js",
"default": "./plugins/html.mjs"
},
"./plugins/yaml": {
"types": "./plugins/yaml.d.ts",
"require": "./plugins/yaml.js",
"default": "./plugins/yaml.mjs"
},
"./esm/standalone.mjs": "./standalone.mjs",
"./parser-babel": "./plugins/babel.js",
"./parser-babel.js": "./plugins/babel.js",
"./esm/parser-babel.mjs": "./plugins/babel.mjs",
"./parser-flow": "./plugins/flow.js",
"./parser-flow.js": "./plugins/flow.js",
"./esm/parser-flow.mjs": "./plugins/flow.mjs",
"./parser-typescript": "./plugins/typescript.js",
"./parser-typescript.js": "./plugins/typescript.js",
"./esm/parser-typescript.mjs": "./plugins/typescript.mjs",
"./parser-espree": "./plugins/acorn.js",
"./parser-espree.js": "./plugins/acorn.js",
"./esm/parser-espree.mjs": "./plugins/acorn.mjs",
"./parser-meriyah": "./plugins/meriyah.js",
"./parser-meriyah.js": "./plugins/meriyah.js",
"./esm/parser-meriyah.mjs": "./plugins/meriyah.mjs",
"./parser-angular": "./plugins/angular.js",
"./parser-angular.js": "./plugins/angular.js",
"./esm/parser-angular.mjs": "./plugins/angular.mjs",
"./parser-postcss": "./plugins/postcss.js",
"./parser-postcss.js": "./plugins/postcss.js",
"./esm/parser-postcss.mjs": "./plugins/postcss.mjs",
"./parser-graphql": "./plugins/graphql.js",
"./parser-graphql.js": "./plugins/graphql.js",
"./esm/parser-graphql.mjs": "./plugins/graphql.mjs",
"./parser-markdown": "./plugins/markdown.js",
"./parser-markdown.js": "./plugins/markdown.js",
"./esm/parser-markdown.mjs": "./plugins/markdown.mjs",
"./parser-glimmer": "./plugins/glimmer.js",
"./parser-glimmer.js": "./plugins/glimmer.js",
"./esm/parser-glimmer.mjs": "./plugins/glimmer.mjs",
"./parser-html": "./plugins/html.js",
"./parser-html.js": "./plugins/html.js",
"./esm/parser-html.mjs": "./plugins/html.mjs",
"./parser-yaml": "./plugins/yaml.js",
"./parser-yaml.js": "./plugins/yaml.js",
"./esm/parser-yaml.mjs": "./plugins/yaml.mjs"
},
"engines": {
"node": ">=14"
},
"files": [
"LICENSE",
"README.md",
"THIRD-PARTY-NOTICES.md",
"bin/prettier.cjs",
"doc.d.ts",
"doc.js",
"doc.mjs",
"index.cjs",
"index.d.ts",
"index.d.ts",
"index.mjs",
"internal/experimental-cli-worker.mjs",
"internal/experimental-cli.mjs",
"internal/legacy-cli.mjs",
"package.json",
"plugins/acorn.d.ts",
"plugins/acorn.js",
"plugins/acorn.mjs",
"plugins/angular.d.ts",
"plugins/angular.js",
"plugins/angular.mjs",
"plugins/babel.d.ts",
"plugins/babel.js",
"plugins/babel.mjs",
"plugins/estree.d.ts",
"plugins/estree.js",
"plugins/estree.mjs",
"plugins/flow.d.ts",
"plugins/flow.js",
"plugins/flow.mjs",
"plugins/glimmer.d.ts",
"plugins/glimmer.js",
"plugins/glimmer.mjs",
"plugins/graphql.d.ts",
"plugins/graphql.js",
"plugins/graphql.mjs",
"plugins/html.d.ts",
"plugins/html.js",
"plugins/html.mjs",
"plugins/markdown.d.ts",
"plugins/markdown.js",
"plugins/markdown.mjs",
"plugins/meriyah.d.ts",
"plugins/meriyah.js",
"plugins/meriyah.mjs",
"plugins/postcss.d.ts",
"plugins/postcss.js",
"plugins/postcss.mjs",
"plugins/typescript.d.ts",
"plugins/typescript.js",
"plugins/typescript.mjs",
"plugins/yaml.d.ts",
"plugins/yaml.js",
"plugins/yaml.mjs",
"standalone.d.ts",
"standalone.js",
"standalone.mjs"
],
"preferUnplugged": true,
"sideEffects": false,
"type": "commonjs"
}
+6
View File
@@ -0,0 +1,6 @@
import { Parser } from "../index.js";
export declare const parsers: {
acorn: Parser;
espree: Parser;
};
+16
View File
File diff suppressed because one or more lines are too long
+16
View File
File diff suppressed because one or more lines are too long
+8
View File
@@ -0,0 +1,8 @@
import { Parser } from "../index.js";
export declare const parsers: {
__ng_action: Parser;
__ng_binding: Parser;
__ng_directive: Parser;
__ng_interpolation: Parser;
};
+4
View File
File diff suppressed because one or more lines are too long
+4
View File
File diff suppressed because one or more lines are too long
+18
View File
@@ -0,0 +1,18 @@
import { Parser } from "../index.js";
export declare const parsers: {
__babel_estree: Parser;
__js_expression: Parser;
__ts_expression: Parser;
__vue_event_binding: Parser;
__vue_expression: Parser;
__vue_ts_event_binding: Parser;
__vue_ts_expression: Parser;
babel: Parser;
"babel-flow": Parser;
"babel-ts": Parser;
json: Parser;
"json-stringify": Parser;
json5: Parser;
jsonc: Parser;
};
+15
View File
File diff suppressed because one or more lines are too long
+15
View File
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
import { Printer } from "../index.js";
export declare const printers: {
estree: Printer;
"estree-json": Printer;
};
+44
View File
File diff suppressed because one or more lines are too long
+44
View File
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
import { Parser } from "../index.js";
export declare const parsers: {
flow: Parser;
};
+20
View File
File diff suppressed because one or more lines are too long
+20
View File
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
import { Parser, Printer } from "../index.js";
export declare const parsers: {
glimmer: Parser;
};
export declare const printers: {
glimmer: Printer;
};
+37
View File
File diff suppressed because one or more lines are too long
+37
View File
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
import { Parser, Printer } from "../index.js";
export declare const parsers: {
graphql: Parser;
};
export declare const printers: {
graphql: Printer;
};
+28
View File
File diff suppressed because one or more lines are too long
+28
View File
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
import { Parser, Printer } from "../index.js";
export declare const parsers: {
angular: Parser;
html: Parser;
lwc: Parser;
mjml: Parser;
vue: Parser;
};
export declare const printers: {
html: Printer;
};
+24
View File
File diff suppressed because one or more lines are too long
+24
View File
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
import { Parser, Printer } from "../index.js";
export declare const parsers: {
markdown: Parser;
mdx: Parser;
remark: Parser;
};
export declare const printers: {
mdast: Printer;
};
+62
View File
File diff suppressed because one or more lines are too long
+62
View File
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
import { Parser } from "../index.js";
export declare const parsers: {
meriyah: Parser;
};
+5
View File
File diff suppressed because one or more lines are too long
+5
View File
File diff suppressed because one or more lines are too long
+11
View File
@@ -0,0 +1,11 @@
import { Parser, Printer } from "../index.js";
export declare const parsers: {
css: Parser;
less: Parser;
scss: Parser;
};
export declare const printers: {
postcss: Printer;
};
+61
View File
File diff suppressed because one or more lines are too long
+61
View File
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
import { Parser } from "../index.js";
export declare const parsers: {
typescript: Parser;
};
+21
View File
File diff suppressed because one or more lines are too long
+21
View File
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
import { Parser, Printer } from "../index.js";
export declare const parsers: {
yaml: Parser;
};
export declare const printers: {
yaml: Printer;
};
+159
View File
File diff suppressed because one or more lines are too long
+159
View File
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
import { CursorOptions, CursorResult, Options, SupportInfo } from "./index.js";
/**
* formatWithCursor both formats the code, and translates a cursor position from unformatted code to formatted code.
* This is useful for editor integrations, to prevent the cursor from moving when code is formatted
*
* The cursorOffset option should be provided, to specify where the cursor is.
*
* ```js
* await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
* ```
* `-> { formatted: "1;\n", cursorOffset: 1 }`
*/
export function formatWithCursor(
source: string,
options: CursorOptions,
): Promise<CursorResult>;
/**
* `format` is used to format text using Prettier. [Options](https://prettier.io/docs/options) may be provided to override the defaults.
*/
export function format(source: string, options?: Options): Promise<string>;
/**
* `check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
* This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
*/
export function check(source: string, options?: Options): Promise<boolean>;
/**
* Returns an object representing the parsers, languages and file types Prettier supports for the current version.
*/
export function getSupportInfo(): Promise<SupportInfo>;
+29
View File
File diff suppressed because one or more lines are too long
+29
View File
File diff suppressed because one or more lines are too long
+32
View File
@@ -0,0 +1,32 @@
{
"name": "havox",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "havox",
"version": "1.0.0",
"license": "ISC",
"devDependencies": {
"prettier": "^3.8.1"
}
},
"node_modules/prettier": {
"version": "3.8.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz",
"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "havox",
"version": "1.0.0",
"description": "",
"main": "404.js",
"scripts": {
"format": "prettier --write ."
},
"repository": {
"type": "git",
"url": "git@git.umbra.mom:jay/havox.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"prettier": "^3.8.1"
}
}
@@ -6,8 +6,5 @@
"main.5cae1eb5.css.map": "/projects/cellular_automata/static/css/main.5cae1eb5.css.map", "main.5cae1eb5.css.map": "/projects/cellular_automata/static/css/main.5cae1eb5.css.map",
"main.608a23ae.js.map": "/projects/cellular_automata/static/js/main.608a23ae.js.map" "main.608a23ae.js.map": "/projects/cellular_automata/static/js/main.608a23ae.js.map"
}, },
"entrypoints": [ "entrypoints": ["static/css/main.5cae1eb5.css", "static/js/main.608a23ae.js"]
"static/css/main.5cae1eb5.css", }
"static/js/main.608a23ae.js"
]
}
+31 -1
View File
@@ -1 +1,31 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/projects/cellular_automata/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/projects/cellular_automata/logo192.png"/><link rel="manifest" href="/projects/cellular_automata/manifest.json"/><title>React App</title><script defer="defer" src="/projects/cellular_automata/static/js/main.608a23ae.js"></script><link href="/projects/cellular_automata/static/css/main.5cae1eb5.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html> <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/projects/cellular_automata/favicon.ico" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link
rel="apple-touch-icon"
href="/projects/cellular_automata/logo192.png"
/>
<link rel="manifest" href="/projects/cellular_automata/manifest.json" />
<title>React App</title>
<script
defer="defer"
src="/projects/cellular_automata/static/js/main.608a23ae.js"
></script>
<link
href="/projects/cellular_automata/static/css/main.5cae1eb5.css"
rel="stylesheet"
/>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
-3
View File
@@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
@@ -1,2 +1,173 @@
#root,body,html{margin:0;min-height:100%}body{background:radial-gradient(circle at top,#eef4ff 0,#f8fbff 55%,#eef2f7 100%);color:#0f172a;font-family:Segoe UI,sans-serif}.cell{border:1px solid #1f2937;box-sizing:border-box;margin:0;padding:0}.dead{background:#000}.alive{background:#fff}.board{border:1px solid #94a3b8;cursor:crosshair;display:inline-block;-webkit-user-select:none;user-select:none}.row{display:flex}.horizontal-slider{margin:auto;width:100%}.example-thumb{background:#fff;border:5px solid #3774ff;border-radius:100%;box-shadow:0 0 2px 0 #00000070;cursor:pointer;display:block;position:absolute;z-index:100}.example-thumb.active{background-color:grey}.example-track{background:#ddd;position:relative}.example-track.example-track-0{background:#83a9ff}.horizontal-slider .example-track{height:4px;top:20px}.horizontal-slider .example-thumb{height:10px;line-height:38px;outline:none;top:12px;width:10px}.radioGroup{grid-gap:.45rem;display:grid;gap:.45rem}.radioOption{align-items:center;color:#1e293b;cursor:pointer;display:flex;font-size:.92rem;gap:.5rem}.radioOption input{accent-color:#2f7df6;margin:0}.title{margin:2rem 0 1.25rem;text-align:center}.title h1{color:#0f172a;font-size:2.2rem;letter-spacing:.03em;margin:0}.title p{color:#475569;font-size:.95rem;margin:.35rem 0 0}.body{align-items:flex-start;display:flex;gap:1.25rem;justify-content:center;margin:0 auto 1.75rem;max-width:980px;padding:0 1rem}.gameBoard{padding:.6rem}.controlPanel,.gameBoard{background:#fff;border:1px solid #d5deea;border-radius:12px;box-shadow:0 12px 28px #0f172a1a}.controlPanel{color:#1e293b;padding:1rem;width:270px}.panelSection{margin-bottom:1rem}.panelSection h3{color:#334155;font-size:.95rem;margin:0 0 .5rem}.buttonRow{grid-gap:.5rem;display:grid;gap:.5rem;grid-template-columns:repeat(3,1fr);margin-bottom:1.1rem}.controlButton{background:#f8fafc;border:1px solid #cbd5e1;border-radius:8px;color:#1e293b;cursor:pointer;font-weight:500;padding:.45rem .35rem}.controlButton:hover{background:#eef2f8}.sliderContainer{grid-gap:.25rem;display:grid;gap:.25rem}.sliderContainer span{color:#334155;font-size:.95rem}.fpsValue{color:#64748b;font-size:.85rem;margin:.3rem 0 0} #root,
/*# sourceMappingURL=main.5cae1eb5.css.map*/ body,
html {
margin: 0;
min-height: 100%;
}
body {
background: radial-gradient(
circle at top,
#eef4ff 0,
#f8fbff 55%,
#eef2f7 100%
);
color: #0f172a;
font-family:
Segoe UI,
sans-serif;
}
.cell {
border: 1px solid #1f2937;
box-sizing: border-box;
margin: 0;
padding: 0;
}
.dead {
background: #000;
}
.alive {
background: #fff;
}
.board {
border: 1px solid #94a3b8;
cursor: crosshair;
display: inline-block;
-webkit-user-select: none;
user-select: none;
}
.row {
display: flex;
}
.horizontal-slider {
margin: auto;
width: 100%;
}
.example-thumb {
background: #fff;
border: 5px solid #3774ff;
border-radius: 100%;
box-shadow: 0 0 2px 0 #00000070;
cursor: pointer;
display: block;
position: absolute;
z-index: 100;
}
.example-thumb.active {
background-color: grey;
}
.example-track {
background: #ddd;
position: relative;
}
.example-track.example-track-0 {
background: #83a9ff;
}
.horizontal-slider .example-track {
height: 4px;
top: 20px;
}
.horizontal-slider .example-thumb {
height: 10px;
line-height: 38px;
outline: none;
top: 12px;
width: 10px;
}
.radioGroup {
grid-gap: 0.45rem;
display: grid;
gap: 0.45rem;
}
.radioOption {
align-items: center;
color: #1e293b;
cursor: pointer;
display: flex;
font-size: 0.92rem;
gap: 0.5rem;
}
.radioOption input {
accent-color: #2f7df6;
margin: 0;
}
.title {
margin: 2rem 0 1.25rem;
text-align: center;
}
.title h1 {
color: #0f172a;
font-size: 2.2rem;
letter-spacing: 0.03em;
margin: 0;
}
.title p {
color: #475569;
font-size: 0.95rem;
margin: 0.35rem 0 0;
}
.body {
align-items: flex-start;
display: flex;
gap: 1.25rem;
justify-content: center;
margin: 0 auto 1.75rem;
max-width: 980px;
padding: 0 1rem;
}
.gameBoard {
padding: 0.6rem;
}
.controlPanel,
.gameBoard {
background: #fff;
border: 1px solid #d5deea;
border-radius: 12px;
box-shadow: 0 12px 28px #0f172a1a;
}
.controlPanel {
color: #1e293b;
padding: 1rem;
width: 270px;
}
.panelSection {
margin-bottom: 1rem;
}
.panelSection h3 {
color: #334155;
font-size: 0.95rem;
margin: 0 0 0.5rem;
}
.buttonRow {
grid-gap: 0.5rem;
display: grid;
gap: 0.5rem;
grid-template-columns: repeat(3, 1fr);
margin-bottom: 1.1rem;
}
.controlButton {
background: #f8fafc;
border: 1px solid #cbd5e1;
border-radius: 8px;
color: #1e293b;
cursor: pointer;
font-weight: 500;
padding: 0.45rem 0.35rem;
}
.controlButton:hover {
background: #eef2f8;
}
.sliderContainer {
grid-gap: 0.25rem;
display: grid;
gap: 0.25rem;
}
.sliderContainer span {
color: #334155;
font-size: 0.95rem;
}
.fpsValue {
color: #64748b;
font-size: 0.85rem;
margin: 0.3rem 0 0;
}
/*# sourceMappingURL=main.5cae1eb5.css.map*/
File diff suppressed because one or more lines are too long
+11 -11
View File
@@ -1,13 +1,13 @@
class cLine { class cLine {
constructor(a, b, col = color(180, 180, 180, 140), w = 2) { constructor(a, b, col = color(180, 180, 180, 140), w = 2) {
this.a = a; this.a = a;
this.b = b; this.b = b;
this.col = col; this.col = col;
this.w = w; this.w = w;
} }
drawLine() { drawLine() {
stroke(this.col); stroke(this.col);
strokeWeight(this.w); strokeWeight(this.w);
line(this.a.x, this.a.y, this.b.x, this.b.y); line(this.a.x, this.a.y, this.b.x, this.b.y);
} }
} }
+46 -38
View File
@@ -1,44 +1,52 @@
class cPoint { class cPoint {
constructor(x, y, kind = 'control') { constructor(x, y, kind = 'control') {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.kind = kind; this.kind = kind;
this.r = 9; this.r = 9;
} }
set changeX(nx) { this.x = nx; } set changeX(nx) {
set changeY(ny) { this.y = ny; } this.x = nx;
get changeX() { return this.x; } }
get changeY() { return this.y; } set changeY(ny) {
this.y = ny;
}
get changeX() {
return this.x;
}
get changeY() {
return this.y;
}
isHit(mx, my, r = HIT_R) { isHit(mx, my, r = HIT_R) {
return dist(mx, my, this.x, this.y) <= r; return dist(mx, my, this.x, this.y) <= r;
}
drawPoint(hovered = false, selected = false, styleOverride = null) {
strokeWeight(2);
if (styleOverride) {
stroke(...styleOverride.stroke);
fill(...styleOverride.fill);
} else {
if (this.kind === 'end') {
stroke(0, 220, 90, 240);
fill(40, 240, 120, 200);
} else if (this.kind === 'control') {
stroke(240, 140, 0, 240);
fill(255, 180, 40, 200);
} else {
stroke(140, 160);
fill(190, 160);
}
} }
drawPoint(hovered = false, selected = false, styleOverride = null) { if (selected) {
strokeWeight(2); stroke(255, 255, 0);
if (styleOverride) { strokeWeight(3);
stroke(...styleOverride.stroke); } else if (hovered) {
fill(...styleOverride.fill); stroke(255);
} else {
if (this.kind === 'end') {
stroke(0, 220, 90, 240);
fill(40, 240, 120, 200);
} else if (this.kind === 'control') {
stroke(240, 140, 0, 240);
fill(255, 180, 40, 200);
} else {
stroke(140, 160);
fill(190, 160);
}
}
if (selected) {
stroke(255, 255, 0);
strokeWeight(3);
} else if (hovered) {
stroke(255);
}
circle(this.x, this.y, this.r * 2);
} }
circle(this.x, this.y, this.r * 2);
}
} }
+174 -163
View File
@@ -1,6 +1,8 @@
let p = [], v = []; let p = [],
v = [];
let lines = []; let lines = [];
let theta = (3 / 2) * Math.PI, t = 0; let theta = (3 / 2) * Math.PI,
t = 0;
let paused = false; let paused = false;
let showLabels = false; let showLabels = false;
let showInterPoints = true; let showInterPoints = true;
@@ -13,227 +15,236 @@ const HIT_R = 10;
const MAX_TRAIL = 1000; const MAX_TRAIL = 1000;
function setup() { function setup() {
createCanvas(1000, 800); createCanvas(1000, 800);
initCubicCurve(true); initCubicCurve(true);
} }
function draw() { function draw() {
background(32); background(32);
stroke(120, 120, 120, 180); stroke(120, 120, 120, 180);
strokeWeight(2); strokeWeight(2);
noFill(); noFill();
beginShape(); beginShape();
vertex(p[0].x, p[0].y); vertex(p[0].x, p[0].y);
vertex(p[1].x, p[1].y); vertex(p[1].x, p[1].y);
vertex(p[2].x, p[2].y); vertex(p[2].x, p[2].y);
vertex(p[3].x, p[3].y); vertex(p[3].x, p[3].y);
endShape(); endShape();
if (!paused) { if (!paused) {
if (theta > TWO_PI) theta = 0; if (theta > TWO_PI) theta = 0;
theta += 0.01; theta += 0.01;
t = (sin(theta) + 1) / 2; // 0..1 t = (sin(theta) + 1) / 2; // 0..1
} }
lerpCubicCurve(); lerpCubicCurve();
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
lines[i].drawLine(); lines[i].drawLine();
} }
drawCurve(); drawCurve();
drawPointsAndLabels(); drawPointsAndLabels();
drawHUD(); drawHUD();
} }
function drawCurve() { function drawCurve() {
if (v.length > MAX_TRAIL) v.splice(0, v.length - MAX_TRAIL); if (v.length > MAX_TRAIL) v.splice(0, v.length - MAX_TRAIL);
stroke(0, 255, 0, 200); stroke(0, 255, 0, 200);
strokeWeight(5); strokeWeight(5);
noFill(); noFill();
beginShape(); beginShape();
for (let i = 0; i < v.length; i++) { for (let i = 0; i < v.length; i++) {
vertex(v[i].x, v[i].y); vertex(v[i].x, v[i].y);
} }
endShape(); endShape();
} }
function drawPointsAndLabels() { function drawPointsAndLabels() {
push(); push();
noStroke(); noStroke();
fill(255, 70, 70, 230); fill(255, 70, 70, 230);
circle(p[9].x, p[9].y, 14); circle(p[9].x, p[9].y, 14);
pop(); pop();
for (let i = 0; i < 4; i++) {
const hovered = (i === hoverIndex);
const selected = (i === selectedIndex);
p[i].drawPoint(hovered, selected);
if (showLabels) {
noStroke();
fill(255);
textSize(14);
textAlign(LEFT, BOTTOM);
text(`P${i}`, p[i].x + 10, p[i].y - 10);
}
}
for (let i = 0; i < 4; i++) {
const hovered = i === hoverIndex;
const selected = i === selectedIndex;
p[i].drawPoint(hovered, selected);
if (showLabels) { if (showLabels) {
noStroke(); fill(220); noStroke();
textSize(12); textAlign(LEFT, BOTTOM); fill(255);
text(`P4`, p[4].x + 8, p[4].y - 8); textSize(14);
textAlign(LEFT, BOTTOM);
text(`P${i}`, p[i].x + 10, p[i].y - 10);
} }
}
if (showInterPoints) { if (showLabels) {
const styleMid = { noStroke();
stroke: [80, 180, 255, 100], fill(220);
fill: [80, 180, 255, 50] textSize(12);
}; textAlign(LEFT, BOTTOM);
for (let i = 4; i <= 8; i++) { text(`P4`, p[4].x + 8, p[4].y - 8);
p[i].drawPoint(false, false, styleMid); }
if (showLabels) {
noStroke(); fill(200); if (showInterPoints) {
textSize(12); textAlign(LEFT, BOTTOM); const styleMid = {
text(`P${i}`, p[i].x + 8, p[i].y - 8); stroke: [80, 180, 255, 100],
} fill: [80, 180, 255, 50],
} };
for (let i = 4; i <= 8; i++) {
p[i].drawPoint(false, false, styleMid);
if (showLabels) {
noStroke();
fill(200);
textSize(12);
textAlign(LEFT, BOTTOM);
text(`P${i}`, p[i].x + 8, p[i].y - 8);
}
} }
}
} }
function drawHUD() { function drawHUD() {
noStroke(); noStroke();
fill(255); fill(255);
textSize(14); textSize(14);
textAlign(LEFT, TOP); textAlign(LEFT, TOP);
const hud = [ const hud = [
`t = ${t.toFixed(3)}`, `t = ${t.toFixed(3)}`,
`Space = ${paused ? 'Resume' : 'Pause'}`, `Space = ${paused ? 'Resume' : 'Pause'}`,
`H = Toggle points 5..8 | L = Toggle labels | R = Reset`, `H = Toggle points 5..8 | L = Toggle labels | R = Reset`,
`Drag a handle (P0..P3). Hold Shift to move the entire curve.` `Drag a handle (P0..P3). Hold Shift to move the entire curve.`,
]; ];
for (let i = 0; i < hud.length; i++) { for (let i = 0; i < hud.length; i++) {
text(hud[i], 12, 12 + i * 18); text(hud[i], 12, 12 + i * 18);
} }
} }
function initCubicCurve(resetPositions = true) { function initCubicCurve(resetPositions = true) {
p.length = 0; p.length = 0;
v.length = 0; v.length = 0;
lines.length = 0; lines.length = 0;
theta = (3 / 2) * Math.PI; theta = (3 / 2) * Math.PI;
t = 0; t = 0;
if (resetPositions) { if (resetPositions) {
p[0] = new cPoint(width * 0.15, height * 0.75, 'end'); p[0] = new cPoint(width * 0.15, height * 0.75, 'end');
p[1] = new cPoint(width * 0.35, height * 0.20, 'control'); p[1] = new cPoint(width * 0.35, height * 0.2, 'control');
p[2] = new cPoint(width * 0.65, height * 0.20, 'control'); p[2] = new cPoint(width * 0.65, height * 0.2, 'control');
p[3] = new cPoint(width * 0.85, height * 0.75, 'end'); p[3] = new cPoint(width * 0.85, height * 0.75, 'end');
} else { } else {
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
if (!p[i]) p[i] = new cPoint(width * (0.15 + i * 0.2), height / 2, i === 0 || i === 3 ? 'end' : 'control'); if (!p[i])
} p[i] = new cPoint(
width * (0.15 + i * 0.2),
height / 2,
i === 0 || i === 3 ? 'end' : 'control'
);
} }
}
// Derived points // Derived points
p[4] = new cPoint(0, 0, 'derived'); p[4] = new cPoint(0, 0, 'derived');
p[5] = new cPoint(0, 0, 'derived'); p[5] = new cPoint(0, 0, 'derived');
p[6] = new cPoint(0, 0, 'derived'); p[6] = new cPoint(0, 0, 'derived');
p[7] = new cPoint(0, 0, 'derived'); p[7] = new cPoint(0, 0, 'derived');
p[8] = new cPoint(0, 0, 'derived'); p[8] = new cPoint(0, 0, 'derived');
p[9] = new cPoint(0, 0, 'derived'); p[9] = new cPoint(0, 0, 'derived');
lines[0] = new cLine(p[4], p[5], color(160, 160, 160, 200), 2); lines[0] = new cLine(p[4], p[5], color(160, 160, 160, 200), 2);
lines[1] = new cLine(p[5], p[6], color(160, 160, 160, 200), 2); lines[1] = new cLine(p[5], p[6], color(160, 160, 160, 200), 2);
lines[2] = new cLine(p[7], p[8], color(200, 200, 200, 220), 3); lines[2] = new cLine(p[7], p[8], color(200, 200, 200, 220), 3);
} }
function lerpCubicCurve() { function lerpCubicCurve() {
// Level 1 // Level 1
p[4].changeX = (1 - t) * p[0].x + t * p[1].x; p[4].changeX = (1 - t) * p[0].x + t * p[1].x;
p[4].changeY = (1 - t) * p[0].y + t * p[1].y; p[4].changeY = (1 - t) * p[0].y + t * p[1].y;
p[5].changeX = (1 - t) * p[1].x + t * p[2].x; p[5].changeX = (1 - t) * p[1].x + t * p[2].x;
p[5].changeY = (1 - t) * p[1].y + t * p[2].y; p[5].changeY = (1 - t) * p[1].y + t * p[2].y;
p[6].changeX = (1 - t) * p[2].x + t * p[3].x; p[6].changeX = (1 - t) * p[2].x + t * p[3].x;
p[6].changeY = (1 - t) * p[2].y + t * p[3].y; p[6].changeY = (1 - t) * p[2].y + t * p[3].y;
// Level 2 // Level 2
p[7].changeX = (1 - t) * p[4].x + t * p[5].x; p[7].changeX = (1 - t) * p[4].x + t * p[5].x;
p[7].changeY = (1 - t) * p[4].y + t * p[5].y; p[7].changeY = (1 - t) * p[4].y + t * p[5].y;
p[8].changeX = (1 - t) * p[5].x + t * p[6].x; p[8].changeX = (1 - t) * p[5].x + t * p[6].x;
p[8].changeY = (1 - t) * p[5].y + t * p[6].y; p[8].changeY = (1 - t) * p[5].y + t * p[6].y;
// Final on-curve // Final on-curve
p[9].changeX = (1 - t) * p[7].x + t * p[8].x; p[9].changeX = (1 - t) * p[7].x + t * p[8].x;
p[9].changeY = (1 - t) * p[7].y + t * p[8].y; p[9].changeY = (1 - t) * p[7].y + t * p[8].y;
v.push(new cPoint(p[9].x, p[9].y, 'derived')); v.push(new cPoint(p[9].x, p[9].y, 'derived'));
} }
function mouseMoved() { function mouseMoved() {
hoverIndex = -1; hoverIndex = -1;
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
if (p[i].isHit(mouseX, mouseY)) { if (p[i].isHit(mouseX, mouseY)) {
hoverIndex = i; hoverIndex = i;
break; break;
}
} }
}
} }
function mousePressed() { function mousePressed() {
prevMouse.x = mouseX; prevMouse.x = mouseX;
prevMouse.y = mouseY; prevMouse.y = mouseY;
selectedIndex = -1; selectedIndex = -1;
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
if (p[i].isHit(mouseX, mouseY)) { if (p[i].isHit(mouseX, mouseY)) {
selectedIndex = i; selectedIndex = i;
break; break;
}
} }
}
draggingAll = keyIsDown(SHIFT) && selectedIndex === -1; draggingAll = keyIsDown(SHIFT) && selectedIndex === -1;
} }
function mouseDragged() { function mouseDragged() {
const dx = mouseX - prevMouse.x; const dx = mouseX - prevMouse.x;
const dy = mouseY - prevMouse.y; const dy = mouseY - prevMouse.y;
if (selectedIndex >= 0) { if (selectedIndex >= 0) {
p[selectedIndex].changeX = mouseX; p[selectedIndex].changeX = mouseX;
p[selectedIndex].changeY = mouseY; p[selectedIndex].changeY = mouseY;
v.length = 0; v.length = 0;
} else if (draggingAll) { } else if (draggingAll) {
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
p[i].changeX = p[i].x + dx; p[i].changeX = p[i].x + dx;
p[i].changeY = p[i].y + dy; p[i].changeY = p[i].y + dy;
}
v.length = 0;
} }
v.length = 0;
}
prevMouse.x = mouseX; prevMouse.x = mouseX;
prevMouse.y = mouseY; prevMouse.y = mouseY;
return false; return false;
} }
function mouseReleased() { function mouseReleased() {
selectedIndex = -1; selectedIndex = -1;
draggingAll = false; draggingAll = false;
} }
function keyPressed() { function keyPressed() {
if (key === ' ') { if (key === ' ') {
paused = !paused; paused = !paused;
} else if (key === 'R' || key === 'r') { } else if (key === 'R' || key === 'r') {
initCubicCurve(true); initCubicCurve(true);
} else if (key === 'H' || key === 'h') { } else if (key === 'H' || key === 'h') {
showInterPoints = !showInterPoints; showInterPoints = !showInterPoints;
} else if (key === 'L' || key === 'l') { } else if (key === 'L' || key === 'l') {
showLabels = !showLabels; showLabels = !showLabels;
} }
} }
+191 -191
View File
@@ -1,191 +1,191 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>
</head> </head>
<style> <style>
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
background: #fafafa; background: #fafafa;
margin: 20px; margin: 20px;
text-align: center; text-align: center;
} }
#container { #container {
max-width: 900px; max-width: 900px;
margin: 0 auto; margin: 0 auto;
} }
h1, h1,
h2, h2,
p { p {
margin: 10px 0; margin: 10px 0;
} }
</style> </style>
<div id="container"> <div id="container">
<h1>Ellipse Construction</h1> <h1>Ellipse Construction</h1>
<p> <p>
Inspired by a Richard Feyman's Inspired by a Richard Feyman's
<a href="https://en.wikipedia.org/wiki/Feynman's_Lost_Lecture" <a href="https://en.wikipedia.org/wiki/Feynman's_Lost_Lecture"
>lost lecture</a >lost lecture</a
> >
& &
<a href="https://www.youtube.com/watch?v=xdIjYBtnvZU" <a href="https://www.youtube.com/watch?v=xdIjYBtnvZU"
>3blue1brown's video</a >3blue1brown's video</a
>. >.
</p> </p>
<p>A geometric proof as to why planetary orbits are ellipitcal.</p> <p>A geometric proof as to why planetary orbits are ellipitcal.</p>
<h2 id="PIbox"></h2> <h2 id="PIbox"></h2>
<h3 id="percentage"></h3> <h3 id="percentage"></h3>
</div> </div>
<script> <script>
class dot { class dot {
constructor(x, y) { constructor(x, y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
} }
var ux, uy; var ux, uy;
var points = []; var points = [];
var numericValue = 15; var numericValue = 15;
function setup() { function setup() {
createCanvas(800, 800); createCanvas(800, 800);
background(41); background(41);
} }
function draw() { function draw() {
translate(width / 2, height / 2); translate(width / 2, height / 2);
background(41); background(41);
stroke(75, 75, 215); stroke(75, 75, 215);
strokeWeight(3); strokeWeight(3);
noFill(); noFill();
ellipse(0, 0, width - 0.0625 * width, height - 0.0625 * height); ellipse(0, 0, width - 0.0625 * width, height - 0.0625 * height);
stroke(215, 215, 15); stroke(215, 215, 15);
strokeWeight(7); strokeWeight(7);
point(0, 0); point(0, 0);
if (mouseY > 0 && mouseY < height && mouseX > 0 && mouseX < width) { if (mouseY > 0 && mouseY < height && mouseX > 0 && mouseX < width) {
if (mouseIsPressed == true && mouseButton == LEFT) { if (mouseIsPressed == true && mouseButton == LEFT) {
ux = mouseX - width / 2; ux = mouseX - width / 2;
uy = mouseY - height / 2; uy = mouseY - height / 2;
point(ux, uy); point(ux, uy);
getCirclePoints(); getCirclePoints();
drawLines(ux, uy); drawLines(ux, uy);
drawTLines(ux, uy); drawTLines(ux, uy);
} else if (mouseIsPressed == true && mouseButton == RIGHT) { } else if (mouseIsPressed == true && mouseButton == RIGHT) {
ux = mouseX - width / 2; ux = mouseX - width / 2;
uy = mouseY - height / 2; uy = mouseY - height / 2;
point(ux, uy); point(ux, uy);
getCirclePoints(); getCirclePoints();
drawTLines(ux, uy); drawTLines(ux, uy);
} }
} }
} }
function getCirclePoints() { function getCirclePoints() {
var r = (width - 0.0625 * width) / 2; var r = (width - 0.0625 * width) / 2;
var step = 1 / numericValue; var step = 1 / numericValue;
var index = 0; var index = 0;
for (var i = 0; i < TWO_PI; i += step) { for (var i = 0; i < TWO_PI; i += step) {
var cx = r * Math.sin(i); var cx = r * Math.sin(i);
var cy = r * Math.cos(i); var cy = r * Math.cos(i);
points[index] = new dot(cx, cy); points[index] = new dot(cx, cy);
index++; index++;
} }
} }
function drawLines(startX, startY) { function drawLines(startX, startY) {
strokeWeight(0.4); strokeWeight(0.4);
stroke(255, 100); stroke(255, 100);
for (var i = 0; i < points.length; i++) { for (var i = 0; i < points.length; i++) {
line(startX, startY, points[i].x, points[i].y); line(startX, startY, points[i].x, points[i].y);
//findMidpoint(startX, startY, points[i].x, points[i].y); //findMidpoint(startX, startY, points[i].x, points[i].y);
} }
} }
function drawTLines(startX, startY) { function drawTLines(startX, startY) {
strokeWeight(0.4); strokeWeight(0.4);
stroke(255); stroke(255);
for (var i = 0; i < points.length; i++) { for (var i = 0; i < points.length; i++) {
findMidpoint(startX, startY, points[i].x, points[i].y); findMidpoint(startX, startY, points[i].x, points[i].y);
} }
} }
function findMidpoint(x1, y1, x2, y2) { function findMidpoint(x1, y1, x2, y2) {
//find center //find center
var cx = (x1 + x2) / 2; var cx = (x1 + x2) / 2;
var cy = (y1 + y2) / 2; var cy = (y1 + y2) / 2;
//move line to the center on the origin //move line to the center on the origin
x1 -= cx; x1 -= cx;
y1 -= cy; y1 -= cy;
x2 -= cx; x2 -= cx;
y2 -= cy; y2 -= cy;
//rotate both points //rotate both points
xtemp = x1; xtemp = x1;
ytemp = y1; ytemp = y1;
x1 = -ytemp; x1 = -ytemp;
y1 = xtemp; y1 = xtemp;
xtemp = x2; xtemp = x2;
ytemp = y2; ytemp = y2;
x2 = -ytemp; x2 = -ytemp;
y2 = xtemp; y2 = xtemp;
//move the center point back to where it was //move the center point back to where it was
x1 += cx; x1 += cx;
y1 += cy; y1 += cy;
x2 += cx; x2 += cx;
y2 += cy; y2 += cy;
stroke(255, 0, 0); stroke(255, 0, 0);
line(x1, y1, x2, y2); line(x1, y1, x2, y2);
stroke(255); stroke(255);
} }
function genLines() { function genLines() {
var pointOk = false; var pointOk = false;
do { do {
ux = random(width); ux = random(width);
uy = random(height); uy = random(height);
if (getDist(0, ux, 0, uy) <= (width - 0.0625 * width) / 2) { if (getDist(0, ux, 0, uy) <= (width - 0.0625 * width) / 2) {
pointOk = true; pointOk = true;
} }
} while (!pointOk); } while (!pointOk);
point(ux, uy); point(ux, uy);
getCirclePoints(); getCirclePoints();
drawLines(ux, uy); drawLines(ux, uy);
drawTLines(ux, uy); drawTLines(ux, uy);
} }
function genTLines() { function genTLines() {
var pointOk = false; var pointOk = false;
do { do {
ux = random(width); ux = random(width);
uy = random(height); uy = random(height);
if (getDist(0, ux, 0, uy) <= (width - 0.0625 * width) / 2) { if (getDist(0, ux, 0, uy) <= (width - 0.0625 * width) / 2) {
pointOk = true; pointOk = true;
} }
} while (!pointOk); } while (!pointOk);
point(ux, uy); point(ux, uy);
getCirclePoints(); getCirclePoints();
drawTLines(ux, uy); drawTLines(ux, uy);
} }
function getDist(x1, x2, y1, y2) { function getDist(x1, x2, y1, y2) {
return Math.sqrt((x1 - x2) ^ (2 + (y1 - y2)) ^ 2); return Math.sqrt((x1 - x2) ^ (2 + (y1 - y2)) ^ 2);
} }
</script> </script>
</html> </html>
+50 -38
View File
@@ -2,46 +2,51 @@
/* eslint-disable */ /* eslint-disable */
export class SimulationWasm { export class SimulationWasm {
free(): void; free(): void;
[Symbol.dispose](): void; [Symbol.dispose](): void;
add_boid(): void; add_boid(): void;
boid_buffer_len(): number; boid_buffer_len(): number;
boid_buffer_ptr(): number; boid_buffer_ptr(): number;
boid_buffer_stride(): number; boid_buffer_stride(): number;
get_align_mult(): number; get_align_mult(): number;
get_boid_count(): number; get_boid_count(): number;
get_cohesion_mult(): number; get_cohesion_mult(): number;
get_separation_mult(): number; get_separation_mult(): number;
constructor(width: number, height: number, num_boids: number); constructor(width: number, height: number, num_boids: number);
remove_boid(): void; remove_boid(): void;
resize(width: number, height: number): void; resize(width: number, height: number): void;
set_align_mult(value: number): void; set_align_mult(value: number): void;
set_cohesion_mult(value: number): void; set_cohesion_mult(value: number): void;
set_separation_mult(value: number): void; set_separation_mult(value: number): void;
step(): void; step(): void;
} }
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module; export type InitInput =
| RequestInfo
| URL
| Response
| BufferSource
| WebAssembly.Module;
export interface InitOutput { export interface InitOutput {
readonly memory: WebAssembly.Memory; readonly memory: WebAssembly.Memory;
readonly __wbg_simulationwasm_free: (a: number, b: number) => void; readonly __wbg_simulationwasm_free: (a: number, b: number) => void;
readonly simulationwasm_add_boid: (a: number) => void; readonly simulationwasm_add_boid: (a: number) => void;
readonly simulationwasm_boid_buffer_len: (a: number) => number; readonly simulationwasm_boid_buffer_len: (a: number) => number;
readonly simulationwasm_boid_buffer_ptr: (a: number) => number; readonly simulationwasm_boid_buffer_ptr: (a: number) => number;
readonly simulationwasm_boid_buffer_stride: (a: number) => number; readonly simulationwasm_boid_buffer_stride: (a: number) => number;
readonly simulationwasm_get_align_mult: (a: number) => number; readonly simulationwasm_get_align_mult: (a: number) => number;
readonly simulationwasm_get_boid_count: (a: number) => number; readonly simulationwasm_get_boid_count: (a: number) => number;
readonly simulationwasm_get_cohesion_mult: (a: number) => number; readonly simulationwasm_get_cohesion_mult: (a: number) => number;
readonly simulationwasm_get_separation_mult: (a: number) => number; readonly simulationwasm_get_separation_mult: (a: number) => number;
readonly simulationwasm_new: (a: number, b: number, c: number) => number; readonly simulationwasm_new: (a: number, b: number, c: number) => number;
readonly simulationwasm_remove_boid: (a: number) => void; readonly simulationwasm_remove_boid: (a: number) => void;
readonly simulationwasm_resize: (a: number, b: number, c: number) => void; readonly simulationwasm_resize: (a: number, b: number, c: number) => void;
readonly simulationwasm_set_align_mult: (a: number, b: number) => void; readonly simulationwasm_set_align_mult: (a: number, b: number) => void;
readonly simulationwasm_set_cohesion_mult: (a: number, b: number) => void; readonly simulationwasm_set_cohesion_mult: (a: number, b: number) => void;
readonly simulationwasm_set_separation_mult: (a: number, b: number) => void; readonly simulationwasm_set_separation_mult: (a: number, b: number) => void;
readonly simulationwasm_step: (a: number) => void; readonly simulationwasm_step: (a: number) => void;
readonly __wbindgen_export: (a: number) => void; readonly __wbindgen_export: (a: number) => void;
} }
export type SyncInitInput = BufferSource | WebAssembly.Module; export type SyncInitInput = BufferSource | WebAssembly.Module;
@@ -54,7 +59,9 @@ export type SyncInitInput = BufferSource | WebAssembly.Module;
* *
* @returns {InitOutput} * @returns {InitOutput}
*/ */
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput; export function initSync(
module: { module: SyncInitInput } | SyncInitInput
): InitOutput;
/** /**
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
@@ -64,4 +71,9 @@ export function initSync(module: { module: SyncInitInput } | SyncInitInput): Ini
* *
* @returns {Promise<InitOutput>} * @returns {Promise<InitOutput>}
*/ */
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>; export default function __wbg_init(
module_or_path?:
| { module_or_path: InitInput | Promise<InitInput> }
| InitInput
| Promise<InitInput>
): Promise<InitOutput>;
+355 -311
View File
@@ -1,270 +1,290 @@
/* @ts-self-types="./flocking.d.ts" */ /* @ts-self-types="./flocking.d.ts" */
export class SimulationWasm { export class SimulationWasm {
__destroy_into_raw() { __destroy_into_raw() {
const ptr = this.__wbg_ptr; const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0; this.__wbg_ptr = 0;
SimulationWasmFinalization.unregister(this); SimulationWasmFinalization.unregister(this);
return ptr; return ptr;
} }
free() { free() {
const ptr = this.__destroy_into_raw(); const ptr = this.__destroy_into_raw();
wasm.__wbg_simulationwasm_free(ptr, 0); wasm.__wbg_simulationwasm_free(ptr, 0);
} }
add_boid() { add_boid() {
wasm.simulationwasm_add_boid(this.__wbg_ptr); wasm.simulationwasm_add_boid(this.__wbg_ptr);
} }
/** /**
* @returns {number} * @returns {number}
*/ */
boid_buffer_len() { boid_buffer_len() {
const ret = wasm.simulationwasm_boid_buffer_len(this.__wbg_ptr); const ret = wasm.simulationwasm_boid_buffer_len(this.__wbg_ptr);
return ret >>> 0; return ret >>> 0;
} }
/** /**
* @returns {number} * @returns {number}
*/ */
boid_buffer_ptr() { boid_buffer_ptr() {
const ret = wasm.simulationwasm_boid_buffer_ptr(this.__wbg_ptr); const ret = wasm.simulationwasm_boid_buffer_ptr(this.__wbg_ptr);
return ret >>> 0; return ret >>> 0;
} }
/** /**
* @returns {number} * @returns {number}
*/ */
boid_buffer_stride() { boid_buffer_stride() {
const ret = wasm.simulationwasm_boid_buffer_stride(this.__wbg_ptr); const ret = wasm.simulationwasm_boid_buffer_stride(this.__wbg_ptr);
return ret >>> 0; return ret >>> 0;
} }
/** /**
* @returns {number} * @returns {number}
*/ */
get_align_mult() { get_align_mult() {
const ret = wasm.simulationwasm_get_align_mult(this.__wbg_ptr); const ret = wasm.simulationwasm_get_align_mult(this.__wbg_ptr);
return ret; return ret;
} }
/** /**
* @returns {number} * @returns {number}
*/ */
get_boid_count() { get_boid_count() {
const ret = wasm.simulationwasm_get_boid_count(this.__wbg_ptr); const ret = wasm.simulationwasm_get_boid_count(this.__wbg_ptr);
return ret >>> 0; return ret >>> 0;
} }
/** /**
* @returns {number} * @returns {number}
*/ */
get_cohesion_mult() { get_cohesion_mult() {
const ret = wasm.simulationwasm_get_cohesion_mult(this.__wbg_ptr); const ret = wasm.simulationwasm_get_cohesion_mult(this.__wbg_ptr);
return ret; return ret;
} }
/** /**
* @returns {number} * @returns {number}
*/ */
get_separation_mult() { get_separation_mult() {
const ret = wasm.simulationwasm_get_separation_mult(this.__wbg_ptr); const ret = wasm.simulationwasm_get_separation_mult(this.__wbg_ptr);
return ret; return ret;
} }
/** /**
* @param {number} width * @param {number} width
* @param {number} height * @param {number} height
* @param {number} num_boids * @param {number} num_boids
*/ */
constructor(width, height, num_boids) { constructor(width, height, num_boids) {
const ret = wasm.simulationwasm_new(width, height, num_boids); const ret = wasm.simulationwasm_new(width, height, num_boids);
this.__wbg_ptr = ret >>> 0; this.__wbg_ptr = ret >>> 0;
SimulationWasmFinalization.register(this, this.__wbg_ptr, this); SimulationWasmFinalization.register(this, this.__wbg_ptr, this);
return this; return this;
} }
remove_boid() { remove_boid() {
wasm.simulationwasm_remove_boid(this.__wbg_ptr); wasm.simulationwasm_remove_boid(this.__wbg_ptr);
} }
/** /**
* @param {number} width * @param {number} width
* @param {number} height * @param {number} height
*/ */
resize(width, height) { resize(width, height) {
wasm.simulationwasm_resize(this.__wbg_ptr, width, height); wasm.simulationwasm_resize(this.__wbg_ptr, width, height);
} }
/** /**
* @param {number} value * @param {number} value
*/ */
set_align_mult(value) { set_align_mult(value) {
wasm.simulationwasm_set_align_mult(this.__wbg_ptr, value); wasm.simulationwasm_set_align_mult(this.__wbg_ptr, value);
} }
/** /**
* @param {number} value * @param {number} value
*/ */
set_cohesion_mult(value) { set_cohesion_mult(value) {
wasm.simulationwasm_set_cohesion_mult(this.__wbg_ptr, value); wasm.simulationwasm_set_cohesion_mult(this.__wbg_ptr, value);
} }
/** /**
* @param {number} value * @param {number} value
*/ */
set_separation_mult(value) { set_separation_mult(value) {
wasm.simulationwasm_set_separation_mult(this.__wbg_ptr, value); wasm.simulationwasm_set_separation_mult(this.__wbg_ptr, value);
} }
step() { step() {
wasm.simulationwasm_step(this.__wbg_ptr); wasm.simulationwasm_step(this.__wbg_ptr);
} }
} }
if (Symbol.dispose) SimulationWasm.prototype[Symbol.dispose] = SimulationWasm.prototype.free; if (Symbol.dispose)
SimulationWasm.prototype[Symbol.dispose] = SimulationWasm.prototype.free;
function __wbg_get_imports() { function __wbg_get_imports() {
const import0 = { const import0 = {
__proto__: null, __proto__: null,
__wbg___wbindgen_is_function_3c846841762788c1: function(arg0) { __wbg___wbindgen_is_function_3c846841762788c1: function (arg0) {
const ret = typeof(getObject(arg0)) === 'function'; const ret = typeof getObject(arg0) === 'function';
return ret; return ret;
}, },
__wbg___wbindgen_is_object_781bc9f159099513: function(arg0) { __wbg___wbindgen_is_object_781bc9f159099513: function (arg0) {
const val = getObject(arg0); const val = getObject(arg0);
const ret = typeof(val) === 'object' && val !== null; const ret = typeof val === 'object' && val !== null;
return ret; return ret;
}, },
__wbg___wbindgen_is_string_7ef6b97b02428fae: function(arg0) { __wbg___wbindgen_is_string_7ef6b97b02428fae: function (arg0) {
const ret = typeof(getObject(arg0)) === 'string'; const ret = typeof getObject(arg0) === 'string';
return ret; return ret;
}, },
__wbg___wbindgen_is_undefined_52709e72fb9f179c: function(arg0) { __wbg___wbindgen_is_undefined_52709e72fb9f179c: function (arg0) {
const ret = getObject(arg0) === undefined; const ret = getObject(arg0) === undefined;
return ret; return ret;
}, },
__wbg___wbindgen_throw_6ddd609b62940d55: function(arg0, arg1) { __wbg___wbindgen_throw_6ddd609b62940d55: function (arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1)); throw new Error(getStringFromWasm0(arg0, arg1));
}, },
__wbg_call_2d781c1f4d5c0ef8: function() { return handleError(function (arg0, arg1, arg2) { __wbg_call_2d781c1f4d5c0ef8: function () {
const ret = getObject(arg0).call(getObject(arg1), getObject(arg2)); return handleError(function (arg0, arg1, arg2) {
return addHeapObject(ret); const ret = getObject(arg0).call(getObject(arg1), getObject(arg2));
}, arguments); }, return addHeapObject(ret);
__wbg_crypto_38df2bab126b63dc: function(arg0) { }, arguments);
const ret = getObject(arg0).crypto; },
return addHeapObject(ret); __wbg_crypto_38df2bab126b63dc: function (arg0) {
}, const ret = getObject(arg0).crypto;
__wbg_getRandomValues_c44a50d8cfdaebeb: function() { return handleError(function (arg0, arg1) { return addHeapObject(ret);
getObject(arg0).getRandomValues(getObject(arg1)); },
}, arguments); }, __wbg_getRandomValues_c44a50d8cfdaebeb: function () {
__wbg_length_ea16607d7b61445b: function(arg0) { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).length; getObject(arg0).getRandomValues(getObject(arg1));
return ret; }, arguments);
}, },
__wbg_msCrypto_bd5a034af96bcba6: function(arg0) { __wbg_length_ea16607d7b61445b: function (arg0) {
const ret = getObject(arg0).msCrypto; const ret = getObject(arg0).length;
return addHeapObject(ret); return ret;
}, },
__wbg_new_with_length_825018a1616e9e55: function(arg0) { __wbg_msCrypto_bd5a034af96bcba6: function (arg0) {
const ret = new Uint8Array(arg0 >>> 0); const ret = getObject(arg0).msCrypto;
return addHeapObject(ret); return addHeapObject(ret);
}, },
__wbg_node_84ea875411254db1: function(arg0) { __wbg_new_with_length_825018a1616e9e55: function (arg0) {
const ret = getObject(arg0).node; const ret = new Uint8Array(arg0 >>> 0);
return addHeapObject(ret); return addHeapObject(ret);
}, },
__wbg_process_44c7a14e11e9f69e: function(arg0) { __wbg_node_84ea875411254db1: function (arg0) {
const ret = getObject(arg0).process; const ret = getObject(arg0).node;
return addHeapObject(ret); return addHeapObject(ret);
}, },
__wbg_prototypesetcall_d62e5099504357e6: function(arg0, arg1, arg2) { __wbg_process_44c7a14e11e9f69e: function (arg0) {
Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), getObject(arg2)); const ret = getObject(arg0).process;
}, return addHeapObject(ret);
__wbg_randomFillSync_6c25eac9869eb53c: function() { return handleError(function (arg0, arg1) { },
getObject(arg0).randomFillSync(takeObject(arg1)); __wbg_prototypesetcall_d62e5099504357e6: function (arg0, arg1, arg2) {
}, arguments); }, Uint8Array.prototype.set.call(
__wbg_require_b4edbdcf3e2a1ef0: function() { return handleError(function () { getArrayU8FromWasm0(arg0, arg1),
const ret = module.require; getObject(arg2)
return addHeapObject(ret); );
}, arguments); }, },
__wbg_static_accessor_GLOBAL_8adb955bd33fac2f: function() { __wbg_randomFillSync_6c25eac9869eb53c: function () {
const ret = typeof global === 'undefined' ? null : global; return handleError(function (arg0, arg1) {
return isLikeNone(ret) ? 0 : addHeapObject(ret); getObject(arg0).randomFillSync(takeObject(arg1));
}, }, arguments);
__wbg_static_accessor_GLOBAL_THIS_ad356e0db91c7913: function() { },
const ret = typeof globalThis === 'undefined' ? null : globalThis; __wbg_require_b4edbdcf3e2a1ef0: function () {
return isLikeNone(ret) ? 0 : addHeapObject(ret); return handleError(function () {
}, const ret = module.require;
__wbg_static_accessor_SELF_f207c857566db248: function() { return addHeapObject(ret);
const ret = typeof self === 'undefined' ? null : self; }, arguments);
return isLikeNone(ret) ? 0 : addHeapObject(ret); },
}, __wbg_static_accessor_GLOBAL_8adb955bd33fac2f: function () {
__wbg_static_accessor_WINDOW_bb9f1ba69d61b386: function() { const ret = typeof global === 'undefined' ? null : global;
const ret = typeof window === 'undefined' ? null : window; return isLikeNone(ret) ? 0 : addHeapObject(ret);
return isLikeNone(ret) ? 0 : addHeapObject(ret); },
}, __wbg_static_accessor_GLOBAL_THIS_ad356e0db91c7913: function () {
__wbg_subarray_a068d24e39478a8a: function(arg0, arg1, arg2) { const ret = typeof globalThis === 'undefined' ? null : globalThis;
const ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0); return isLikeNone(ret) ? 0 : addHeapObject(ret);
return addHeapObject(ret); },
}, __wbg_static_accessor_SELF_f207c857566db248: function () {
__wbg_versions_276b2795b1c6a219: function(arg0) { const ret = typeof self === 'undefined' ? null : self;
const ret = getObject(arg0).versions; return isLikeNone(ret) ? 0 : addHeapObject(ret);
return addHeapObject(ret); },
}, __wbg_static_accessor_WINDOW_bb9f1ba69d61b386: function () {
__wbindgen_cast_0000000000000001: function(arg0, arg1) { const ret = typeof window === 'undefined' ? null : window;
// Cast intrinsic for `Ref(Slice(U8)) -> NamedExternref("Uint8Array")`. return isLikeNone(ret) ? 0 : addHeapObject(ret);
const ret = getArrayU8FromWasm0(arg0, arg1); },
return addHeapObject(ret); __wbg_subarray_a068d24e39478a8a: function (arg0, arg1, arg2) {
}, const ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
__wbindgen_cast_0000000000000002: function(arg0, arg1) { return addHeapObject(ret);
// Cast intrinsic for `Ref(String) -> Externref`. },
const ret = getStringFromWasm0(arg0, arg1); __wbg_versions_276b2795b1c6a219: function (arg0) {
return addHeapObject(ret); const ret = getObject(arg0).versions;
}, return addHeapObject(ret);
__wbindgen_object_clone_ref: function(arg0) { },
const ret = getObject(arg0); __wbindgen_cast_0000000000000001: function (arg0, arg1) {
return addHeapObject(ret); // Cast intrinsic for `Ref(Slice(U8)) -> NamedExternref("Uint8Array")`.
}, const ret = getArrayU8FromWasm0(arg0, arg1);
__wbindgen_object_drop_ref: function(arg0) { return addHeapObject(ret);
takeObject(arg0); },
}, __wbindgen_cast_0000000000000002: function (arg0, arg1) {
}; // Cast intrinsic for `Ref(String) -> Externref`.
return { const ret = getStringFromWasm0(arg0, arg1);
__proto__: null, return addHeapObject(ret);
"./flocking_bg.js": import0, },
}; __wbindgen_object_clone_ref: function (arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
},
__wbindgen_object_drop_ref: function (arg0) {
takeObject(arg0);
},
};
return {
__proto__: null,
'./flocking_bg.js': import0,
};
} }
const SimulationWasmFinalization = (typeof FinalizationRegistry === 'undefined') const SimulationWasmFinalization =
typeof FinalizationRegistry === 'undefined'
? { register: () => {}, unregister: () => {} } ? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_simulationwasm_free(ptr >>> 0, 1)); : new FinalizationRegistry((ptr) =>
wasm.__wbg_simulationwasm_free(ptr >>> 0, 1)
);
function addHeapObject(obj) { function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1); if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next; const idx = heap_next;
heap_next = heap[idx]; heap_next = heap[idx];
heap[idx] = obj; heap[idx] = obj;
return idx; return idx;
} }
function dropObject(idx) { function dropObject(idx) {
if (idx < 1028) return; if (idx < 1028) return;
heap[idx] = heap_next; heap[idx] = heap_next;
heap_next = idx; heap_next = idx;
} }
function getArrayU8FromWasm0(ptr, len) { function getArrayU8FromWasm0(ptr, len) {
ptr = ptr >>> 0; ptr = ptr >>> 0;
return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
} }
function getStringFromWasm0(ptr, len) { function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0; ptr = ptr >>> 0;
return decodeText(ptr, len); return decodeText(ptr, len);
} }
let cachedUint8ArrayMemory0 = null; let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() { function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { if (
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); cachedUint8ArrayMemory0 === null ||
} cachedUint8ArrayMemory0.byteLength === 0
return cachedUint8ArrayMemory0; ) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
} }
function getObject(idx) { return heap[idx]; } function getObject(idx) {
return heap[idx];
}
function handleError(f, args) { function handleError(f, args) {
try { try {
return f.apply(this, args); return f.apply(this, args);
} catch (e) { } catch (e) {
wasm.__wbindgen_export(addHeapObject(e)); wasm.__wbindgen_export(addHeapObject(e));
} }
} }
let heap = new Array(1024).fill(undefined); let heap = new Array(1024).fill(undefined);
@@ -273,116 +293,140 @@ heap.push(undefined, null, true, false);
let heap_next = heap.length; let heap_next = heap.length;
function isLikeNone(x) { function isLikeNone(x) {
return x === undefined || x === null; return x === undefined || x === null;
} }
function takeObject(idx) { function takeObject(idx) {
const ret = getObject(idx); const ret = getObject(idx);
dropObject(idx); dropObject(idx);
return ret; return ret;
} }
let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); let cachedTextDecoder = new TextDecoder('utf-8', {
ignoreBOM: true,
fatal: true,
});
cachedTextDecoder.decode(); cachedTextDecoder.decode();
const MAX_SAFARI_DECODE_BYTES = 2146435072; const MAX_SAFARI_DECODE_BYTES = 2146435072;
let numBytesDecoded = 0; let numBytesDecoded = 0;
function decodeText(ptr, len) { function decodeText(ptr, len) {
numBytesDecoded += len; numBytesDecoded += len;
if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) { if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); cachedTextDecoder = new TextDecoder('utf-8', {
cachedTextDecoder.decode(); ignoreBOM: true,
numBytesDecoded = len; fatal: true,
} });
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); cachedTextDecoder.decode();
numBytesDecoded = len;
}
return cachedTextDecoder.decode(
getUint8ArrayMemory0().subarray(ptr, ptr + len)
);
} }
let wasmModule, wasm; let wasmModule, wasm;
function __wbg_finalize_init(instance, module) { function __wbg_finalize_init(instance, module) {
wasm = instance.exports; wasm = instance.exports;
wasmModule = module; wasmModule = module;
cachedUint8ArrayMemory0 = null; cachedUint8ArrayMemory0 = null;
return wasm; return wasm;
} }
async function __wbg_load(module, imports) { async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) { if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') { if (typeof WebAssembly.instantiateStreaming === 'function') {
try { try {
return await WebAssembly.instantiateStreaming(module, imports); return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) { } catch (e) {
const validResponse = module.ok && expectedResponseType(module.type); const validResponse = module.ok && expectedResponseType(module.type);
if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') { if (
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); validResponse &&
module.headers.get('Content-Type') !== 'application/wasm'
} else { throw e; } ) {
} console.warn(
} '`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n',
e
const bytes = await module.arrayBuffer(); );
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else { } else {
return instance; throw e;
} }
}
} }
function expectedResponseType(type) { const bytes = await module.arrayBuffer();
switch (type) { return await WebAssembly.instantiate(bytes, imports);
case 'basic': case 'cors': case 'default': return true; } else {
} const instance = await WebAssembly.instantiate(module, imports);
return false;
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
} }
}
function expectedResponseType(type) {
switch (type) {
case 'basic':
case 'cors':
case 'default':
return true;
}
return false;
}
} }
function initSync(module) { function initSync(module) {
if (wasm !== undefined) return wasm; if (wasm !== undefined) return wasm;
if (module !== undefined) {
if (module !== undefined) { if (Object.getPrototypeOf(module) === Object.prototype) {
if (Object.getPrototypeOf(module) === Object.prototype) { ({ module } = module);
({module} = module) } else {
} else { console.warn(
console.warn('using deprecated parameters for `initSync()`; pass a single object instead') 'using deprecated parameters for `initSync()`; pass a single object instead'
} );
} }
}
const imports = __wbg_get_imports(); const imports = __wbg_get_imports();
if (!(module instanceof WebAssembly.Module)) { if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module); module = new WebAssembly.Module(module);
} }
const instance = new WebAssembly.Instance(module, imports); const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module); return __wbg_finalize_init(instance, module);
} }
async function __wbg_init(module_or_path) { async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm; if (wasm !== undefined) return wasm;
if (module_or_path !== undefined) {
if (module_or_path !== undefined) { if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) { ({ module_or_path } = module_or_path);
({module_or_path} = module_or_path) } else {
} else { console.warn(
console.warn('using deprecated parameters for the initialization function; pass a single object instead') 'using deprecated parameters for the initialization function; pass a single object instead'
} );
} }
}
if (module_or_path === undefined) { if (module_or_path === undefined) {
module_or_path = new URL('flocking_bg.wasm', import.meta.url); module_or_path = new URL('flocking_bg.wasm', import.meta.url);
} }
const imports = __wbg_get_imports(); const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { if (
module_or_path = fetch(module_or_path); typeof module_or_path === 'string' ||
} (typeof Request === 'function' && module_or_path instanceof Request) ||
(typeof URL === 'function' && module_or_path instanceof URL)
) {
module_or_path = fetch(module_or_path);
}
const { instance, module } = await __wbg_load(await module_or_path, imports); const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module); return __wbg_finalize_init(instance, module);
} }
export { initSync, __wbg_init as default }; export { initSync, __wbg_init as default };
+1 -1
View File
@@ -12,4 +12,4 @@
"sideEffects": [ "sideEffects": [
"./snippets/*" "./snippets/*"
] ]
} }
+164 -160
View File
@@ -19,223 +19,227 @@ let displayHeight = 1;
let resizeAnimationFrame = 0; let resizeAnimationFrame = 0;
function clamp(value, min, max) { function clamp(value, min, max) {
return Math.min(Math.max(value, min), max); return Math.min(Math.max(value, min), max);
} }
function getInitialBoidCount(width, height) { function getInitialBoidCount(width, height) {
const areaScale = (width * height) / (1920 * 1080); const areaScale = (width * height) / (1920 * 1080);
const targetCount = Math.round(BOIDS_PER_1920X1080 * areaScale); const targetCount = Math.round(BOIDS_PER_1920X1080 * areaScale);
const clampedCount = clamp(targetCount, MIN_INITIAL_BOIDS, MAX_INITIAL_BOIDS); const clampedCount = clamp(targetCount, MIN_INITIAL_BOIDS, MAX_INITIAL_BOIDS);
return Math.round(clampedCount / BOID_STEP) * BOID_STEP; return Math.round(clampedCount / BOID_STEP) * BOID_STEP;
} }
function syncBoidCountToViewport(width, height) { function syncBoidCountToViewport(width, height) {
const targetCount = getInitialBoidCount(width, height); const targetCount = getInitialBoidCount(width, height);
let currentCount = sim.get_boid_count(); let currentCount = sim.get_boid_count();
while (currentCount < targetCount) { while (currentCount < targetCount) {
sim.add_boid(); sim.add_boid();
currentCount = sim.get_boid_count(); currentCount = sim.get_boid_count();
} }
while (currentCount > targetCount) { while (currentCount > targetCount) {
sim.remove_boid(); sim.remove_boid();
currentCount = sim.get_boid_count(); currentCount = sim.get_boid_count();
} }
updateBoidCount(); updateBoidCount();
} }
function updateControlsCollapsedState(isCollapsed) { function updateControlsCollapsedState(isCollapsed) {
if (controls === null || controlsToggle === null) { if (controls === null || controlsToggle === null) {
return; return;
} }
controls.classList.toggle('collapsed', isCollapsed); controls.classList.toggle('collapsed', isCollapsed);
controls.setAttribute('aria-expanded', String(!isCollapsed)); controls.setAttribute('aria-expanded', String(!isCollapsed));
controlsToggle.setAttribute('aria-expanded', String(!isCollapsed)); controlsToggle.setAttribute('aria-expanded', String(!isCollapsed));
controlsToggle.setAttribute('aria-label', isCollapsed ? 'Expand controls' : 'Collapse controls'); controlsToggle.setAttribute(
controlsToggle.textContent = isCollapsed ? '' : ''; 'aria-label',
isCollapsed ? 'Expand controls' : 'Collapse controls'
);
controlsToggle.textContent = isCollapsed ? '' : '';
} }
function sizeCanvasToViewport() { function sizeCanvasToViewport() {
const dpr = window.devicePixelRatio || 1; const dpr = window.devicePixelRatio || 1;
const nextDisplayWidth = Math.max(1, Math.floor(canvas.clientWidth)); const nextDisplayWidth = Math.max(1, Math.floor(canvas.clientWidth));
const nextDisplayHeight = Math.max(1, Math.floor(canvas.clientHeight)); const nextDisplayHeight = Math.max(1, Math.floor(canvas.clientHeight));
const nextBufferWidth = Math.max(1, Math.round(nextDisplayWidth * dpr)); const nextBufferWidth = Math.max(1, Math.round(nextDisplayWidth * dpr));
const nextBufferHeight = Math.max(1, Math.round(nextDisplayHeight * dpr)); const nextBufferHeight = Math.max(1, Math.round(nextDisplayHeight * dpr));
if (canvas.width !== nextBufferWidth || canvas.height !== nextBufferHeight) { if (canvas.width !== nextBufferWidth || canvas.height !== nextBufferHeight) {
canvas.width = nextBufferWidth; canvas.width = nextBufferWidth;
canvas.height = nextBufferHeight; canvas.height = nextBufferHeight;
} }
displayWidth = nextDisplayWidth; displayWidth = nextDisplayWidth;
displayHeight = nextDisplayHeight; displayHeight = nextDisplayHeight;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
document.getElementById('canvasSize').textContent = `${displayWidth}x${displayHeight}`; document.getElementById('canvasSize').textContent =
`${displayWidth}x${displayHeight}`;
return { width: displayWidth, height: displayHeight }; return { width: displayWidth, height: displayHeight };
} }
function scheduleResize() { function scheduleResize() {
if (resizeAnimationFrame !== 0) { if (resizeAnimationFrame !== 0) {
return; return;
} }
resizeAnimationFrame = window.requestAnimationFrame(() => { resizeAnimationFrame = window.requestAnimationFrame(() => {
resizeAnimationFrame = 0; resizeAnimationFrame = 0;
const { width, height } = sizeCanvasToViewport(); const { width, height } = sizeCanvasToViewport();
if (sim !== null) { if (sim !== null) {
sim.resize(width, height); sim.resize(width, height);
syncBoidCountToViewport(width, height); syncBoidCountToViewport(width, height);
} }
}); });
} }
function setupResizeObserver() { function setupResizeObserver() {
controlsResizeObserver = new ResizeObserver(() => { controlsResizeObserver = new ResizeObserver(() => {
scheduleResize(); scheduleResize();
}); });
controlsResizeObserver.observe(document.getElementById('container')); controlsResizeObserver.observe(document.getElementById('container'));
controlsResizeObserver.observe(controls); controlsResizeObserver.observe(controls);
} }
async function run() { async function run() {
wasm = await init(); wasm = await init();
canvas = document.getElementById('canvas'); canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d'); ctx = canvas.getContext('2d');
controls = document.getElementById('controls'); controls = document.getElementById('controls');
controlsToggle = document.getElementById('controlsToggle'); controlsToggle = document.getElementById('controlsToggle');
updateControlsCollapsedState(false); updateControlsCollapsedState(false);
const { width, height } = sizeCanvasToViewport(); const { width, height } = sizeCanvasToViewport();
sim = new SimulationWasm(width, height, getInitialBoidCount(width, height)); sim = new SimulationWasm(width, height, getInitialBoidCount(width, height));
setupControls(); setupControls();
setupResizeObserver(); setupResizeObserver();
updateBoidCount(); updateBoidCount();
window.addEventListener('resize', scheduleResize); window.addEventListener('resize', scheduleResize);
animate(); animate();
} }
function setupControls() { function setupControls() {
const alignSlider = document.getElementById('alignSlider'); const alignSlider = document.getElementById('alignSlider');
const cohesionSlider = document.getElementById('cohesionSlider'); const cohesionSlider = document.getElementById('cohesionSlider');
const separationSlider = document.getElementById('separationSlider'); const separationSlider = document.getElementById('separationSlider');
const addBtn = document.getElementById('addBtn'); const addBtn = document.getElementById('addBtn');
const removeBtn = document.getElementById('removeBtn'); const removeBtn = document.getElementById('removeBtn');
controlsToggle.addEventListener('click', () => { controlsToggle.addEventListener('click', () => {
const isCollapsed = !controls.classList.contains('collapsed'); const isCollapsed = !controls.classList.contains('collapsed');
updateControlsCollapsedState(isCollapsed); updateControlsCollapsedState(isCollapsed);
scheduleResize(); scheduleResize();
}); });
alignSlider.addEventListener('input', (e) => { alignSlider.addEventListener('input', (e) => {
const value = Number.parseFloat(e.target.value); const value = Number.parseFloat(e.target.value);
sim.set_align_mult(value); sim.set_align_mult(value);
document.getElementById('alignValue').textContent = value.toFixed(2); document.getElementById('alignValue').textContent = value.toFixed(2);
}); });
cohesionSlider.addEventListener('input', (e) => { cohesionSlider.addEventListener('input', (e) => {
const value = Number.parseFloat(e.target.value); const value = Number.parseFloat(e.target.value);
sim.set_cohesion_mult(value); sim.set_cohesion_mult(value);
document.getElementById('cohesionValue').textContent = value.toFixed(2); document.getElementById('cohesionValue').textContent = value.toFixed(2);
}); });
separationSlider.addEventListener('input', (e) => { separationSlider.addEventListener('input', (e) => {
const value = Number.parseFloat(e.target.value); const value = Number.parseFloat(e.target.value);
sim.set_separation_mult(value); sim.set_separation_mult(value);
document.getElementById('separationValue').textContent = value.toFixed(2); document.getElementById('separationValue').textContent = value.toFixed(2);
}); });
addBtn.addEventListener('click', () => { addBtn.addEventListener('click', () => {
sim.add_boid(); sim.add_boid();
updateBoidCount(); updateBoidCount();
}); });
removeBtn.addEventListener('click', () => { removeBtn.addEventListener('click', () => {
sim.remove_boid(); sim.remove_boid();
updateBoidCount(); updateBoidCount();
}); });
} }
function updateBoidCount() { function updateBoidCount() {
document.getElementById('boidCount').textContent = sim.get_boid_count(); document.getElementById('boidCount').textContent = sim.get_boid_count();
} }
function getBoidView() { function getBoidView() {
const ptr = sim.boid_buffer_ptr(); const ptr = sim.boid_buffer_ptr();
const len = sim.boid_buffer_len(); const len = sim.boid_buffer_len();
return new Float32Array(wasm.memory.buffer, ptr, len); return new Float32Array(wasm.memory.buffer, ptr, len);
} }
function animate() { function animate() {
ctx.fillStyle = '#121212'; ctx.fillStyle = '#121212';
ctx.fillRect(0, 0, displayWidth, displayHeight); ctx.fillRect(0, 0, displayWidth, displayHeight);
sim.step(); sim.step();
const boidData = getBoidView(); const boidData = getBoidView();
const stride = sim.boid_buffer_stride(); const stride = sim.boid_buffer_stride();
for (let i = 0; i < boidData.length; i += stride) { for (let i = 0; i < boidData.length; i += stride) {
const x = boidData[i]; const x = boidData[i];
const y = boidData[i + 1]; const y = boidData[i + 1];
const vx = boidData[i + 2]; const vx = boidData[i + 2];
const vy = boidData[i + 3]; const vy = boidData[i + 3];
const r = boidData[i + 4]; const r = boidData[i + 4];
const g = boidData[i + 5]; const g = boidData[i + 5];
const b = boidData[i + 6]; const b = boidData[i + 6];
const a = boidData[i + 7]; const a = boidData[i + 7];
const speedSq = vx * vx + vy * vy; const speedSq = vx * vx + vy * vy;
let dx; let dx;
let dy; let dy;
if (speedSq > 1e-6) { if (speedSq > 1e-6) {
const invSpeed = 1 / Math.sqrt(speedSq); const invSpeed = 1 / Math.sqrt(speedSq);
dx = vx * invSpeed; dx = vx * invSpeed;
dy = vy * invSpeed; dy = vy * invSpeed;
} else { } else {
dx = 0; dx = 0;
dy = -1; dy = -1;
}
const size = 5;
const headMult = 3;
const px = -dy;
const py = dx;
const tipX = x + dx * size * headMult;
const tipY = y + dy * size * headMult;
const baseX = x - dx * size;
const baseY = y - dy * size;
const leftX = baseX + px * size;
const leftY = baseY + py * size;
const rightX = baseX - px * size;
const rightY = baseY - py * size;
ctx.strokeStyle = `rgba(${r},${g},${b},${a / 255})`;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(tipX, tipY);
ctx.lineTo(leftX, leftY);
ctx.lineTo(rightX, rightY);
ctx.closePath();
ctx.stroke();
} }
frameCount += 1; const size = 5;
const now = Date.now(); const headMult = 3;
if (now - lastFpsUpdate >= 1000) { const px = -dy;
document.getElementById('fps').textContent = frameCount; const py = dx;
frameCount = 0;
lastFpsUpdate = now;
}
requestAnimationFrame(animate); const tipX = x + dx * size * headMult;
const tipY = y + dy * size * headMult;
const baseX = x - dx * size;
const baseY = y - dy * size;
const leftX = baseX + px * size;
const leftY = baseY + py * size;
const rightX = baseX - px * size;
const rightY = baseY - py * size;
ctx.strokeStyle = `rgba(${r},${g},${b},${a / 255})`;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(tipX, tipY);
ctx.lineTo(leftX, leftY);
ctx.lineTo(rightX, rightY);
ctx.closePath();
ctx.stroke();
}
frameCount += 1;
const now = Date.now();
if (now - lastFpsUpdate >= 1000) {
document.getElementById('fps').textContent = frameCount;
frameCount = 0;
lastFpsUpdate = now;
}
requestAnimationFrame(animate);
} }
await run(); await run();
+146 -141
View File
@@ -1,239 +1,244 @@
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
:root { :root {
--panel-width: 280px; --panel-width: 280px;
--panel-collapsed-width: 44px; --panel-collapsed-width: 44px;
--panel-transition: 180ms ease; --panel-transition: 180ms ease;
} }
html, body { html,
width: 100%; body {
height: 100%; width: 100%;
height: 100%;
} }
body { body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; font-family:
background: #121212; -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
color: #d9d9d9; Cantarell, sans-serif;
overflow: hidden; background: #121212;
color: #d9d9d9;
overflow: hidden;
} }
#container { #container {
display: flex; display: flex;
width: 100vw; width: 100vw;
height: 100vh; height: 100vh;
} }
#canvas { #canvas {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
min-height: 0; min-height: 0;
display: block; display: block;
background: #121212; background: #121212;
} }
#controls { #controls {
width: var(--panel-width); width: var(--panel-width);
background: #1e1e1e; background: #1e1e1e;
border-left: 1px solid #333; border-left: 1px solid #333;
overflow: hidden; overflow: hidden;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
transition: width var(--panel-transition), min-width var(--panel-transition); transition:
min-width: var(--panel-width); width var(--panel-transition),
min-width var(--panel-transition);
min-width: var(--panel-width);
} }
#controls.collapsed { #controls.collapsed {
width: var(--panel-collapsed-width); width: var(--panel-collapsed-width);
min-width: var(--panel-collapsed-width); min-width: var(--panel-collapsed-width);
} }
#controlsHeader { #controlsHeader {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 12px;
padding: 14px 12px 12px 16px; padding: 14px 12px 12px 16px;
border-bottom: 1px solid #333; border-bottom: 1px solid #333;
} }
#controlsTitle { #controlsTitle {
font-size: 16px; font-size: 16px;
color: #d9d9d9; color: #d9d9d9;
white-space: nowrap; white-space: nowrap;
} }
#controlsToggle { #controlsToggle {
width: 32px; width: 32px;
min-width: 32px; min-width: 32px;
height: 32px; height: 32px;
padding: 0; padding: 0;
border: 1px solid #333; border: 1px solid #333;
background: #2a2a2a; background: #2a2a2a;
color: #d9d9d9; color: #d9d9d9;
border-radius: 4px; border-radius: 4px;
cursor: pointer; cursor: pointer;
font-size: 16px; font-size: 16px;
line-height: 1; line-height: 1;
transition: all 0.2s; transition: all 0.2s;
} }
#controlsToggle:hover { #controlsToggle:hover {
background: #3a3a3a; background: #3a3a3a;
border-color: #4a9eff; border-color: #4a9eff;
} }
#controlsBody { #controlsBody {
flex: 1; flex: 1;
padding: 20px; padding: 20px;
overflow-y: auto; overflow-y: auto;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 20px; gap: 20px;
opacity: 1; opacity: 1;
transition: opacity 120ms ease; transition: opacity 120ms ease;
} }
#controls.collapsed #controlsBody { #controls.collapsed #controlsBody {
opacity: 0; opacity: 0;
pointer-events: none; pointer-events: none;
} }
#controls.collapsed #controlsTitle { #controls.collapsed #controlsTitle {
display: none; display: none;
} }
.control-group { .control-group {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 10px; gap: 10px;
} }
label { label {
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.5px; letter-spacing: 0.5px;
color: #a0a0a0; color: #a0a0a0;
} }
input[type="range"] { input[type='range'] {
width: 100%; width: 100%;
height: 6px; height: 6px;
border-radius: 3px; border-radius: 3px;
background: #333; background: #333;
outline: none; outline: none;
-webkit-appearance: none; -webkit-appearance: none;
appearance: none; appearance: none;
} }
input[type="range"]::-webkit-slider-thumb { input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none; -webkit-appearance: none;
appearance: none; appearance: none;
width: 16px; width: 16px;
height: 16px; height: 16px;
border-radius: 50%; border-radius: 50%;
background: #4a9eff; background: #4a9eff;
cursor: pointer; cursor: pointer;
transition: background 0.2s; transition: background 0.2s;
} }
input[type="range"]::-webkit-slider-thumb:hover { input[type='range']::-webkit-slider-thumb:hover {
background: #2196f3; background: #2196f3;
} }
input[type="range"]::-moz-range-thumb { input[type='range']::-moz-range-thumb {
width: 16px; width: 16px;
height: 16px; height: 16px;
border-radius: 50%; border-radius: 50%;
background: #4a9eff; background: #4a9eff;
cursor: pointer; cursor: pointer;
border: none; border: none;
transition: background 0.2s; transition: background 0.2s;
} }
input[type="range"]::-moz-range-thumb:hover { input[type='range']::-moz-range-thumb:hover {
background: #2196f3; background: #2196f3;
} }
.value-display { .value-display {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
font-size: 14px; font-size: 14px;
} }
.value-display strong { .value-display strong {
color: #4a9eff; color: #4a9eff;
font-weight: 600; font-weight: 600;
} }
.button-group { .button-group {
display: flex; display: flex;
gap: 10px; gap: 10px;
} }
button { button {
flex: 1; flex: 1;
padding: 10px 16px; padding: 10px 16px;
border: 1px solid #333; border: 1px solid #333;
background: #2a2a2a; background: #2a2a2a;
color: #d9d9d9; color: #d9d9d9;
border-radius: 4px; border-radius: 4px;
cursor: pointer; cursor: pointer;
font-size: 13px; font-size: 13px;
font-weight: 500; font-weight: 500;
transition: all 0.2s; transition: all 0.2s;
} }
button:hover { button:hover {
background: #3a3a3a; background: #3a3a3a;
border-color: #4a9eff; border-color: #4a9eff;
} }
button:active { button:active {
background: #1a1a1a; background: #1a1a1a;
} }
.stats { .stats {
padding: 12px; padding: 12px;
background: #252525; background: #252525;
border-radius: 4px; border-radius: 4px;
border-left: 3px solid #4a9eff; border-left: 3px solid #4a9eff;
font-size: 13px; font-size: 13px;
} }
.stat-item { .stat-item {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
margin-bottom: 6px; margin-bottom: 6px;
} }
.stat-item:last-child { .stat-item:last-child {
margin-bottom: 0; margin-bottom: 0;
} }
.stat-label { .stat-label {
color: #a0a0a0; color: #a0a0a0;
} }
.stat-value { .stat-value {
color: #4a9eff; color: #4a9eff;
font-weight: 600; font-weight: 600;
font-family: 'Courier New', monospace; font-family: 'Courier New', monospace;
} }
#fps { #fps {
color: #4a9eff; color: #4a9eff;
font-size: 13px; font-size: 13px;
font-family: 'Courier New', monospace; font-family: 'Courier New', monospace;
} }
.divider { .divider {
height: 1px; height: 1px;
background: #333; background: #333;
} }
+120 -120
View File
@@ -1,120 +1,120 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Fourier Series — Epicycles (p5.js)</title> <title>Fourier Series — Epicycles (p5.js)</title>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>
<style> <style>
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
background: #fafafa; background: #fafafa;
margin: 20px; margin: 20px;
text-align: center; text-align: center;
} }
#container { #container {
max-width: 900px; max-width: 900px;
margin: 0 auto; margin: 0 auto;
} }
h1, h1,
h2, h2,
p { p {
margin: 10px 0; margin: 10px 0;
} }
input[type="range"] { input[type='range'] {
display: block; display: block;
margin: 10px auto 0; margin: 10px auto 0;
width: 260px; width: 260px;
} }
</style> </style>
</head> </head>
<body> <body>
<div id="container"> <div id="container">
<h1>Fourier Series</h1> <h1>Fourier Series</h1>
<p> <p>
This interactive sketch visualizes a Fourier series using epicycles. This interactive sketch visualizes a Fourier series using epicycles.
Each circle represents an odd harmonic; as you add more epicycles with Each circle represents an odd harmonic; as you add more epicycles with
the slider, the path on the right converges toward a square wave. The the slider, the path on the right converges toward a square wave. The
rotating vectors sum to a point whose vertical position is traced over rotating vectors sum to a point whose vertical position is traced over
time. time.
</p> </p>
<div class="canvas-holder"></div> <div class="canvas-holder"></div>
</div> </div>
<script> <script>
class dot { class dot {
constructor(x, y) { constructor(x, y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
} }
class circle { class circle {
constructor(cx, cy, r, a) { constructor(cx, cy, r, a) {
this.cx = cx; this.cx = cx;
this.cy = cy; this.cy = cy;
this.r = r; this.r = r;
this.a = a; this.a = a;
} }
} }
let time = 0; let time = 0;
let wave = []; let wave = [];
let slider; let slider;
function setup() { function setup() {
createCanvas(900, 800); createCanvas(900, 800);
slider = createSlider(1, 50, 5); slider = createSlider(1, 50, 5);
} }
function draw() { function draw() {
background(41); background(41);
translate(250, height / 2); translate(250, height / 2);
let x = 0; let x = 0;
let y = 0; let y = 0;
for (let i = 0; i < slider.value(); i++) { for (let i = 0; i < slider.value(); i++) {
let prevx = x; let prevx = x;
let prevy = y; let prevy = y;
let n = i * 2 + 1; let n = i * 2 + 1;
let radius = 100 * (4 / (n * PI)); let radius = 100 * (4 / (n * PI));
x += radius * cos(n * time); x += radius * cos(n * time);
y += radius * sin(n * time); y += radius * sin(n * time);
stroke(255, 100); stroke(255, 100);
noFill(); noFill();
ellipse(prevx, prevy, radius * 2); ellipse(prevx, prevy, radius * 2);
//fill(255); //fill(255);
stroke(255); stroke(255);
line(prevx, prevy, x, y); line(prevx, prevy, x, y);
//ellipse(x, y, 8); //ellipse(x, y, 8);
} }
wave.unshift(y); wave.unshift(y);
translate(200, 0); translate(200, 0);
line(x - 200, y, 0, wave[0]); line(x - 200, y, 0, wave[0]);
beginShape(); beginShape();
noFill(); noFill();
for (let i = 0; i < wave.length; i++) { for (let i = 0; i < wave.length; i++) {
vertex(i, wave[i]); vertex(i, wave[i]);
} }
endShape(); endShape();
time += 0.02; time += 0.02;
if (wave.length > 450) { if (wave.length > 450) {
wave.pop(); wave.pop();
} }
} }
</script> </script>
</body> </body>
</html> </html>
+247 -247
View File
@@ -1,247 +1,247 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta <meta
name="viewport" name="viewport"
width="device-width," width="device-width,"
initial-scale="1.0," initial-scale="1.0,"
maximum-scale="1.0," maximum-scale="1.0,"
user-scalable="0" user-scalable="0"
/> />
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>
<style> <style>
body { body {
font-family: font-family:
system-ui, system-ui,
-apple-system, -apple-system,
Segoe UI, Segoe UI,
Roboto, Roboto,
Helvetica, Helvetica,
Arial, Arial,
sans-serif; sans-serif;
margin: 16px; margin: 16px;
background: #fafafa; background: #fafafa;
color: #222; color: #222;
} }
.intro { .intro {
max-width: 900px; max-width: 900px;
margin: 0 auto 18px; margin: 0 auto 18px;
padding: 0 12px; padding: 0 12px;
} }
.intro h1 { .intro h1 {
font-size: 1.5rem; font-size: 1.5rem;
margin: 0 0 6px; margin: 0 0 6px;
} }
.intro p { .intro p {
margin: 4px 0 10px; margin: 4px 0 10px;
line-height: 1.45; line-height: 1.45;
} }
canvas { canvas {
display: block; display: block;
margin: 0 auto; margin: 0 auto;
} }
</style> </style>
</head> </head>
<body> <body>
<div class="intro"> <div class="intro">
<h1>Marching Squares Field Visualizer</h1> <h1>Marching Squares Field Visualizer</h1>
<p> <p>
This sketch uses the <strong>Marching Squares</strong> algorithm to This sketch uses the <strong>Marching Squares</strong> algorithm to
generate and display contour boundaries on a grid. Each cell is either generate and display contour boundaries on a grid. Each cell is either
active or inactive, the algorithm determines the correct line or active or inactive, the algorithm determines the correct line or
triangle to draw based on the surrounding corners. triangle to draw based on the surrounding corners.
</p> </p>
<p><b>Left-click</b> toggles a cell between the two states.</p> <p><b>Left-click</b> toggles a cell between the two states.</p>
<p> <p>
<b>Rightclick</b> shows or hides the contour lines produced by the <b>Rightclick</b> shows or hides the contour lines produced by the
algorithm. algorithm.
</p> </p>
</div> </div>
<script> <script>
var reso = 50; var reso = 50;
var cols, rows; var cols, rows;
var field = []; var field = [];
var draw_lines = true; var draw_lines = true;
function setup() { function setup() {
createCanvas(800, 600); createCanvas(800, 600);
cols = width / reso + 1; cols = width / reso + 1;
rows = height / reso + 1; rows = height / reso + 1;
for (var i = 0; i < cols * rows; i++) field[i] = Math.floor(random(2)); for (var i = 0; i < cols * rows; i++) field[i] = Math.floor(random(2));
} }
function draw() { function draw() {
background(100); background(100);
const cBlue = color(55, 120, 232); const cBlue = color(55, 120, 232);
const cGreen = color(146, 232, 55); const cGreen = color(146, 232, 55);
for (var i = 0; i < cols * rows; i++) { for (var i = 0; i < cols * rows; i++) {
let x = i % cols; let x = i % cols;
let y = Math.floor(i / cols); let y = Math.floor(i / cols);
let c = field[i] ? cBlue : cGreen; let c = field[i] ? cBlue : cGreen;
fill(c); fill(c);
rect(x * reso - reso * 0.5, y * reso - reso * 0.5, reso, reso); rect(x * reso - reso * 0.5, y * reso - reso * 0.5, reso, reso);
} }
for (var i = 0; i < cols * rows; i++) { for (var i = 0; i < cols * rows; i++) {
if (i + cols + 1 > cols * rows) { if (i + cols + 1 > cols * rows) {
break; break;
} }
var x = (i % cols) * reso; var x = (i % cols) * reso;
var y = Math.floor(i / cols) * reso; var y = Math.floor(i / cols) * reso;
const a = [x + reso * 0.5, y]; const a = [x + reso * 0.5, y];
const b = [x + reso, y + reso * 0.5]; const b = [x + reso, y + reso * 0.5];
const c = [x + reso * 0.5, y + reso]; const c = [x + reso * 0.5, y + reso];
const d = [x, y + reso * 0.5]; const d = [x, y + reso * 0.5];
var s = getState( var s = getState(
field[i], field[i],
field[i + 1], field[i + 1],
field[i + cols + 1], field[i + cols + 1],
field[i + cols], field[i + cols]
); );
noStroke(); noStroke();
switch (s) { switch (s) {
case 1: case 1:
fill(cGreen); fill(cGreen);
triangle(x + reso * 0.5, y + reso * 0.5, c[0], c[1], d[0], d[1]); triangle(x + reso * 0.5, y + reso * 0.5, c[0], c[1], d[0], d[1]);
break; break;
case 14: case 14:
fill(cBlue); fill(cBlue);
triangle(x + reso * 0.5, y + reso * 0.5, c[0], c[1], d[0], d[1]); triangle(x + reso * 0.5, y + reso * 0.5, c[0], c[1], d[0], d[1]);
break; break;
case 2: case 2:
fill(cGreen); fill(cGreen);
triangle(x + reso * 0.5, y + reso * 0.5, b[0], b[1], c[0], c[1]); triangle(x + reso * 0.5, y + reso * 0.5, b[0], b[1], c[0], c[1]);
break; break;
case 13: case 13:
fill(cBlue); fill(cBlue);
triangle(x + reso * 0.5, y + reso * 0.5, b[0], b[1], c[0], c[1]); triangle(x + reso * 0.5, y + reso * 0.5, b[0], b[1], c[0], c[1]);
break; break;
case 3: case 3:
fill(cBlue); fill(cBlue);
rect(d[0], d[1], reso, reso * 0.5); rect(d[0], d[1], reso, reso * 0.5);
break; break;
case 12: case 12:
fill(cGreen); fill(cGreen);
rect(d[0], d[1], reso, reso * 0.5); rect(d[0], d[1], reso, reso * 0.5);
break; break;
case 4: case 4:
fill(cGreen); fill(cGreen);
triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], b[0], b[1]); triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], b[0], b[1]);
break; break;
case 11: case 11:
fill(cBlue); fill(cBlue);
triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], b[0], b[1]); triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], b[0], b[1]);
break; break;
case 5: case 5:
fill(cBlue); fill(cBlue);
triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], d[0], d[1]); triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], d[0], d[1]);
triangle(x + reso * 0.5, y + reso * 0.5, b[0], b[1], c[0], c[1]); triangle(x + reso * 0.5, y + reso * 0.5, b[0], b[1], c[0], c[1]);
break; break;
case 6: case 6:
fill(cBlue); fill(cBlue);
rect(a[0], a[1], reso * 0.5, reso); rect(a[0], a[1], reso * 0.5, reso);
break; break;
case 9: case 9:
fill(cGreen); fill(cGreen);
rect(a[0], a[1], reso * 0.5, reso); rect(a[0], a[1], reso * 0.5, reso);
break; break;
case 7: case 7:
fill(cBlue); fill(cBlue);
triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], d[0], d[1]); triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], d[0], d[1]);
break; break;
case 8: case 8:
fill(cGreen); fill(cGreen);
triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], d[0], d[1]); triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], d[0], d[1]);
break; break;
case 10: case 10:
fill(cBlue); fill(cBlue);
triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], b[0], b[1]); triangle(x + reso * 0.5, y + reso * 0.5, a[0], a[1], b[0], b[1]);
triangle(x + reso * 0.5, y + reso * 0.5, c[0], c[1], d[0], d[1]); triangle(x + reso * 0.5, y + reso * 0.5, c[0], c[1], d[0], d[1]);
break; break;
default: default:
break; break;
} }
if (draw_lines) { if (draw_lines) {
drawLines(s, a, b, c, d); drawLines(s, a, b, c, d);
} }
} }
} }
function getState(a, b, c, d) { function getState(a, b, c, d) {
return d * 1 + c * 2 + b * 4 + a * 8; return d * 1 + c * 2 + b * 4 + a * 8;
} }
function drawLines(s, a, b, c, d) { function drawLines(s, a, b, c, d) {
stroke(232, 229, 55); stroke(232, 229, 55);
strokeWeight(reso * 0.1); strokeWeight(reso * 0.1);
switch (s) { switch (s) {
case 1: case 1:
case 14: case 14:
line(c[0], c[1], d[0], d[1]); line(c[0], c[1], d[0], d[1]);
break; break;
case 2: case 2:
case 13: case 13:
line(b[0], b[1], c[0], c[1]); line(b[0], b[1], c[0], c[1]);
break; break;
case 3: case 3:
case 12: case 12:
line(b[0], b[1], d[0], d[1]); line(b[0], b[1], d[0], d[1]);
break; break;
case 4: case 4:
case 11: case 11:
line(a[0], a[1], b[0], b[1]); line(a[0], a[1], b[0], b[1]);
break; break;
case 5: case 5:
line(a[0], a[1], d[0], d[1]); line(a[0], a[1], d[0], d[1]);
line(b[0], b[1], c[0], c[1]); line(b[0], b[1], c[0], c[1]);
break; break;
case 6: case 6:
case 9: case 9:
line(a[0], a[1], c[0], c[1]); line(a[0], a[1], c[0], c[1]);
break; break;
case 7: case 7:
case 8: case 8:
line(a[0], a[1], d[0], d[1]); line(a[0], a[1], d[0], d[1]);
break; break;
case 10: case 10:
line(a[0], a[1], b[0], b[1]); line(a[0], a[1], b[0], b[1]);
line(c[0], c[1], d[0], d[1]); line(c[0], c[1], d[0], d[1]);
break; break;
default: default:
break; break;
} }
noStroke(); noStroke();
} }
function mousePressed() { function mousePressed() {
if (mouseButton == LEFT) { if (mouseButton == LEFT) {
var x = Math.floor((mouseX + 0.5 * reso) / reso); var x = Math.floor((mouseX + 0.5 * reso) / reso);
var y = Math.floor((mouseY + 0.5 * reso) / reso); var y = Math.floor((mouseY + 0.5 * reso) / reso);
var i = Math.floor(y * cols + x); var i = Math.floor(y * cols + x);
field[i] = (field[i] + 1) % 2; field[i] = (field[i] + 1) % 2;
} else if (mouseButton == RIGHT) { } else if (mouseButton == RIGHT) {
draw_lines = !draw_lines; draw_lines = !draw_lines;
} }
} }
</script> </script>
</body> </body>
</html> </html>
+18 -20
View File
@@ -4,13 +4,13 @@ function Cell(i, j) {
this.walls = [true, true, true, true]; this.walls = [true, true, true, true];
this.visited = false; this.visited = false;
this.checkNeighbors = function() { this.checkNeighbors = function () {
var neighbors = []; var neighbors = [];
var top = grid[index(i, j -1)]; var top = grid[index(i, j - 1)];
var right = grid[index(i+1, j)]; var right = grid[index(i + 1, j)];
var bottom = grid[index(i, j+1)]; var bottom = grid[index(i, j + 1)];
var left = grid[index(i-1, j)]; var left = grid[index(i - 1, j)];
if (top && !top.visited) { if (top && !top.visited) {
neighbors.push(top); neighbors.push(top);
@@ -31,32 +31,30 @@ function Cell(i, j) {
} else { } else {
return undefined; return undefined;
} }
};
this.highlight = function () {
} var x = this.i * w;
this.highlight = function() { var y = this.j * w;
var x = this.i*w;
var y = this.j*w;
noStroke(); noStroke();
fill(252, 106, 2, 100); fill(252, 106, 2, 100);
rect(x, y, w, w); rect(x, y, w, w);
} };
this.show = function() { this.show = function () {
var x = this.i*w; var x = this.i * w;
var y = this.j*w; var y = this.j * w;
stroke(0); stroke(0);
if (this.walls[0]) { if (this.walls[0]) {
line(x , y , x + w, y); line(x, y, x + w, y);
} }
if (this.walls[1]) { if (this.walls[1]) {
line(x + w, y , x + w, y + w); line(x + w, y, x + w, y + w);
} }
if (this.walls[2]) { if (this.walls[2]) {
line(x + w, y + w, x , y + w); line(x + w, y + w, x, y + w);
} }
if (this.walls[3]) { if (this.walls[3]) {
line(x , y + w, x , y); line(x, y + w, x, y);
} }
if (this.visited) { if (this.visited) {
@@ -64,5 +62,5 @@ function Cell(i, j) {
fill(242, 255, 28, 125); fill(242, 255, 28, 125);
rect(x, y, w, w); rect(x, y, w, w);
} }
} };
} }
+108 -113
View File
@@ -4,134 +4,129 @@ var grid = [];
var current; var current;
var stack = []; var stack = [];
function setup(){ function setup() {
createCanvas(800, 800); createCanvas(800, 800);
cols = floor(width/w) cols = floor(width / w);
rows = floor(height/w) rows = floor(height / w);
//frameRate(6); //frameRate(6);
for (var j = 0; j < rows; j++){ for (var j = 0; j < rows; j++) {
for (var i = 0; i < cols; i++){ for (var i = 0; i < cols; i++) {
var cell = new Cell(i,j); var cell = new Cell(i, j);
grid.push(cell); grid.push(cell);
}
} }
current = grid[0]; }
current = grid[0];
} }
function draw(){ function draw() {
background(150); background(150);
for (var i = 0; i < grid.length; i++){ for (var i = 0; i < grid.length; i++) {
grid[i].show(); grid[i].show();
}
current.visited = true;
current.highlight();
var next = current.checkNeighbors();
if (next) {
next.visited = true;
stack.push(current);
} removeWalls(current, next);
current.visited = true;
current.highlight();
var next = current.checkNeighbors();
if (next) {
next.visited = true;
stack.push(current);
removeWalls(current, next);
current = next;
} else if (stack.length > 0){
current = stack.pop();
}
current = next;
} else if (stack.length > 0) {
current = stack.pop();
}
} }
function index(i, j) {
if (i < 0 || j < 0 || i > cols - 1 || j > rows - 1) {
return -1;
}
function index(i, j){ return i + j * cols;
if(i < 0 || j < 0 || i > cols-1 || j > rows-1){
return -1
}
return i + j * cols;
} }
function cell(i, j){ function cell(i, j) {
this.i = i; this.i = i;
this.j = j; this.j = j;
this.walls = [true, true, true, true]; this.walls = [true, true, true, true];
this.visited = false; this.visited = false;
this.checkNeighbors = function(){ this.checkNeighbors = function () {
var neighbors = []; var neighbors = [];
var top = grid[index(i, j-1)];
var right = grid[index(i+1, j)];
var bottom = grid[index(i, j + 1)];
var left = grid[index(i-1, j)];
if (top && !top.visited){ var top = grid[index(i, j - 1)];
neighbors.push(top); var right = grid[index(i + 1, j)];
} var bottom = grid[index(i, j + 1)];
if (right && !right.visited){ var left = grid[index(i - 1, j)];
neighbors.push(right);
}
if (bottom && !bottom.visited){
neighbors.push(bottom);
}
if (left && !left.visited){
neighbors.push(left);
}
if (neighbors.length > 0){
var r = floor(random(0, neighbors.length));
return neighbor[r];
} else {
return undefined;
}
this.highlight = function(){
var x = this.i*w;
var y = this.j*w;
noStroke();
fill(0, 0, 255, 125);
rect(x,y,w,w);
}
}
this.show = function(){ if (top && !top.visited) {
var x = this.i*w; neighbors.push(top);
var y = this.j*w; }
stroke(255); if (right && !right.visited) {
if (this.walls[0]){ neighbors.push(right);
line(x,y,x+w,y); }
} if (bottom && !bottom.visited) {
if (this.walls[1]){ neighbors.push(bottom);
line(x+w,y,x+w,y+w); }
} if (left && !left.visited) {
if (this.walls[2]){ neighbors.push(left);
line(x+w,y+w,x,y+w); }
} if (neighbors.length > 0) {
if (this.walls[3]){ var r = floor(random(0, neighbors.length));
line(x,y+w,x,y); return neighbor[r];
} } else {
if (this.visited){ return undefined;
fill(255, 0, 255, 125); }
rect(x,y,w,w); this.highlight = function () {
} var x = this.i * w;
} var y = this.j * w;
noStroke();
fill(0, 0, 255, 125);
rect(x, y, w, w);
};
};
this.show = function () {
var x = this.i * w;
var y = this.j * w;
stroke(255);
if (this.walls[0]) {
line(x, y, x + w, y);
}
if (this.walls[1]) {
line(x + w, y, x + w, y + w);
}
if (this.walls[2]) {
line(x + w, y + w, x, y + w);
}
if (this.walls[3]) {
line(x, y + w, x, y);
}
if (this.visited) {
fill(255, 0, 255, 125);
rect(x, y, w, w);
}
};
} }
function removeWalls(a, b){ function removeWalls(a, b) {
var x = a.i - b.i; var x = a.i - b.i;
if (x === 1){ if (x === 1) {
a.walls[3] = false; a.walls[3] = false;
b.walls[1] = false; b.walls[1] = false;
} else if (x === -1){ } else if (x === -1) {
a.walls[1] = false; a.walls[1] = false;
b.walls[3] = false; b.walls[3] = false;
} }
var y = a.j - b.j;
if (y === 1){
a.walls[0] = false;
b.walls[2] = false;
} else if (y === -1){
a.walls[2] = false;
b.walls[0] = false;
}
var y = a.j - b.j;
if (y === 1) {
a.walls[0] = false;
b.walls[2] = false;
} else if (y === -1) {
a.walls[2] = false;
b.walls[0] = false;
}
} }
+9640 -8215
View File
File diff suppressed because it is too large Load Diff
+63 -55
View File
@@ -6,73 +6,81 @@ const fullscreenButton = document.getElementById('fullscreenButton');
outputElement.value = ''; outputElement.value = '';
canvasElement.addEventListener('webglcontextlost', (event) => { canvasElement.addEventListener(
'webglcontextlost',
(event) => {
event.preventDefault(); event.preventDefault();
setStatus('WebGL context lost. Reload the page to restart the simulation.'); setStatus('WebGL context lost. Reload the page to restart the simulation.');
}, false); },
false
);
function setStatus(text) { function setStatus(text) {
if (!setStatus.last) { if (!setStatus.last) {
setStatus.last = { time: Date.now(), text: '' }; setStatus.last = { time: Date.now(), text: '' };
} }
if (text === setStatus.last.text) { if (text === setStatus.last.text) {
return; return;
} }
const match = text && text.match(/([^(]+)\((\d+(?:\.\d+)?)\/(\d+)\)/); const match = text && text.match(/([^(]+)\((\d+(?:\.\d+)?)\/(\d+)\)/);
const now = Date.now(); const now = Date.now();
if (match && now - setStatus.last.time < 30) { if (match && now - setStatus.last.time < 30) {
return; return;
} }
setStatus.last.time = now; setStatus.last.time = now;
setStatus.last.text = text; setStatus.last.text = text;
if (match) { if (match) {
statusElement.textContent = match[1].trim(); statusElement.textContent = match[1].trim();
progressElement.value = Number.parseInt(match[2], 10) * 100; progressElement.value = Number.parseInt(match[2], 10) * 100;
progressElement.max = Number.parseInt(match[3], 10) * 100; progressElement.max = Number.parseInt(match[3], 10) * 100;
progressElement.hidden = false; progressElement.hidden = false;
} else { } else {
statusElement.textContent = text || ''; statusElement.textContent = text || '';
progressElement.hidden = !text; progressElement.hidden = !text;
if (!text) { if (!text) {
progressElement.removeAttribute('value'); progressElement.removeAttribute('value');
}
} }
}
} }
var Module = { var Module = {
canvas: canvasElement, canvas: canvasElement,
print: (...args) => { print: (...args) => {
console.log(...args); console.log(...args);
outputElement.value += `${args.join(' ')}\n`; outputElement.value += `${args.join(' ')}\n`;
outputElement.scrollTop = outputElement.scrollHeight; outputElement.scrollTop = outputElement.scrollHeight;
}, },
printErr: (...args) => { printErr: (...args) => {
console.error(...args); console.error(...args);
outputElement.value += `[err] ${args.join(' ')}\n`; outputElement.value += `[err] ${args.join(' ')}\n`;
outputElement.scrollTop = outputElement.scrollHeight; outputElement.scrollTop = outputElement.scrollHeight;
}, },
setStatus, setStatus,
totalDependencies: 0, totalDependencies: 0,
monitorRunDependencies(left) { monitorRunDependencies(left) {
this.totalDependencies = Math.max(this.totalDependencies, left); this.totalDependencies = Math.max(this.totalDependencies, left);
setStatus(left ? `Preparing... (${this.totalDependencies - left}/${this.totalDependencies})` : 'Running...'); setStatus(
if (!left) { left
setTimeout(() => setStatus(''), 250); ? `Preparing... (${this.totalDependencies - left}/${this.totalDependencies})`
} : 'Running...'
);
if (!left) {
setTimeout(() => setStatus(''), 250);
} }
},
}; };
fullscreenButton.addEventListener('click', () => { fullscreenButton.addEventListener('click', () => {
if (typeof Module.requestFullscreen === 'function') { if (typeof Module.requestFullscreen === 'function') {
Module.requestFullscreen(false, false); Module.requestFullscreen(false, false);
} }
}); });
globalThis.onerror = () => { globalThis.onerror = () => {
setStatus('Exception thrown, see JavaScript console'); setStatus('Exception thrown, see JavaScript console');
}; };
+1 -1
View File
@@ -162,7 +162,7 @@ textarea {
margin-top: 10px; margin-top: 10px;
padding: 10px; padding: 10px;
border: 1px solid #ddd; border: 1px solid #ddd;
font-family: "Courier New", monospace; font-family: 'Courier New', monospace;
font-size: 0.9rem; font-size: 0.9rem;
resize: vertical; resize: vertical;
background: white; background: white;
+5 -5
View File
@@ -44,7 +44,7 @@
var circleCount, total; var circleCount, total;
var x, y; var x, y;
var calcPI; var calcPI;
var DisplayPI = "a"; var DisplayPI = 'a';
const PI = 3.1415926535; const PI = 3.1415926535;
var BestPI = 50; var BestPI = 50;
@@ -84,15 +84,15 @@
DisplayPI = calcPI; DisplayPI = calcPI;
BestPI = calcPI; BestPI = calcPI;
var PIDisplay = document.getElementById("PIbox"); var PIDisplay = document.getElementById('PIbox');
PIDisplay.innerHTML = DisplayPI; PIDisplay.innerHTML = DisplayPI;
var ErrorDisplay = document.getElementById("percentage"); var ErrorDisplay = document.getElementById('percentage');
var DisplayError = "a"; var DisplayError = 'a';
var Perror = (calcPI - PI) / PI; var Perror = (calcPI - PI) / PI;
Perror *= 100; Perror *= 100;
DisplayError = nfc(Perror, 10); DisplayError = nfc(Perror, 10);
ErrorDisplay.innerHTML = DisplayError + "%"; ErrorDisplay.innerHTML = DisplayError + '%';
} }
} }
</script> </script>
View File
View File
+64 -53
View File
@@ -7,83 +7,94 @@ const resizeCheckbox = document.getElementById('resize');
const pointerLockCheckbox = document.getElementById('pointerLock'); const pointerLockCheckbox = document.getElementById('pointerLock');
if (outputElement) { if (outputElement) {
outputElement.value = ''; outputElement.value = '';
} }
canvasElement.addEventListener('webglcontextlost', (event) => { canvasElement.addEventListener(
'webglcontextlost',
(event) => {
event.preventDefault(); event.preventDefault();
setStatus('WebGL context lost. Reload the page to restart the game.'); setStatus('WebGL context lost. Reload the page to restart the game.');
}, false); },
false
);
function setStatus(text) { function setStatus(text) {
if (!setStatus.last) { if (!setStatus.last) {
setStatus.last = { time: Date.now(), text: '' }; setStatus.last = { time: Date.now(), text: '' };
} }
if (text === setStatus.last.text) { if (text === setStatus.last.text) {
return; return;
} }
const match = text?.match(/([^(]+)\((\d+(?:\.\d+)?)\/(\d+)\)/); const match = text?.match(/([^(]+)\((\d+(?:\.\d+)?)\/(\d+)\)/);
const now = Date.now(); const now = Date.now();
if (match && now - setStatus.last.time < 30) { if (match && now - setStatus.last.time < 30) {
return; return;
} }
setStatus.last.time = now; setStatus.last.time = now;
setStatus.last.text = text; setStatus.last.text = text;
if (match) { if (match) {
statusElement.textContent = match[1].trim(); statusElement.textContent = match[1].trim();
progressElement.value = Number.parseInt(match[2], 10) * 100; progressElement.value = Number.parseInt(match[2], 10) * 100;
progressElement.max = Number.parseInt(match[3], 10) * 100; progressElement.max = Number.parseInt(match[3], 10) * 100;
progressElement.hidden = false; progressElement.hidden = false;
} else { } else {
statusElement.textContent = text || ''; statusElement.textContent = text || '';
progressElement.hidden = !text; progressElement.hidden = !text;
if (!text) { if (!text) {
progressElement.removeAttribute('value'); progressElement.removeAttribute('value');
}
} }
}
} }
globalThis.Module = globalThis.Module || {}; globalThis.Module = globalThis.Module || {};
globalThis.Module.canvas = canvasElement; globalThis.Module.canvas = canvasElement;
globalThis.Module.print = (...args) => { globalThis.Module.print = (...args) => {
console.log(...args); console.log(...args);
if (!outputElement) { if (!outputElement) {
return; return;
} }
outputElement.value += `${args.join(' ')}\n`; outputElement.value += `${args.join(' ')}\n`;
outputElement.scrollTop = outputElement.scrollHeight; outputElement.scrollTop = outputElement.scrollHeight;
}; };
globalThis.Module.printErr = (...args) => { globalThis.Module.printErr = (...args) => {
console.error(...args); console.error(...args);
if (!outputElement) { if (!outputElement) {
return; return;
} }
outputElement.value += `[err] ${args.join(' ')}\n`; outputElement.value += `[err] ${args.join(' ')}\n`;
outputElement.scrollTop = outputElement.scrollHeight; outputElement.scrollTop = outputElement.scrollHeight;
}; };
globalThis.Module.setStatus = setStatus; globalThis.Module.setStatus = setStatus;
globalThis.Module.totalDependencies = 0; globalThis.Module.totalDependencies = 0;
globalThis.Module.monitorRunDependencies = function (left) { globalThis.Module.monitorRunDependencies = function (left) {
this.totalDependencies = Math.max(this.totalDependencies, left); this.totalDependencies = Math.max(this.totalDependencies, left);
setStatus(left ? `Preparing... (${this.totalDependencies - left}/${this.totalDependencies})` : 'Running...'); setStatus(
if (!left) { left
setTimeout(() => setStatus(''), 250); ? `Preparing... (${this.totalDependencies - left}/${this.totalDependencies})`
} : 'Running...'
);
if (!left) {
setTimeout(() => setStatus(''), 250);
}
}; };
fullscreenButton.addEventListener('click', () => { fullscreenButton.addEventListener('click', () => {
if (typeof globalThis.Module.requestFullscreen === 'function') { if (typeof globalThis.Module.requestFullscreen === 'function') {
globalThis.Module.requestFullscreen(pointerLockCheckbox.checked, resizeCheckbox.checked); globalThis.Module.requestFullscreen(
} pointerLockCheckbox.checked,
resizeCheckbox.checked
);
}
}); });
setStatus('Downloading...'); setStatus('Downloading...');
globalThis.onerror = () => { globalThis.onerror = () => {
setStatus('Exception thrown, see JavaScript console'); setStatus('Exception thrown, see JavaScript console');
}; };
+148 -148
View File
@@ -1,41 +1,41 @@
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
:root { :root {
--bg: #fffdf7; --bg: #fffdf7;
--text: #0f172a; --text: #0f172a;
--muted: #475569; --muted: #475569;
--border: #0f172a; --border: #0f172a;
--panel: #dff4ff; --panel: #dff4ff;
--panel-2: #ffffff; --panel-2: #ffffff;
--accent: #00a6fb; --accent: #00a6fb;
--accent-strong: #0077b6; --accent-strong: #0077b6;
--highlight: #ffd23f; --highlight: #ffd23f;
--danger: #ff5d73; --danger: #ff5d73;
} }
body { body {
background: var(--bg); background: var(--bg);
color: var(--text); color: var(--text);
font-family: Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
font-size: 18px; font-size: 18px;
line-height: 1.6; line-height: 1.6;
padding: 20px; padding: 20px;
} }
.container { .container {
max-width: 920px; max-width: 920px;
margin: 0 auto; margin: 0 auto;
} }
header { header {
text-align: center; text-align: center;
margin-bottom: 30px; margin-bottom: 30px;
border-bottom: 3px solid var(--border); border-bottom: 3px solid var(--border);
padding-bottom: 20px; padding-bottom: 20px;
} }
h1, h1,
@@ -44,216 +44,216 @@ h3,
button, button,
summary, summary,
.back-button { .back-button {
font-family: "Arial Black", Arial, Helvetica, sans-serif; font-family: 'Arial Black', Arial, Helvetica, sans-serif;
font-weight: 900; font-weight: 900;
letter-spacing: 0.02em; letter-spacing: 0.02em;
} }
h1 { h1 {
font-size: clamp(2.4rem, 5vw, 3.6rem); font-size: clamp(2.4rem, 5vw, 3.6rem);
margin-bottom: 10px; margin-bottom: 10px;
line-height: 1; line-height: 1;
text-transform: uppercase; text-transform: uppercase;
} }
h2 { h2 {
font-size: 1.8rem; font-size: 1.8rem;
margin: 0 0 16px; margin: 0 0 16px;
} }
h3 { h3 {
font-size: 1.35rem; font-size: 1.35rem;
margin: 0 0 14px; margin: 0 0 14px;
} }
p, p,
ul { ul {
margin-bottom: 16px; margin-bottom: 16px;
} }
.subtitle { .subtitle {
color: var(--accent-strong); color: var(--accent-strong);
font-size: 1rem; font-size: 1rem;
} }
.back-button { .back-button {
display: inline-block; display: inline-block;
margin-bottom: 20px; margin-bottom: 20px;
padding: 10px 15px; padding: 10px 15px;
background: var(--highlight); background: var(--highlight);
color: var(--text); color: var(--text);
text-decoration: none; text-decoration: none;
border: 3px solid var(--border); border: 3px solid var(--border);
} }
.back-button:hover, .back-button:hover,
.action-button:hover { .action-button:hover {
background: var(--text); background: var(--text);
color: #fff; color: #fff;
} }
.info-box { .info-box {
background: var(--highlight); background: var(--highlight);
border: 3px solid var(--border); border: 3px solid var(--border);
padding: 16px; padding: 16px;
margin: 20px 0; margin: 20px 0;
} }
.canvas-container { .canvas-container {
background: var(--panel); background: var(--panel);
border: 3px solid var(--border); border: 3px solid var(--border);
padding: 20px; padding: 20px;
margin: 30px 0; margin: 30px 0;
} }
.canvas-toolbar { .canvas-toolbar {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
gap: 12px; gap: 12px;
margin-bottom: 15px; margin-bottom: 15px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.canvas-toolbar p { .canvas-toolbar p {
margin: 0; margin: 0;
color: var(--muted); color: var(--muted);
font-size: 0.95rem; font-size: 0.95rem;
text-transform: uppercase; text-transform: uppercase;
} }
.action-button { .action-button {
padding: 10px 14px; padding: 10px 14px;
background: var(--danger); background: var(--danger);
color: white; color: white;
border: 3px solid var(--border); border: 3px solid var(--border);
cursor: pointer; cursor: pointer;
font: inherit; font: inherit;
} }
.canvas-shell { .canvas-shell {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
min-height: 520px; min-height: 520px;
overflow: auto; overflow: auto;
background: var(--panel-2); background: var(--panel-2);
border: 3px solid var(--border); border: 3px solid var(--border);
padding: 12px; padding: 12px;
} }
#canvas { #canvas {
display: block; display: block;
margin: 0 auto; margin: 0 auto;
max-width: 100%; max-width: 100%;
height: auto; height: auto;
background: #000; background: #000;
outline: none; outline: none;
image-rendering: pixelated; image-rendering: pixelated;
} }
.canvas-options { .canvas-options {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 14px; gap: 14px;
margin-top: 15px; margin-top: 15px;
font-size: 0.95rem; font-size: 0.95rem;
color: var(--muted); color: var(--muted);
} }
.canvas-options label { .canvas-options label {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
} }
.canvas-options input { .canvas-options input {
accent-color: var(--accent-strong); accent-color: var(--accent-strong);
} }
.status { .status {
margin-top: 15px; margin-top: 15px;
min-height: 24px; min-height: 24px;
color: var(--accent-strong); color: var(--accent-strong);
font-weight: 700; font-weight: 700;
} }
progress { progress {
width: 100%; width: 100%;
height: 18px; height: 18px;
margin-top: 10px; margin-top: 10px;
border: 3px solid var(--border); border: 3px solid var(--border);
} }
progress[hidden] { progress[hidden] {
display: none; display: none;
} }
details { details {
margin-top: 15px; margin-top: 15px;
} }
summary { summary {
cursor: pointer; cursor: pointer;
} }
.feature-list { .feature-list {
padding-left: 24px; padding-left: 24px;
} }
.feature-list li { .feature-list li {
margin-bottom: 10px; margin-bottom: 10px;
} }
.visually-hidden { .visually-hidden {
position: absolute; position: absolute;
width: 1px; width: 1px;
height: 1px; height: 1px;
padding: 0; padding: 0;
margin: -1px; margin: -1px;
overflow: hidden; overflow: hidden;
clip: rect(0, 0, 0, 0); clip: rect(0, 0, 0, 0);
white-space: nowrap; white-space: nowrap;
border: 0; border: 0;
} }
textarea { textarea {
width: 100%; width: 100%;
min-height: 120px; min-height: 120px;
margin-top: 10px; margin-top: 10px;
padding: 10px; padding: 10px;
border: 3px solid var(--border); border: 3px solid var(--border);
font-family: "Courier New", monospace; font-family: 'Courier New', monospace;
font-size: 0.9rem; font-size: 0.9rem;
resize: vertical; resize: vertical;
background: white; background: white;
color: var(--text); color: var(--text);
} }
footer { footer {
text-align: center; text-align: center;
margin-top: 40px; margin-top: 40px;
padding-top: 20px; padding-top: 20px;
border-top: 3px solid var(--border); border-top: 3px solid var(--border);
font-size: 0.9rem; font-size: 0.9rem;
color: var(--muted); color: var(--muted);
} }
@media (max-width: 768px) { @media (max-width: 768px) {
body { body {
padding: 16px; padding: 16px;
font-size: 16px; font-size: 16px;
} }
h1 { h1 {
font-size: 2.2rem; font-size: 2.2rem;
} }
.canvas-container { .canvas-container {
padding: 15px; padding: 15px;
} }
.canvas-shell { .canvas-shell {
min-height: 360px; min-height: 360px;
} }
} }
File diff suppressed because one or more lines are too long
+6 -2
View File
@@ -6,7 +6,7 @@ export function setupCanvas(gl, canvas) {
return { return {
canvas, canvas,
gl, gl,
aspectRatio: canvas.width / canvas.height aspectRatio: canvas.width / canvas.height,
}; };
} }
@@ -15,5 +15,9 @@ export function resizeCanvas(gl, canvas, program) {
canvas.height = canvas.clientHeight * window.devicePixelRatio; canvas.height = canvas.clientHeight * window.devicePixelRatio;
gl.viewport(0, 0, canvas.width, canvas.height); gl.viewport(0, 0, canvas.width, canvas.height);
gl.useProgram(program); gl.useProgram(program);
gl.uniform2f(gl.getUniformLocation(program, "u_resolution"), canvas.width, canvas.height); gl.uniform2f(
gl.getUniformLocation(program, 'u_resolution'),
canvas.width,
canvas.height
);
} }
+68 -41
View File
@@ -1,8 +1,8 @@
import { initWasm } from "./wasm.js"; import { initWasm } from './wasm.js';
import { setupCanvas, resizeCanvas } from "./canvas.js"; import { setupCanvas, resizeCanvas } from './canvas.js';
import { createShaderProgram } from "./shaders.js"; import { createShaderProgram } from './shaders.js';
import { draw } from "./tsp-gl.js"; import { draw } from './tsp-gl.js';
import { initPoints } from "./utils.js"; import { initPoints } from './utils.js';
const DEFAULT_POINT_COUNT = 36; const DEFAULT_POINT_COUNT = 36;
const MIN_POINTS = 4; const MIN_POINTS = 4;
@@ -57,28 +57,31 @@ function createLineFragmentShader() {
} }
async function run() { async function run() {
const canvas = document.getElementById("tsp-canvas"); const canvas = document.getElementById('tsp-canvas');
const pointCountInput = document.getElementById("pointCountInput"); const pointCountInput = document.getElementById('pointCountInput');
const applyPointCountButton = document.getElementById("applyPointCountButton"); const applyPointCountButton = document.getElementById(
const pointCountStatus = document.getElementById("pointCountStatus"); 'applyPointCountButton'
);
const pointCountStatus = document.getElementById('pointCountStatus');
if (!canvas || !pointCountInput || !applyPointCountButton || !pointCountStatus) { if (
!canvas ||
!pointCountInput ||
!applyPointCountButton ||
!pointCountStatus
) {
return; return;
} }
const gl = canvas.getContext("webgl2"); const gl = canvas.getContext('webgl2');
if (!gl) { if (!gl) {
pointCountStatus.textContent = "WebGL2 unavailable in this browser."; pointCountStatus.textContent = 'WebGL2 unavailable in this browser.';
return; return;
} }
gl.clearColor(0.1, 0.1, 0.1, 1); gl.clearColor(0.1, 0.1, 0.1, 1);
const { const { initialisePoints, getPointOrder, memory } = await initWasm();
initialisePoints,
getPointOrder,
memory
} = await initWasm();
const vertexCode = ` const vertexCode = `
attribute vec2 a_position; attribute vec2 a_position;
@@ -93,7 +96,7 @@ async function run() {
const lineBuffer = gl.createBuffer(); const lineBuffer = gl.createBuffer();
if (!positionBuffer || !lineBuffer) { if (!positionBuffer || !lineBuffer) {
pointCountStatus.textContent = "Unable to initialise WebGL buffers."; pointCountStatus.textContent = 'Unable to initialise WebGL buffers.';
return; return;
} }
@@ -103,20 +106,26 @@ async function run() {
const state = { const state = {
scene: null, scene: null,
draggingIndex: -1 draggingIndex: -1,
}; };
function updateStatus(pointCount) { function updateStatus(pointCount) {
pointCountStatus.textContent = `${pointCount} point${pointCount === 1 ? "" : "s"}`; pointCountStatus.textContent = `${pointCount} point${pointCount === 1 ? '' : 's'}`;
} }
function recalculateRoute(scene) { function recalculateRoute(scene) {
const pointOrderPtr = getPointOrder(scene.pointsPtr, scene.pointCount); const pointOrderPtr = getPointOrder(scene.pointsPtr, scene.pointCount);
scene.pointOrder = Array.from(new Uint32Array(memory.buffer, pointOrderPtr, scene.pointCount)); scene.pointOrder = Array.from(
new Uint32Array(memory.buffer, pointOrderPtr, scene.pointCount)
);
} }
function syncPointsToMemory(scene) { function syncPointsToMemory(scene) {
scene.pointArray = new Float32Array(memory.buffer, scene.pointsPtr, scene.pointCount * 2); scene.pointArray = new Float32Array(
memory.buffer,
scene.pointsPtr,
scene.pointCount * 2
);
for (let i = 0; i < scene.points.length; i++) { for (let i = 0; i < scene.points.length; i++) {
scene.pointArray[i * 2] = scene.points[i].cx; scene.pointArray[i * 2] = scene.points[i].cx;
@@ -133,10 +142,22 @@ async function run() {
} }
const pointsPtr = initialisePoints(pointCount, Date.now()); const pointsPtr = initialisePoints(pointCount, Date.now());
const pointArray = new Float32Array(memory.buffer, pointsPtr, pointCount * 2); const pointArray = new Float32Array(
memory.buffer,
pointsPtr,
pointCount * 2
);
const points = initPoints(pointArray); const points = initPoints(pointArray);
const program = createShaderProgram(gl, vertexCode, createPointFragmentShader(pointCount)); const program = createShaderProgram(
const lineProgram = createShaderProgram(gl, vertexCode, createLineFragmentShader()); gl,
vertexCode,
createPointFragmentShader(pointCount)
);
const lineProgram = createShaderProgram(
gl,
vertexCode,
createLineFragmentShader()
);
state.scene = { state.scene = {
pointCount, pointCount,
@@ -145,7 +166,7 @@ async function run() {
points, points,
pointOrder: [], pointOrder: [],
program, program,
lineProgram lineProgram,
}; };
recalculateRoute(state.scene); recalculateRoute(state.scene);
@@ -154,7 +175,7 @@ async function run() {
pointCountInput.value = String(pointCount); pointCountInput.value = String(pointCount);
} }
canvas.addEventListener("mousedown", (e) => { canvas.addEventListener('mousedown', (e) => {
if (!state.scene) { if (!state.scene) {
return; return;
} }
@@ -165,8 +186,8 @@ async function run() {
for (let i = 0; i < state.scene.points.length; i++) { for (let i = 0; i < state.scene.points.length; i++) {
const point = state.scene.points[i]; const point = state.scene.points[i];
const dx = (0.5 * x + 0.5) - point.cx; const dx = 0.5 * x + 0.5 - point.cx;
const dy = (0.5 * y + 0.5) - point.cy; const dy = 0.5 * y + 0.5 - point.cy;
const distance = Math.hypot(dx, dy); const distance = Math.hypot(dx, dy);
if (distance <= RADIUS_SIZE) { if (distance <= RADIUS_SIZE) {
@@ -176,14 +197,16 @@ async function run() {
} }
}); });
canvas.addEventListener("mousemove", (e) => { canvas.addEventListener('mousemove', (e) => {
if (!state.scene || state.draggingIndex === -1) { if (!state.scene || state.draggingIndex === -1) {
return; return;
} }
const rect = canvas.getBoundingClientRect(); const rect = canvas.getBoundingClientRect();
state.scene.points[state.draggingIndex].cx = (e.clientX - rect.left) / rect.width; state.scene.points[state.draggingIndex].cx =
state.scene.points[state.draggingIndex].cy = 1 - (e.clientY - rect.top) / rect.height; (e.clientX - rect.left) / rect.width;
state.scene.points[state.draggingIndex].cy =
1 - (e.clientY - rect.top) / rect.height;
syncPointsToMemory(state.scene); syncPointsToMemory(state.scene);
recalculateRoute(state.scene); recalculateRoute(state.scene);
@@ -193,26 +216,30 @@ async function run() {
state.draggingIndex = -1; state.draggingIndex = -1;
} }
canvas.addEventListener("mouseup", stopDragging); canvas.addEventListener('mouseup', stopDragging);
canvas.addEventListener("mouseleave", stopDragging); canvas.addEventListener('mouseleave', stopDragging);
function applyPointCount() { function applyPointCount() {
const nextPointCount = clampPointCount(Number.parseInt(pointCountInput.value, 10)); const nextPointCount = clampPointCount(
Number.parseInt(pointCountInput.value, 10)
);
initialiseScene(nextPointCount); initialiseScene(nextPointCount);
} }
applyPointCountButton.addEventListener("click", applyPointCount); applyPointCountButton.addEventListener('click', applyPointCount);
pointCountInput.addEventListener("keydown", (event) => { pointCountInput.addEventListener('keydown', (event) => {
if (event.key === "Enter") { if (event.key === 'Enter') {
applyPointCount(); applyPointCount();
} }
}); });
pointCountInput.addEventListener("blur", () => { pointCountInput.addEventListener('blur', () => {
pointCountInput.value = String(clampPointCount(Number.parseInt(pointCountInput.value, 10))); pointCountInput.value = String(
clampPointCount(Number.parseInt(pointCountInput.value, 10))
);
}); });
window.addEventListener("resize", () => { window.addEventListener('resize', () => {
if (!state.scene) { if (!state.scene) {
return; return;
} }
-1
View File
@@ -17,4 +17,3 @@ export function createShaderProgram(gl, vertexCode, fragCode) {
return program; return program;
} }
+14 -5
View File
@@ -1,7 +1,16 @@
// tsp-gl.js // tsp-gl.js
import { updateLines } from "./utils.js"; import { updateLines } from './utils.js';
export function draw(gl, points, program, lineProgram, positionBuffer, lineBuffer, pointOrder, aspectRatio) { export function draw(
gl,
points,
program,
lineProgram,
positionBuffer,
lineBuffer,
pointOrder,
aspectRatio
) {
gl.clear(gl.COLOR_BUFFER_BIT); gl.clear(gl.COLOR_BUFFER_BIT);
// Draw Circles // Draw Circles
@@ -22,10 +31,10 @@ function updateCircleUniforms(gl, points, program, positionBuffer) {
gl.useProgram(program); gl.useProgram(program);
gl.uniform2fv(gl.getUniformLocation(program, "u_centers"), centerArray); gl.uniform2fv(gl.getUniformLocation(program, 'u_centers'), centerArray);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positionAttribLoc = gl.getAttribLocation(program, "a_position"); const positionAttribLoc = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionAttribLoc); gl.enableVertexAttribArray(positionAttribLoc);
gl.vertexAttribPointer(positionAttribLoc, 2, gl.FLOAT, false, 0, 0); gl.vertexAttribPointer(positionAttribLoc, 2, gl.FLOAT, false, 0, 0);
@@ -38,7 +47,7 @@ function drawLines(gl, program, buffer, lineVertices) {
gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, lineVertices, gl.DYNAMIC_DRAW); gl.bufferData(gl.ARRAY_BUFFER, lineVertices, gl.DYNAMIC_DRAW);
const positionAttribLoc = gl.getAttribLocation(program, "a_position"); const positionAttribLoc = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionAttribLoc); gl.enableVertexAttribArray(positionAttribLoc);
gl.vertexAttribPointer(positionAttribLoc, 2, gl.FLOAT, false, 0, 0); gl.vertexAttribPointer(positionAttribLoc, 2, gl.FLOAT, false, 0, 0);
+11 -8
View File
@@ -1,24 +1,27 @@
export async function initWasm() { export async function initWasm() {
let wasmMemory = new WebAssembly.Memory({ let wasmMemory = new WebAssembly.Memory({
initial: 256, initial: 256,
maximum: 256 maximum: 256,
}); });
let importObject = { let importObject = {
env: { env: {
memory: wasmMemory, memory: wasmMemory,
} },
}; };
const response = await fetch("./main.wasm"); const response = await fetch('./main.wasm');
const wasmModule = await WebAssembly.instantiateStreaming(response, importObject); const wasmModule = await WebAssembly.instantiateStreaming(
const { initialisePoints, getPointOrder, memory } = wasmModule.instance.exports; response,
importObject
);
const { initialisePoints, getPointOrder, memory } =
wasmModule.instance.exports;
return { return {
initialisePoints, initialisePoints,
getPointOrder, getPointOrder,
memory, memory,
wasmMemory wasmMemory,
} };
} }
+222 -222
View File
@@ -1,222 +1,222 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<meta <meta
name="viewport" name="viewport"
width="device-width," width="device-width,"
initial-scale="1.0," initial-scale="1.0,"
maximum-scale="1.0," maximum-scale="1.0,"
user-scalable="0" user-scalable="0"
/> />
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>
<style> <style>
body { body {
padding: 0; padding: 0;
margin: 0; margin: 0;
font-family: font-family:
system-ui, system-ui,
-apple-system, -apple-system,
Segoe UI, Segoe UI,
Roboto, Roboto,
Helvetica, Helvetica,
Arial, Arial,
sans-serif; sans-serif;
background: #fafafa; background: #fafafa;
} }
.intro { .intro {
max-width: 900px; max-width: 900px;
margin: 20px auto 10px; margin: 20px auto 10px;
padding: 0 16px; padding: 0 16px;
} }
.intro h1 { .intro h1 {
margin: 0 0 6px; margin: 0 0 6px;
font-size: 1.5rem; font-size: 1.5rem;
} }
.intro p { .intro p {
margin: 4px 0 14px; margin: 4px 0 14px;
line-height: 1.45; line-height: 1.45;
} }
.slidecontainer { .slidecontainer {
width: 100%; width: 100%;
/* Width of the outside container */ /* Width of the outside container */
} }
/* The slider itself */ /* The slider itself */
.slider { .slider {
-webkit-appearance: none; -webkit-appearance: none;
/* Override default CSS styles */ /* Override default CSS styles */
appearance: none; appearance: none;
width: 100%; width: 100%;
/* Full-width */ /* Full-width */
height: 25px; height: 25px;
/* Specified height */ /* Specified height */
background: #d3d3d3; background: #d3d3d3;
/* Grey background */ /* Grey background */
outline: none; outline: none;
/* Remove outline */ /* Remove outline */
opacity: 1; opacity: 1;
/* Set transparency (for mouse-over effects on hover) */ /* Set transparency (for mouse-over effects on hover) */
-webkit-transition: 0.2s; -webkit-transition: 0.2s;
/* 0.2 seconds transition on hover */ /* 0.2 seconds transition on hover */
transition: opacity 0.2s; transition: opacity 0.2s;
} }
.slider::-webkit-slider-thumb { .slider::-webkit-slider-thumb {
-webkit-appearance: none; -webkit-appearance: none;
/* Override default look */ /* Override default look */
appearance: none; appearance: none;
width: 25px; width: 25px;
/* Set a specific slider handle width */ /* Set a specific slider handle width */
height: 25px; height: 25px;
/* Slider handle height */ /* Slider handle height */
background: #434343; background: #434343;
/* Grey background */ /* Grey background */
cursor: pointer; cursor: pointer;
/* Cursor on hover */ /* Cursor on hover */
} }
.slider::-moz-range-thumb { .slider::-moz-range-thumb {
width: 25px; width: 25px;
/* Set a specific slider handle width */ /* Set a specific slider handle width */
height: 25px; height: 25px;
/* Slider handle height */ /* Slider handle height */
background: #434343; background: #434343;
/* Grey background */ /* Grey background */
cursor: pointer; cursor: pointer;
/* Cursor on hover */ /* Cursor on hover */
} }
</style> </style>
</head> </head>
<body> <body>
<div class="intro"> <div class="intro">
<h1>Oscillating Arrow Field Visualizer</h1> <h1>Oscillating Arrow Field Visualizer</h1>
<p> <p>
A sketch to <s>hopefully</s> demonstrate the illusion of the A sketch to <s>hopefully</s> demonstrate the illusion of the
<a href="https://en.wikipedia.org/wiki/M%C3%BCller-Lyer_illusion" <a href="https://en.wikipedia.org/wiki/M%C3%BCller-Lyer_illusion"
>Müller-Lyer Illusion</a >Müller-Lyer Illusion</a
> >
</p> </p>
<p> <p>
The lines - that are the same length, should look longer and shorter The lines - that are the same length, should look longer and shorter
based on the angle of the arrow heads. based on the angle of the arrow heads.
</p> </p>
<p> <p>
Increasing the value adds more horizontal slices, creating a denser and Increasing the value adds more horizontal slices, creating a denser and
more detailed pattern. Tap or click to pause and resume the motion. more detailed pattern. Tap or click to pause and resume the motion.
</p> </p>
</div> </div>
<div class="slidecontainer"> <div class="slidecontainer">
<input <input
type="range" type="range"
min="2" min="2"
max="11" max="11"
step="1" step="1"
value="2" value="2"
class="slider" class="slider"
id="myRange" id="myRange"
/> />
</div> </div>
<script> <script>
let vMargin, hMargin, arrowHeight, t, lineNum; let vMargin, hMargin, arrowHeight, t, lineNum;
let lineMove = true; let lineMove = true;
function setup() { function setup() {
createCanvas(windowWidth, windowHeight * 0.6); createCanvas(windowWidth, windowHeight * 0.6);
hMargin = 12; hMargin = 12;
arrowHeight = 25; arrowHeight = 25;
t = 0; t = 0;
lineNum = 1; lineNum = 1;
} }
function windowResized() { function windowResized() {
resizeCanvas(windowWidth, windowHeight * 0.6); resizeCanvas(windowWidth, windowHeight * 0.6);
} }
function draw() { function draw() {
background(43); background(43);
angleMode(DEGREES); angleMode(DEGREES);
lineNum = document.getElementById("myRange").value; lineNum = document.getElementById('myRange').value;
drawLine(hMargin, lineNum + 1); drawLine(hMargin, lineNum + 1);
if (lineMove) { if (lineMove) {
t++; t++;
} }
if (t == 360) { if (t == 360) {
t = 0; t = 0;
} }
} }
function drawLine(hm, vm) { function drawLine(hm, vm) {
//let changex = map(sin(t), -1, 1, -22, 22); //let changex = map(sin(t), -1, 1, -22, 22);
let changex = sin(t) * 18; let changex = sin(t) * 18;
vm /= 10; vm /= 10;
for (let j = 1; j < vm - 1; j++) { for (let j = 1; j < vm - 1; j++) {
stroke(255, 34, 63); stroke(255, 34, 63);
strokeWeight(4); strokeWeight(4);
line(width / hm, (j * height) / vm, width / 2, (j * height) / vm); //red line line(width / hm, (j * height) / vm, width / 2, (j * height) / vm); //red line
stroke(69, 98, 255); stroke(69, 98, 255);
line( line(
width / 2, width / 2,
(j * height) / vm, (j * height) / vm,
((hm - 1) * width) / hm, ((hm - 1) * width) / hm,
(j * height) / vm, (j * height) / vm
); //blue line ); //blue line
stroke(255); stroke(255);
line( line(
width / hm, width / hm,
(j * height) / vm, (j * height) / vm,
width / hm + changex, width / hm + changex,
(j * height) / vm - arrowHeight, (j * height) / vm - arrowHeight
); //left top ); //left top
line( line(
width / hm + changex, width / hm + changex,
(j * height) / vm + arrowHeight, (j * height) / vm + arrowHeight,
width / hm, width / hm,
(j * height) / vm, (j * height) / vm
); //left bottom ); //left bottom
line( line(
((hm - 1) * width) / hm + changex, ((hm - 1) * width) / hm + changex,
(j * height) / vm + arrowHeight, (j * height) / vm + arrowHeight,
((hm - 1) * width) / hm, ((hm - 1) * width) / hm,
(j * height) / vm, (j * height) / vm
); //right bottom ); //right bottom
line( line(
width / 2 - changex, width / 2 - changex,
(j * height) / vm + arrowHeight, (j * height) / vm + arrowHeight,
width / 2, width / 2,
(j * height) / vm, (j * height) / vm
); //center bottom ); //center bottom
line( line(
((hm - 1) * width) / hm, ((hm - 1) * width) / hm,
(j * height) / vm, (j * height) / vm,
((hm - 1) * width) / hm + changex, ((hm - 1) * width) / hm + changex,
(j * height) / vm - arrowHeight, (j * height) / vm - arrowHeight
); //right bottom ); //right bottom
line( line(
width / 2, width / 2,
(j * height) / vm, (j * height) / vm,
width / 2 - changex, width / 2 - changex,
(j * height) / vm - arrowHeight, (j * height) / vm - arrowHeight
); //center top ); //center top
} }
} }
function mouseClicked() { function mouseClicked() {
lineMove = !lineMove; lineMove = !lineMove;
} }
</script> </script>
</body> </body>
</html> </html>
+149 -132
View File
@@ -1,6 +1,7 @@
const NAV_OFFSET = 120; const NAV_OFFSET = 120;
const DEFAULT_VISIBLE_PROJECTS = 9; const DEFAULT_VISIBLE_PROJECTS = 9;
const INTERACTIVE_SELECTOR = 'a, button, input, textarea, select, summary, [role="button"]'; const INTERACTIVE_SELECTOR =
'a, button, input, textarea, select, summary, [role="button"]';
initRevealOnScroll(); initRevealOnScroll();
initActiveNavLink(); initActiveNavLink();
@@ -8,168 +9,184 @@ initProjectCardLinks();
initProjectFilters(); initProjectFilters();
function initRevealOnScroll() { function initRevealOnScroll() {
const revealTargets = document.querySelectorAll('.reveal'); const revealTargets = document.querySelectorAll('.reveal');
if (revealTargets.length === 0) { if (revealTargets.length === 0) {
return; return;
} }
const observer = new IntersectionObserver((entries, currentObserver) => { const observer = new IntersectionObserver(
entries.forEach((entry) => { (entries, currentObserver) => {
if (!entry.isIntersecting) { entries.forEach((entry) => {
return; if (!entry.isIntersecting) {
} return;
}
entry.target.classList.add('visible'); entry.target.classList.add('visible');
currentObserver.unobserve(entry.target); currentObserver.unobserve(entry.target);
}); });
}, {threshold: 0.1, rootMargin: '0px 0px -40px 0px'}); },
{ threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
);
revealTargets.forEach((target) => observer.observe(target)); revealTargets.forEach((target) => observer.observe(target));
} }
function initActiveNavLink() { function initActiveNavLink() {
const sections = Array.from(document.querySelectorAll('section[id]')); const sections = Array.from(document.querySelectorAll('section[id]'));
const navLinks = Array.from(document.querySelectorAll('.nav-links a')); const navLinks = Array.from(document.querySelectorAll('.nav-links a'));
if (sections.length === 0 || navLinks.length === 0) { if (sections.length === 0 || navLinks.length === 0) {
return; return;
} }
const updateActiveNavLink = () => { const updateActiveNavLink = () => {
let currentSectionId = ''; let currentSectionId = '';
sections.forEach((section) => { sections.forEach((section) => {
if (window.scrollY >= section.offsetTop - NAV_OFFSET) { if (window.scrollY >= section.offsetTop - NAV_OFFSET) {
currentSectionId = section.id; currentSectionId = section.id;
} }
}); });
navLinks.forEach((link) => { navLinks.forEach((link) => {
link.classList.toggle('is-active', link.getAttribute('href') === `#${currentSectionId}`); link.classList.toggle(
}); 'is-active',
}; link.getAttribute('href') === `#${currentSectionId}`
);
});
};
window.addEventListener('scroll', updateActiveNavLink, {passive: true}); window.addEventListener('scroll', updateActiveNavLink, { passive: true });
updateActiveNavLink(); updateActiveNavLink();
} }
function initProjectCardLinks() { function initProjectCardLinks() {
const cardLinks = document.querySelectorAll('.card-link[data-href]'); const cardLinks = document.querySelectorAll('.card-link[data-href]');
if (cardLinks.length === 0) { if (cardLinks.length === 0) {
return;
}
cardLinks.forEach((card) => {
card.setAttribute('role', 'link');
card.setAttribute('tabindex', '0');
card.addEventListener('click', (event) => {
if (shouldIgnoreCardActivation(card, event.target)) {
return; return;
} }
cardLinks.forEach((card) => { navigateToCard(card, event);
card.setAttribute('role', 'link');
card.setAttribute('tabindex', '0');
card.addEventListener('click', (event) => {
if (shouldIgnoreCardActivation(card, event.target)) {
return;
}
navigateToCard(card, event);
});
card.addEventListener('keydown', (event) => {
if (event.key !== 'Enter' && event.key !== ' ') {
return;
}
if (shouldIgnoreCardActivation(card, event.target)) {
return;
}
event.preventDefault();
navigateToCard(card, event);
});
}); });
card.addEventListener('keydown', (event) => {
if (event.key !== 'Enter' && event.key !== ' ') {
return;
}
if (shouldIgnoreCardActivation(card, event.target)) {
return;
}
event.preventDefault();
navigateToCard(card, event);
});
});
} }
function shouldIgnoreCardActivation(card, target) { function shouldIgnoreCardActivation(card, target) {
if (!(target instanceof Element)) { if (!(target instanceof Element)) {
return false; return false;
} }
const interactiveAncestor = target.closest(INTERACTIVE_SELECTOR); const interactiveAncestor = target.closest(INTERACTIVE_SELECTOR);
return interactiveAncestor !== null && interactiveAncestor !== card; return interactiveAncestor !== null && interactiveAncestor !== card;
} }
function navigateToCard(card, event) { function navigateToCard(card, event) {
const href = card.dataset.href; const href = card.dataset.href;
if (!href) { if (!href) {
return; return;
} }
if (event.metaKey || event.ctrlKey || event.button === 1) { if (event.metaKey || event.ctrlKey || event.button === 1) {
window.open(href, '_blank', 'noopener'); window.open(href, '_blank', 'noopener');
return; return;
} }
window.location.assign(href); window.location.assign(href);
} }
function initProjectFilters() { function initProjectFilters() {
const filterChips = Array.from(document.querySelectorAll('.filter-chip')); const filterChips = Array.from(document.querySelectorAll('.filter-chip'));
const projectCards = Array.from(document.querySelectorAll('#project-grid .project-card')); const projectCards = Array.from(
if (filterChips.length === 0 || projectCards.length === 0) { document.querySelectorAll('#project-grid .project-card')
);
if (filterChips.length === 0 || projectCards.length === 0) {
return;
}
const seeMoreButton = document.querySelector('#projects-see-more');
const techByCard = new Map(
projectCards.map((card) => [
card,
(card.dataset.tech || '').split(/\s+/).filter(Boolean),
])
);
let selectedFilter = 'all';
let isExpanded = false;
const applyFilter = () => {
let visibleCount = 0;
projectCards.forEach((card) => {
const tech = techByCard.get(card) || [];
const matchesFilter =
selectedFilter === 'all' || tech.includes(selectedFilter);
card.classList.toggle('is-hidden', !matchesFilter);
if (!matchesFilter) {
card.classList.remove('is-collapsed');
return; return;
} }
const seeMoreButton = document.querySelector('#projects-see-more'); const isCollapsed =
const techByCard = new Map( !isExpanded && visibleCount >= DEFAULT_VISIBLE_PROJECTS;
projectCards.map((card) => [card, (card.dataset.tech || '').split(/\s+/).filter(Boolean)]), card.classList.toggle('is-collapsed', isCollapsed);
); visibleCount += 1;
let selectedFilter = 'all';
let isExpanded = false;
const applyFilter = () => {
let visibleCount = 0;
projectCards.forEach((card) => {
const tech = techByCard.get(card) || [];
const matchesFilter = selectedFilter === 'all' || tech.includes(selectedFilter);
card.classList.toggle('is-hidden', !matchesFilter);
if (!matchesFilter) {
card.classList.remove('is-collapsed');
return;
}
const isCollapsed = !isExpanded && visibleCount >= DEFAULT_VISIBLE_PROJECTS;
card.classList.toggle('is-collapsed', isCollapsed);
visibleCount += 1;
});
if (!seeMoreButton) {
return;
}
const canExpand = visibleCount > DEFAULT_VISIBLE_PROJECTS;
seeMoreButton.hidden = !canExpand;
seeMoreButton.setAttribute('aria-expanded', canExpand && isExpanded ? 'true' : 'false');
seeMoreButton.textContent = isExpanded ? 'See less' : 'See more';
};
filterChips.forEach((chip) => {
chip.addEventListener('click', () => {
selectedFilter = chip.dataset.filter || 'all';
isExpanded = false;
filterChips.forEach((otherChip) => {
otherChip.classList.toggle('active', otherChip === chip);
});
applyFilter();
});
}); });
if (seeMoreButton) { if (!seeMoreButton) {
seeMoreButton.addEventListener('click', () => { return;
isExpanded = !isExpanded;
applyFilter();
});
} }
applyFilter(); const canExpand = visibleCount > DEFAULT_VISIBLE_PROJECTS;
} seeMoreButton.hidden = !canExpand;
seeMoreButton.setAttribute(
'aria-expanded',
canExpand && isExpanded ? 'true' : 'false'
);
seeMoreButton.textContent = isExpanded ? 'See less' : 'See more';
};
filterChips.forEach((chip) => {
chip.addEventListener('click', () => {
selectedFilter = chip.dataset.filter || 'all';
isExpanded = false;
filterChips.forEach((otherChip) => {
otherChip.classList.toggle('active', otherChip === chip);
});
applyFilter();
});
});
if (seeMoreButton) {
seeMoreButton.addEventListener('click', () => {
isExpanded = !isExpanded;
applyFilter();
});
}
applyFilter();
}
+684 -674
View File
File diff suppressed because it is too large Load Diff