Skip to content

Instantly share code, notes, and snippets.

@rozek
Last active December 6, 2019 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rozek/b91fbe5e8921a1aca87553ee5f81f693 to your computer and use it in GitHub Desktop.
Save rozek/b91fbe5e8921a1aca87553ee5f81f693 to your computer and use it in GitHub Desktop.
Bangle.js: displays the famous Mandelbrot set
Bangle.setLCDMode(); // use normal display mode
g.clear();
const Width = g.getWidth();
const Height = g.getHeight();
/**** color mapping (especially for Bangle.js) ****/
function rgb565 (r,g,b) {
return (r << 11) | (g << 5) | b;
}
let ColorMap = [0]; // not part of Mandelbrot set? then leave pixel black
for (let i = 1; i <= 4; i++) { // make low escape times distiguishable
ColorMap.push(rgb565(4*i,4*2*i+1,31));
}
for (let i = 4*4+1; i < 32; i++) { // extend map for more details
ColorMap.push(rgb565(i,2*i+1,31));
}
const ColorCount = ColorMap.length;
/**** EscapeTimeOf ****/
const maxIterations = ColorCount;
/*
function EscapeTimeOf (x,y) { // unoptimized
let re = x, imag = y;
for (let i = 0; i < maxIterations; i++) {
let newRe = re*re - imag*imag + x;
let newImag = 2*re*imag + y;
re = newRe; imag = newImag;
if (re*re + imag*imag > 2) { return i }
}
return 0;
}
*/
function EscapeTimeOf (x,y) { // slightly optimized
let re = x, imag = y;
let r2 = x*x, i2 = y*y, z2 = (x+y)*(x+y);
for (let i = 0; i < maxIterations; i++) {
let newRe = r2 - i2 + x;
let newImag = z2 - r2 - i2 + y;
r2 = newRe*newRe;
i2 = newImag*newImag;
z2 = (newRe+newImag)*(newRe+newImag);
if (r2 + i2 > 4) { return i }
}
return 0;
}
/**** draw Mandelbrot set ****/
const xOffset = -1.9; const Zoom = 100;
const yOffset = -1.2;
for (let y = 0; y < Height; y++) {
for (let x = 0; x < Width; x++) {
let EscapeTime = EscapeTimeOf(
xOffset + x/Zoom, yOffset + y/Zoom
);
if (EscapeTime > 0) {
g.setPixel(x,y,ColorMap[EscapeTime]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment