From c4a238c10c7ce0370d572db8bfb5a32c254b677a Mon Sep 17 00:00:00 2001 From: 409 Date: Fri, 22 Mar 2024 13:05:23 +0100 Subject: [PATCH] v1.0.0: cleanup and documentation --- README.md | 77 ++++++++++++++++++++++++++++++++++++++++++++------ build.mjs | 8 ++++++ bun.lockb | Bin 15573 -> 22291 bytes index.ts | 52 ---------------------------------- layers.ts | 72 ---------------------------------------------- package.json | 50 +++++++++++++++++++++++--------- src/index.ts | 60 +++++++++++++++++++++++++++++++++++++++ src/layers.ts | 25 ++++++++++++++++ 8 files changed, 199 insertions(+), 145 deletions(-) create mode 100644 build.mjs delete mode 100644 index.ts delete mode 100644 layers.ts create mode 100644 src/index.ts create mode 100644 src/layers.ts diff --git a/README.md b/README.md index 8779290..491a4e7 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,76 @@ # generative-art +An easy-to-use library to generate random images from a set of layers. -To install dependencies: - -```bash -bun install +## Installation +NPM: +```console +$ npm install layered-generative-art +``` +Bun: +```console +$ bun add layered-generative-art ``` -To run: +## Example +```ts +// import generate function +import { generateRandomImage } from 'layered-generative-art'; +import { writeFileSync } from 'node:fs'; -```bash -bun run index.ts +// ... + +// generate a random character from a fixed base shape, randomly choose between brown or +// blue eyes (blue eyes are 5 times as rare) and an optional hat at a 25% probability +const result: GenerativeArtOutput = generateRandomImage('./assets/base_shape.png', [ + { + traitName: 'Eyes', + path: './assets/eyes/', + options: [ + { + name: 'Blue', + // this path will be combined with the layer's path (in this case => './assets/eyes/blue_eyes.png') + path: 'blue_eyes.png', + weight: 1 + }, + { + name: 'Brown', + path: 'brown.png', + // Brown eyes now have 5 times the probability of blue eyes + weight: 5 + } + ] + }, + { + traitName: 'Hat', + path: './assets/hats/', + // Set the probability of a hat occouring to 25% + probability: 0.25, + options: [ + { + name: 'Red Beanie', + path: 'red_beanie.png', + }, + { + name: 'Green Cap', + path: 'green_cap.png', + } + ] + }, +]); + +// write the newly generated character to a file +writeFileSync('./output/my_character.png', result.buffer); + +// log the choices that were taken by the generator +console.log(result.choices); ``` -This project was created using `bun init` in bun v1.0.33. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. +## Features +- optional layers based on a probability +- weighted layer options to create rare trait options + +## Contributing +Feel free to open pull requests + +## License +MIT diff --git a/build.mjs b/build.mjs new file mode 100644 index 0000000..0134dbb --- /dev/null +++ b/build.mjs @@ -0,0 +1,8 @@ +import dts from "bun-plugin-dts"; + +await Bun.build({ + entrypoints: ["./src/index.ts"], + outdir: "./dist", + minify: true, + plugins: [dts()], +}); diff --git a/bun.lockb b/bun.lockb index 55806a4f3a4c2547c7b44f23a17ac87323104422..0c42d60c02665f1f4cb043233ee33aab281c042c 100755 GIT binary patch delta 6080 zcmd@&d0bP+*7t@)2*@f>!Xm2z!VQG5D@y?dtqNG`f`SbpglHg;L}cqrthlzQd{e7G zu>!s-YN?=9p6JuMD{fTWg|^^B9~A|q*0tbw=7x)Tt$n}W_xCry%sq3KIdkTmnaRw# zUWE3N8~EOfYWlTbS(_V&PTjG7J36{;@7(&>6pbbDPfR+G#4G6*diVex0X6}&1!w_qtOgp@!-N4)HWu*D0mmI~0FFB}19Sqo1)wv)6#%h8 zxd7h-sFLIqNR$MT!zBp#X^TX1xlE-d#K1QJT&$2QfK7;v31T$h%>eO4O@OJv0`)+E zpLRBUOaX$`w7>+A#vKaaV*$_>AU3Q>q?D>a<|`1!{31apwuPt|#!Epv)^}nUN&sR* zQvu@fv>=B)nQuzWqFpIbiA8czrbH~4Es=quFJUx1liL7s2k1vD1UJ*L8hT@X|1j(Z zh~=`Zz@WwhqzS31xY4k=-|BgZjoH*xarVvdvBD{$p5l#e0c+as&3SOua((aJJt5k@ z*AdbmGD}x2@`xKC2ksqJ9~+dD4S8;Hcbwe1+>deHnp4TG?Ngpt<<%(!-^u&L+a6}7 ze)Qv{V{zR-CZCl(a!Rk4eRKWdn4`A8%TEr@m|wWi&a+H(tvZ00^wHIa9>ofac{BY^ zZ0DUnX+7>Zl7Wt~ywGD-0_l&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!Jl*^6?$%SI%g)`@ULfP9rd)E4HfAqZeR!$l_wgkiuM<~+uS=WAe&%{} z-`#>KcruhsaeI#pwCV~gdos1(rr4A$#1ZDCC|+r(Un!&X_i>M>f?QPdt;K ztKVTQvB-UjHbLLr5R!UOT&AjbadTe9c*;dQHb k*4+6HnkaM=-x)b=-hR?ZL3{kB%PW#N{aEg%*OE{C4FHyx0ssI2 diff --git a/index.ts b/index.ts deleted file mode 100644 index 1dd5fb8..0000000 --- a/index.ts +++ /dev/null @@ -1,52 +0,0 @@ -import sharp, { type OverlayOptions } from 'sharp'; -import { LAYERS, weightedChoice } from './layers'; - -const BASE_SHAPE_PATH = './assets/base_shape.png'; - -export type Trait = 'skin' | 'nose' | 'eyes' | 'mouth' | 'detail'; - -export type Layer = { - trait: Trait, - path: string, - chance?: number, - options: TraitOption[] -}; - -export type TraitOption = { - fileName: string, - weight?: number -}; - -async function generateRandomImage(fileName: string, orderedLayers: Layer[]) { - const layers: { input: string }[] = []; - - for (const layer of orderedLayers) { - if (layer.chance && Math.random() > layer.chance) { - continue; - } - - const choice = weightedChoice(layer.options); - - layers.push({ input: `${layer.path}${choice}` }); - } - - const image = sharp(BASE_SHAPE_PATH).composite(layers); - - await Bun.write(`./output/${fileName}`, await image.toBuffer()); -} - -for (let i = 0; i < 100; i++) { - await generateRandomImage(`characters/${i}.png`, LAYERS); -} - -// combine into a single grid image -const characters: OverlayOptions[] = []; -for (let i = 0; i < 100; i++) { - characters.push({ input: `./output/characters/${i}.png`, left: (i % 10) * 16, top: Math.floor(i / 10.0) * 16 }); -} - -const grid = sharp({ create: { width: 160, height: 160, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } } }).composite(characters).png(); - -await Bun.write('./output/grid.png', await grid.toBuffer()); - -console.log('Finished generation'); diff --git a/layers.ts b/layers.ts deleted file mode 100644 index cd6dc81..0000000 --- a/layers.ts +++ /dev/null @@ -1,72 +0,0 @@ -import type { Layer, TraitOption } from "."; - -export const LAYERS: Layer[] = [ - { - trait: 'skin', - path: './assets/skin/', - options: [ - { fileName: 'sand.png' }, - { fileName: 'sienna.png' }, - { fileName: 'bole.png' }, - { fileName: 'chocolate.png' } - ] - }, - { - trait: 'nose', - path: './assets/nose/', - options: [ - { fileName: 'small.png' }, - { fileName: 'big.png' } - ] - }, - { - trait: 'eyes', - path: './assets/eyes/', - options: [ - { fileName: 'blue.png', weight: 27 }, - { fileName: 'green.png', weight: 9 }, - { fileName: 'brown.png', weight: 19 }, - { fileName: 'dark_brown.png', weight: 45 } - ] - }, - { - trait: 'mouth', - path: './assets/mouth/', - options: [ - { fileName: 'neutral.png', weight: 8 }, - { fileName: 'happy.png', weight: 4 }, - { fileName: 'smirk.png', weight: 2 }, - { fileName: 'shock.png', weight: 1 } - ] - }, - { - trait: 'detail', - chance: 0.1, - path: './assets/detail/', - options: [ - { fileName: 'halo.png', weight: 1 }, - { fileName: 'red_beanie.png', weight: 25 }, - { fileName: 'green_beanie.png', weight: 25 } - ] - } -]; - -export function weightedChoice(options: TraitOption[]): string { - let i; - - let weights: number[] = [options[0].weight ?? 1]; - - for (i = 1; i < options.length; i++) { - weights[i] = (options[i].weight ?? 1) + weights[i - 1]; - } - - const random = Math.random() * weights[weights.length - 1]; - - for (i = 0; i < weights.length; i++) { - if (weights[i] > random) { - break; - } - } - - return options[i].fileName; -} diff --git a/package.json b/package.json index 248cab0..9cce532 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,38 @@ { - "name": "generative-art", - "module": "index.ts", - "devDependencies": { - "@types/bun": "latest" - }, - "peerDependencies": { - "typescript": "^5.0.0" - }, - "type": "module", - "dependencies": { - "sharp": "^0.33.2" - } -} \ No newline at end of file + "name": "layered-generative-art", + "description": "An easy-to-use library to generate random images from a set of layers", + "version": "1.0.0", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "author": "409", + "type": "module", + "module": "index.ts", + "license": "MIT", + "files": [ + "dist" + ], + "keywords": [ + "generative", + "random", + "art", + "image", + "images", + "generative-art" + ], + "homepage": "https://github.com/4-0-9/layered-generative-art", + "repository": { + "type": "git", + "url": "git+https://github.com/4-0-9/layered-generative-art.git" + }, + "bugs": "https://github.com/4-0-9/layered-generative-art/issues", + "dependencies": { + "sharp": "^0.33.2" + }, + "peerDependencies": { + "typescript": "^5.0.0" + }, + "devDependencies": { + "@types/bun": "latest", + "bun-plugin-dts": "^0.2.1" + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..ff1787e --- /dev/null +++ b/src/index.ts @@ -0,0 +1,60 @@ +import sharp, { type OverlayOptions } from 'sharp'; +import { type Layer, type TraitOption } from './layers'; + +/** Generates a random image from a base shape and a set of layers + * @param baseShapePath - The path to the base shape of the image. This image determines the resolution of the image. (set this to a transparent image if you don't want a base shape) + * @param orderedLayers - The layers to choose from in ascending order + * @returns A buffer containing the newly generated image + */ +async function generateRandomImage(baseShapePath: string, orderedLayers: Layer[]): Promise { + const layers: OverlayOptions[] = []; + const choices: Record = {}; + + for (const layer of orderedLayers) { + if (layer.probability && Math.random() > layer.probability) { + continue; + } + + const choice = weightedChoice(layer.options); + + layers.push({ input: `${layer.path}${choice.fileName}` }); + choices[layer.traitName] = choice.name; + } + + const image = sharp(baseShapePath).composite(layers); + + const buffer = await image.toBuffer(); + return { buffer: buffer, choices }; +} + + +// https://stackoverflow.com/questions/43566019/how-to-choose-a-weighted-random-array-element-in-javascript +function weightedChoice(options: TraitOption[]): TraitOption { + let i; + + let weights: number[] = [options[0].weight ?? 1]; + + for (i = 1; i < options.length; i++) { + weights[i] = (options[i].weight ?? 1) + weights[i - 1]; + } + + const random = Math.random() * weights[weights.length - 1]; + + for (i = 0; i < weights.length; i++) { + if (weights[i] > random) { + break; + } + } + + return options[i]; +} + +/** + * A piece of randomly generated art + */ +export type GenerativeArtOutput = { + /** The buffer containing the image */ + buffer: Buffer, + /** An object mapping traits to the choices' names. If a layer was not used due the probability field it will **not** be present in this object */ + choices: Record, +}; diff --git a/src/layers.ts b/src/layers.ts new file mode 100644 index 0000000..18f991a --- /dev/null +++ b/src/layers.ts @@ -0,0 +1,25 @@ +/** + * A generative art layer + */ +export type Layer = { + /** The trait's name */ + traitName: string, + /** The base path (**use trailing slash**, e.g. ./assets/eyes/) */ + path: string, + /** The probability of this trait occouring. Range: 0.0-1.0 (e.g. 0.5 for 50%). **Defaults to 1.0** */ + probability?: number, + /** The options to randomly pick from. Can optionally contain weights to increase certain options' rarity */ + options: TraitOption[] +}; + +/** + * A trait option with an optional weight + */ +export type TraitOption = { + /** The option's name (e.g: 'Blue') */ + name: string, + /** The option's file name (e.g.: 'blue_eyes.png') */ + fileName: string, + /** The option's weight. Defaults to 1 */ + weight?: number +};