• Stars
    star
    311
  • Rank 134,521 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐ŸŒŠ๐Ÿ’ฅ N-dimensional Wave Function Collapse with infinite canvas

NDWFC

A Wave Function Collapse implementation with infinite canvas in arbitrary number of dimensions.

Online Demo

Installation

Browser

<!-- the main library -->
<script src="ndwfc.js"></script>

<!-- optional helpful tools -->
<script src="ndwfc-tools.js"></script>

Node.js

// the main library
const WFC = require('./ndwfc');

// optional helpful tools
const {WFCTool2D,WFCTool3D} = require('./ndwfc-tools');

Usage

The main library, ndwfc.js, doesn't make any assumption about what you're trying to generate. It is an abstracted implementation of the WFC algorithm, while ndwfc-tools.js provide helpful functions for practical usage such as generating tiled textures or models.

Below are some sample code, but be sure to check out index.js for detailed usage and examples.

Basics

var nd = 2;             // number of dimensions (2, 3, etc.)
var weights = [1, 1, 1] // weight for each type of tile
                        // this also implies the total number of tiles
                        // here all weights are equal, so the tiles will
                        // generate at equal probability
                        
// the rules is an array of 3-tuples.
// for each rule, the first element specifies the axis, and the 2nd and 3rd
// specifies what tiles can go next to each other on that axis

var rules = [
	['x',0,1],  // 0th tile can be placed to the left of 1st tile
	['x',1,0],  // 1st tile can also be placed to the left of 0th tile
	['y',1,2],
	            // if you have more than 3 dimensions, the axis can be specified
	            // using integers instead of 'x', 'y' and 'z'.
	            // in fact 'y' is an alias of 0th axis, 'x' the 1st, and 'z' the 2nd
	...
	...
]

var wfc = new WFC({nd, weights, rules});  // initialize the wfc!


// define a region of interest inside which you want tiles to be generated
// by passing two corners of the bounding box/cube/hypercube
var size = 5;
wfc.expand([-size,-size],[size,size]);  

// the main loop
// subsitute with setTimeout/requestAnimationFrame/WebWorker depending on usage
                            
while (true){
	var done = wfc.step();  // advance 1 step, filling at least 1 new coordinate.
	                        // step() returns true if the region of interest has
	                        // been entirely filled
	                        
	if (done){ 
		size += 5           // all space filled, time to expand more
		wfc.expand([-size,-size],[size,size]);  // newly marked area will begin to 
		                                        // be generated in the next step()
	}
	
	console.log(wfc.readout());
	// ^ get the current result, an object mapping coordinate to tile index
	// something like {'1,2':0, '2,2':2, '3,1':1, ...}
	
	// use wfc.readout(false) to read the result as probability distribution,
	// something like {'1,2',[1,0,0], '2,2':[0.3,0.2,0.5], ...}
	
}

Using the 2D/3D tile helpers

ndwfc-tools.js provides helpers for generating 2D and 3D content. You can use strings of characters to describe the semantics of your tiles, and the tool can figure out what can go next to what and generate the rules for you. Though the tool is also capable of simple visualization using canvas (2D) or three.js (3D), you can just grab the result from wfc.readout() and plug in your own assets such as image files and 3D models to produce the visuals you want.

// initialize the 2d tool
var tool = new WFCTool2D();

// add an 3x3 "L" shaped tile
tool.addTile(`\
.@.
.@@
...`)
// ^ all rotated versions of the tile will also be added,
// unless you specify otherwise (see below)

// add an 3x3 "I" shaped tile
tool.addTile(`\
.@.
.@.
.@.`,
{transformations:['cw']})
// ^ for this tile, we only need itself and a clockwise 90 deg rotated version
// for 2D tiles, transformations can include 'cw', 'fx' (flip x) and 'fy' (flip y).
// you can also combine them using '+'
// e.g. for anti-clockwise 90 deg rotation you can do 'cw+cw+cw'
// duplicates will be detected and will not be added multiple times.

// add a plain tile
tool.addTile(`\
...
...
...`,
{transformations:[],weight:0.1})
// you can specify the weight of the tile. higher the weight,
// more often it will appear. default is 1.


// rules are automatically generated based on this logic:
// only tiles with an identical edge can go next to each other, like so:
// .@.     ...
// .@@  +  @@@
// ...     ...
// the tiles below can NOT go next to each other:
// .@.     ...
// .@@  +  ...
// ...     ... 
// because the right edge of 1st tile does not match left edge of the 2nd
// same for vertical axis.


// define the color of the symbols.
// this is used only to quickly visualize the results
// you won't need this if you're using your own assets
tool.addColor("@", [255,0,0])
tool.addColor(".", [0,255,255])


// print a summary of automatically generated version of the tiles
// you'll need this if you're using your own assets
// each formula is a 3-tuple:
// the first element is the original index (the order you called `addTile`)
// the second element is the transformations applied (e.g. 'fx+cw')
// the third element is the transformed version
console.log(tool.getTileFormulae());

// this generates all the input which you can directly pass to WFC
var wfcInput = tool.generateWFCInput();
var wfc = new WFC(wfcInput);

... 
... // see previous section on how to use wfc
...

// visualize the output on a HTML canvas
var canvas = document.createElement("canvas");

var viewport = {x:0,y:0,w:10,h:10}; // the region you want to visualize
tool.plotWFCOoutput(canvas, viewport, wfc.readout()); // plot it!

WFCTool3D is similar to WFCTool2D, see index.js for usage example.

More Repositories

1

shan-shui-inf

Procedurally generated Chinese landscape painting.
HTML
5,488
star
2

fishdraw

procedurally generated fish drawings
JavaScript
2,200
star
3

qiji-font

้ฝŠไผ‹้ซ” - typeface from Ming Dynasty woodblock printed books
Python
1,296
star
4

rrpl

Describing Chinese Characters with Recursive Radical Packing Language (RRPL)
JavaScript
884
star
5

wax

A tiny programming language that transpiles to C, C++, Java, TypeScript, Python, C#, Swift, Lua and WebAssembly ๐Ÿš€
C
770
star
6

linedraw

Convert images to vectorized line drawings for plotters.
Python
755
star
7

q5xjs

A small and fast alternative (experimental) implementation of p5.js
JavaScript
541
star
8

nonflowers

Procedurally generated paintings of nonexistent flowers.
JavaScript
509
star
9

skeleton-tracing

A new algorithm for retrieving topological skeleton as a set of polylines from binary images
C
497
star
10

cope

A modern IDE for writing classical Chinese poetry ๆ ผๅพ‹่ฏ—็ผ–่พ‘็จ‹ๅบ
JavaScript
455
star
11

psvg

Programmable Scalable Vector Graphics -- drawings that draw themselves
TypeScript
297
star
12

legumes

๐ŸŽผ A sheet music to polylines renderer
TypeScript
230
star
13

magic-square-poems

Discovering magic squares in Tang Dynasty poems
C
188
star
14

handpose-facemesh-demos

๐ŸŽฅ๐ŸคŸ 8 minimalistic templates for tfjs mediapipe handpose and facemesh
JavaScript
187
star
15

Hermit

A man. A horse. A nature.
Python
168
star
16

chinese-hershey-font

Convert Chinese Characters to Single-Line Fonts using Computer Vision
Python
129
star
17

Processing-Demos-for-The-Pocket-Handbook-of-Image-Processing-Algorithms

Processing Demos made when reading the book *The Pocket Handbook for Image Processing Algorithms in C*
Processing
127
star
18

edges2calligraphy

Using pix2pix to convert scribbles to Chinese calligraphy
JavaScript
115
star
19

tk-fangsong-font

ๅ‰”้ชจไปฟๅฎ‹: Experimental Fang Song style Chinese font
Python
112
star
20

grand-timeline

Interactive grand unified timeline of 30,800 ancient Chinese people / ๅคไบบๅ…จ่กจ
JavaScript
111
star
21

hfmath

Render LaTeX math with Hershey Fonts
TypeScript
94
star
22

VisionOSC

PoseOSC + FaceOSC + HandOSC + OcrOSC + CatOSC + DogOSC
Objective-C++
88
star
23

wechit

WeChat in Terminal (ๅพฎไฟก็ปˆ็ซฏ็‰ˆ)
Python
88
star
24

wasm-fun

Non-trivial programs in hand-written WebAssembly
WebAssembly
78
star
25

PoseOSC

๐Ÿ“น๐Ÿคธโ€โ™‚๏ธ๐Ÿคพโ€โ™€๏ธ๐Ÿคบ PoseNet + OSC: send realtime human pose estimation data to your apps
JavaScript
77
star
26

ci-ren

Generative Chinese poetry
Python
75
star
27

r1b

A thermal-printer-oriented, 1-bit graphics rasterizer for 2D and 3D
C
73
star
28

squiggy

vector brushstroke library
TypeScript
65
star
29

asciimare

3D engine powered by ASCII art
Python
63
star
30

Okb.js

Procedural generation toolkit for Javascript - noises, randomness, curves, and more
HTML
60
star
31

ofxPoissonFill

Poisson filling shader for OpenFrameworks
C++
56
star
32

p5-hershey-js

p5.js Hershey Vector Font Library
JavaScript
53
star
33

pmst

๐ŸŽจ Poor Man's Style Transfer - Painting an image with the style of another, without machine learning
C++
48
star
34

Loshu.js

A linear algebra library for JavaScript ๐Ÿ”ข
JavaScript
47
star
35

zdic-cli

An offline command-line interface to zdic.net dictionary (ๆผขๅ…ธ)
JavaScript
47
star
36

interesting-polygon-archive

Collection of polygon data in various formats for testing computational geometry algorithms.
Processing
46
star
37

ttf2hershey

Convert True Type Fonts (.ttf) to Hershey vector fonts
Python
43
star
38

skeletonization-js

Javascript implementation of image skeletonization
JavaScript
42
star
39

t43

A tiny 3D slicer written from scratch
C
32
star
40

fv

An experimental approach to expressing vector math in js (tagged template literals)
JavaScript
31
star
41

LingDong-

Automatically keep my Github profile README updated with a python script and Github Actions
Python
28
star
42

PContour

Processing/Java library for finding contours in binary images
HTML
28
star
43

srcsnap

screenshot-driven version tracking
JavaScript
22
star
44

dbn.js

Recreation of John Maeda's "Design By Numbers" programming environment in JavaScript
JavaScript
18
star
45

wax4vscode

Extension for the wax programming language in VS Code (highlight + transpile + run)
TypeScript
17
star
46

TrackpadOSC

๐Ÿ’ป๐Ÿ‘‹โœŒ๏ธ๐Ÿ‘‰Send mac's multitouch trackpad read-out through OSC
Objective-C
17
star
47

xcessing

Friendly Processing-like interface to X11/Xlib in C
C
16
star
48

svg2pl

convert svg to polylines
C
15
star
49

lbll

tiny experimental language for limited environments
C
14
star
50

fast-many-face-detection-with-cpp-or-openframeworks-on-mac-using-neural-networks

Fast Many Face Detection with C++/OpenFrameworks on macOS using Neural Networks
C++
14
star
51

galiano-drawing

A procedurally generated drawing
JavaScript
11
star
52

machining-projection-map

JavaScript
8
star
53

avrlass

AVR Lightweight Assembler (and disassembler)
JavaScript
6
star
54

60-212

JavaScript
5
star
55

teapot.lua

1 path tracer written in pure lua, 1 file, 0 dependencies.
Lua
5
star
56

Hello-World

Lorem Ipsum
3
star
57

cvDictUI

opencv-python tool for generating interactive GUI from any python dictionary
Python
3
star
58

lingdong

LingDong's project links
JavaScript
2
star
59

galiano-lidar-render

Semi-realistic rendering of LiDAR data from the entire Galiano Island, BC
C
1
star