Welcome in my X-mas tree showroom! Feel free to configure your own tree using the sliders and if you really like one: let me know in the comments and I'll throw in an extra ball or two! Merry Christmas!
Notes:
- Setting 'seed' to 0 makes it a dynamic seed
- The 'New turtle'-star is featured as the tree topper
2022: Merry Christmas 🌲
Log in to post a comment.
const seed = 2023; //min=0 max=7000 step=7 const storeys = 8; //min=3 max=15 step=1 const sawLikeTree = .4; //min=0 max=1 step=.01 const branchTrim = 0.3;//min=0 max=.5 step=.05 const branchCpLength = .4; //min=0 max=2 step=.05 const topTrim = 0.4; //min=0 max=.5 step=.05 const topCpLength = .4; //min=0 max=2 step=.05 const ballsProbability = 150; //min=0 max=500 step=10 const ballHatching = 2; //min=0 max=2 step=1 (Lines, Circular, Both) const ballTypeChange = 0; //min=0 max=1 step=.05 const topperSpikes = 5; //min=5 max=13 step=1 const topperRotate = .25; //min=0 max=1 step=.01 const penThickness = 1; //min=.15 max=4 step=.01 const widthCorrection = 1; //min=.5 max=1.5 step=.01 const plotBackground = 1; //min=0 max=1 step=1 (No, Yes) // You can find the Turtle API reference here: https://turtletoy.net/syntax Canvas.setpenopacity(.7); // Seedable random number generator by David Bau: http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html !function(a,b,c,d,e,f,g,h,i){function j(a){var b,c=a.length,e=this,f=0,g=e.i=e.j=0,h=e.S=[];for(c||(a=[c++]);d>f;)h[f]=f++;for(f=0;d>f;f++)h[f]=h[g=s&g+a[f%c]+(b=h[f])],h[g]=b;(e.g=function(a){for(var b,c=0,f=e.i,g=e.j,h=e.S;a--;)b=h[f=s&f+1],c=c*d+h[s&(h[f]=h[g=s&g+b])+(h[g]=b)];return e.i=f,e.j=g,c})(d)}function k(a,b){var c,d=[],e=typeof a;if(b&&"object"==e)for(c in a)try{d.push(k(a[c],b-1))}catch(f){}return d.length?d:"string"==e?a:a+"\0"}function l(a,b){for(var c,d=a+"",e=0;e<d.length;)b[s&e]=s&(c^=19*b[s&e])+d.charCodeAt(e++);return n(b)}function m(c){try{return o?n(o.randomBytes(d)):(a.crypto.getRandomValues(c=new Uint8Array(d)),n(c))}catch(e){return[+new Date,a,(c=a.navigator)&&c.plugins,a.screen,n(b)]}}function n(a){return String.fromCharCode.apply(0,a)}var o,p=c.pow(d,e),q=c.pow(2,f),r=2*q,s=d-1,t=c["seed"+i]=function(a,f,g){var h=[];f=1==f?{entropy:!0}:f||{};var o=l(k(f.entropy?[a,n(b)]:null==a?m():a,3),h),s=new j(h);return l(n(s.S),b),(f.pass||g||function(a,b,d){return d?(c[i]=a,b):a})(function(){for(var a=s.g(e),b=p,c=0;q>a;)a=(a+c)*d,b*=d,c=s.g(1);for(;a>=r;)a/=2,b/=2,c>>>=1;return(a+c)/b},o,"global"in f?f.global:this==c)};if(l(c[i](),b),g&&g.exports){g.exports=t;try{o=require("crypto")}catch(u){}}else h&&h.amd&&h(function(){return t})}(this,[],Math,256,6,52,"object"==typeof module&&module,"function"==typeof define&&define,"random"); Math.seedrandom(''+ (seed == 0? Date.now(): 'Merry Christmas!' + seed)); // Add a seed in seedrandom, then Math.random will use this seed // Global code will be evaluated once. const turtle = new Turtle(); const polygons = new Polygons(); const upd = new UniformPointDistributor().getPointIterator(() => 3 + Math.random() * 4); const treeStoreyPaths = []; let ptr = 0; let topperBigR = 15; // The walk function will be called until it returns false. function walk(i) { const trans = pt => add2(pt, [0, -82]); if(i < storeys) { //calculate tree polygon paths const size = ((minSize, maxSize) => minSize + (maxSize - minSize) * i / (storeys - 1))(18, 74); const storeyY = ((startY, maxY) => startY + (maxY - startY) * i / (storeys - 1))(-70, 10); treeStoreyPaths.push(getXMasTreeStoreyPts(size).map(pt => mul2(add2(pt, [0, storeyY]), [widthCorrection, 1]))) } else if(i == storeys) { //draw the star const outer = circlePoints(topperBigR, 2 * Math.PI, 0, topperSpikes); const inner = circlePoints((topperSpikes % 2 == 1?6 * topperBigR/15: 8.5*topperBigR/15), 2 * Math.PI, Math.PI / topperSpikes, topperSpikes); const path = Array.from({length: outer.length}).flatMap((v, i) => [outer[i], inner[i]]); drawPolygon(path.map(pt => trans( trans2(rot2(topperRotate * 2 * Math.PI / topperSpikes), pt) ))); // featuring the (new-turtle) star const dev = [2, 3, 2, 1.5, 2, 1.5, 2, 1.6, 2][topperSpikes - 5]; const newTurtleStar = circlePoints(9, 2 * Math.PI, 0, topperSpikes); const maxLoops = (topperSpikes == 6 || topperSpikes == 10)? 2: 1; for(let ii = 0; ii < maxLoops; ii++) { const rot = rot2(2 * ii * Math.PI / topperSpikes + (topperRotate * 2 * Math.PI / topperSpikes)); const nts = newTurtleStar.map(pt => trans2(rot, pt)).map(pt => trans(pt)) turtle.jump(nts[nts.length - Math.floor(topperSpikes / dev)]); nts.forEach((v, i, a) => (maxLoops == 1 || i < a.length / 2)? turtle.goto(a[(i * Math.floor(topperSpikes / dev)) % a.length]): false); } } else if(i == storeys + 1) { //draw balls const minBallY = trans([0,0])[1] + topperBigR; const treeStoreyEdges = treeStoreyPaths.map(p => pts2Edges(p)); const balls = Array.from({length: ballsProbability}) .map(i => upd.next().value) .filter(pt => pt[1] > minBallY && treeStoreyEdges.some(path => isInPolygon(path, pt))) .forEach(pt => { const typehatch = (Math.random() * (ballHatching == 0? 3: 4)) | 0; const hatch = ballHatching == 1? 3: typehatch; const ballType = /* hatch == 3? 1: */(() => Math.random() < ballTypeChange? .5 + (ballTypeChange > .5? 1 - ballTypeChange: .5) * Math.random(): 1)(); const ballPath = circlePoints(pt[2]).map(c => mul2(c, [ballType, 1])).map(c => add2(add2(pt, [0, pt[2]]), c)); switch(hatch) { case 0: case 1: case 2: drawPolygon( ballPath, Array.from({length: 1 + hatch}).map(v => [Math.random() * Math.PI, .4 + Math.random() * 1.5]) ) break; case 3: const spacing = penThickness * (.4 + Math.random() * .75); const rounds = (pt[2] / spacing) | 0; for(let i = 0, r = pt[2] - rounds * spacing; i < rounds; i++, r += spacing) { drawPolygon( circlePoints(r,2 * Math.PI, 0, steps = Math.max(8, 2*Math.PI*r|0)).map(c => mul2(c, [ballType, 1])).map(c => add2(add2(pt, [0, pt[2]]), c)) ) } drawPolygon(ballPath); break; } }); } else if ( ptr < treeStoreyPaths.length ) { drawPolygon( treeStoreyPaths[ptr++], [[i%2 == 1? 1: 2, .5 + Math.random() * .1]] ); //draw the tree } else { const mY = treeStoreyPaths[1].reduce((p, c) => p>c[1]?p:c[1], -100); drawPolygon( treeStoreyPaths[1].map(pt => add2(pt, [0, 90 - mY])), [[1, .25]] ); //foot of tree if(plotBackground == '1') { drawPolygon( [[-101, 33], [-101, -101], [101, -101], [101, 33]], [[1, .5], [2, .5]] ); //sky drawPolygon( [[-101, 101], [-101, -101], [101, -101], [101, 101]], [[0, 1.5]] ); //floor } return false; } return true; } function drawPolygon(polygon, hatching = []) { const p = polygons.create(); p.addPoints(...polygon); p.addOutline(); hatching.forEach(h => p.addHatching(...mul2(h, [1, penThickness]))) polygons.draw(turtle, p); } function getXMasTreeStoreyPts(size = 40) { const bottom = circlePoints(size * 2, Math.PI / 2, Math.PI / 4, null, true) .map(pt => mul2(pt, [1, .5])); const rightSide = getBezierPathByControlVectors( [0,-size], bottom[0], [0, size * (1 + sawLikeTree)], [-size * sawLikeTree, 0] ); const rSide = trimPath(rightSide, 0, (topTrim * size) | 0); const rBottom = trimPath(bottom, (branchTrim * size) | 0, (branchTrim * size) | 0); const rTip = getBezierPathByControlVectors( rSide[rSide.length - 1], rBottom[0], scale2(sub2(bottom[0], rSide[rSide.length - 1]), topCpLength), scale2(sub2(bottom[0], rBottom[0]), branchCpLength), ).filter((v, i, a) => 0 < i && i < a.length - 1); return [ ...rSide.filter((v, i) => i != 0), ...rTip, ...rBottom, ...rTip.reverse().map(pt => mul2(pt, [-1, 1])), ...rSide.reverse().map(pt => mul2(pt, [-1, 1])) ]; } /// Below is the standard lib I just copy paste under almost all my turtles function approx1(a,b,delta=0.0001) { return -delta < a-b && a-b < delta } //////////////////////////////////////////////////////////////// // 2D Vector Math utility code - Created by several Turtletoy users //////////////////////////////////////////////////////////////// function norm2(a) { return scale2(a, 1/len2(a)); } function add2(a, b) { return [a[0]+b[0], a[1]+b[1]]; } function sub2(a, b) { return [a[0]-b[0], a[1]-b[1]]; } function mul2(a, b) { return [a[0]*b[0], a[1]*b[1]]; } function scale2(a, s) { return [a[0]*s,a[1]*s]; } function lerp2(a,b,t) { return [a[0]*(1-t) + b[0]*t, a[1]*(1-t) + b[1]*t]; } function lenSq2(a) { return a[0]**2+a[1]**2; } function len2(a) { return Math.sqrt(lenSq2(a)); } function rot2(a) { return [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a)]; } function trans2(m, a) { return [m[0]*a[0]+m[2]*a[1], m[1]*a[0]+m[3]*a[1]]; } //Matrix(2x1) x Matrix(2x2) function dist2(a,b) { return Math.hypot(...sub2(a,b)); } function dot2(a,b) { return a[0]*b[0]+a[1]*b[1]; } function cross2(a,b) { return a[0]*b[1] - a[1]*b[0]; } function multiply2(a2x2, a) { return [(a[0]*a2x2[0])+(a[1]*a2x2[1]),(a[0]*a2x2[2])+(a[1]*a2x2[3])]; } //Matrix(2x2) x Matrix(1x2) function intersect_info2(as, ad, bs, bd) { const d = [bs[0] - as[0], bs[1] - as[1]]; const det = bd[0] * ad[1] - bd[1] * ad[0]; if(det === 0) return false; const res = [(d[1] * bd[0] - d[0] * bd[1]) / det, (d[1] * ad[0] - d[0] * ad[1]) / det]; return [...res, add2(as, scale2(ad, res[0]))]; } function intersect_ray2(a, b, c, d) { const i = intersect_info2(a, b, c, d); return i === false? i: i[2]; } function segment_intersect2(a,b,c,d, inclusive = true) { const i = intersect_info2(a, sub2(b, a), c, sub2(d, c)); if(i === false) return false; const t = inclusive? 0<=i[0]&&i[0]<=1&&0<=i[1]&&i[1]<=1: 0<i[0]&&i[0]<1&&0<i[1]&&i[1]<1; return t?i[2]:false; } function approx2(a,b,delta=0.0001) { return len2(sub2(a,b)) < delta } function eq2(a,b) { return a[0]==b[0]&&a[1]==b[1]; } function clamp2(a, tl, br) { return [Math.max(Math.min(br[0], a[0]), tl[0]), Math.max(Math.min(br[1], a[1]), tl[1])]; } function nearSq2(test, near, delta = .0001) { return near[0] - delta < test[0] && test[0] < near[0] + delta && near[1] - delta < test[1] && test[1] < near[1] + delta; } //////////////////////////////////////////////////////////////// // Start of some path utility code - Created by Jurgen Westerhof 2023 //////////////////////////////////////////////////////////////// function circlePoints(radius, extend = 2 * Math.PI, clockWiseStart = 0, steps = null, includeLast = false) { return [steps == null? (radius*extend+1)|0: steps].map(steps => Array.from({length: steps}).map((v, i, a) => [radius * Math.cos(clockWiseStart + extend*i/(a.length-(includeLast?1:0))), radius * Math.sin(clockWiseStart + extend*i/(a.length-(includeLast?1:0)))])).pop(); } function pts2Edges(pts) { return pts.map((v, i, a) => [v, a[(i+1)%a.length]]); } function drawPath(turtle, pts) { return pts.forEach((pt, i) => turtle[i == 0? 'jump':'goto'](pt)); } function drawTour(turtle, pts) { return drawPath(turtle, pts.concat([pts[0]])); } function drawPoint(turtle, pt) { return drawTour(turtle, circlePoints(.5).map(p => add2(p, pt))); } function isInPolygon(edges, pt) { return edges.map(edge => intersect_info2(edge[0], sub2(edge[1], edge[0]), pt, [0, 300])).filter(ii => ii !== false && 0 <= ii[0] && ii[0] <= 1 && 0 < ii[1]).length % 2 == 1; } function isInVectorTour(vectors, pt) { return vectors.map(v => intersect_info2(...v, pt[0], pt[1])).filter(ii => ii !== false && 0 <= ii[0] && ii[0] < 1 && 0 <= ii[1]).length % 2 == 1; } function tourToVectors(path) { return path.map((v, i, a) => [v, sub2(a[(i+1)%a.length], v)]); } function thickLinePaths(from, to, thickness) { return [trans2(rot2(Math.atan2(...sub2(to, from))), [thickness/2, 0])].map(v => [[add2(from, v), add2(to, v)], [sub2(from, v), sub2(to, v)]]).pop();} function toursIntersect(path1, path2) { return path1.some((pt1, i1) => path2.some((pt2, i2) => segment_intersect2(pt1, path1[(i1 + 1) % path1.length], pt2, path2[(i2 + 1) % path2.length]) !== false)); } function pathsIntersect(path1, path2) { return path1.some((pt1, i1) => i1 == path1.length - 1? false: path2.some((pt2, i2) => i2 == path2.length - 1? false: segment_intersect2(pt1, path1[i1 + 1], pt2, path2[i2 + 1]) !== false ) ); } function pathsIntersections(path1, path2) { return path1.flatMap((pt1, i1) => i1 == path1.length - 1? [[false]]: path2.map((pt2, i2) => i2 == path2.length - 1? [false]: [segment_intersect2(pt1, path1[i1 + 1], pt2, path2[i2 + 1]), i1, i2] ) ).filter(v => v[0] !== false); } function getBezierPathByControlVectors(p1, p2, v1, v2, steps = null) { return getBezierPath(p1, p2, add2(p1, v1), add2(p2, v2), steps); } function getBezierPath(p1, p2, cp, cp2 = null, steps = null) { cp2 = cp2 === null? [...cp]: cp2; const v1 = sub2(cp, p1); const v2 = sub2(cp2, cp); const v3 = sub2(p2, cp2); if(steps === null) { steps = (len2(v1) + len2(v2) + len2(v3)) | 0; } steps--; const result = [[...p1]]; for(let i = 1; i <= steps; i++) { const fraction = i / steps; const pp1 = add2( p1, scale2(v1, fraction) ); const pp2 = add2( cp, scale2(v2, fraction) ); const pp3 = add2( cp2, scale2(v3, fraction) ); const vv1 = sub2( pp2, pp1 ); const vv2 = sub2( pp3, pp2 ); const ppp1 = add2( pp1, scale2(vv1, fraction)); const ppp2 = add2( pp2, scale2(vv2, fraction)); const vvv1 = sub2( ppp2, ppp1 ); result.push( add2( ppp1, scale2( vvv1, fraction )) ); } return result; } function pathLength(path) { return path.reduce((p, c) => [p[0] + len2(sub2(p[1], c)), c], [0, path[0]])[0]; } function trimPath(path, stripFromStart = 0, stripFromEnd = 0, relative = false) { if(stripFromStart < 0 || stripFromEnd < 0) throw new Error('Cannot trim by negative length'); if(path.length < 2) throw new Error('Not a valid path'); const pathLengths = path.map((v, i, a) => len2(sub2(v, a[(i+1)%a.length]))); pathLengths.pop(); const totalLength = pathLengths.reduce((p, c) => p+c, 0); if(relative) { stripFromStart = stripFromStart * totalLength; stripFromEnd = stripFromEnd * totalLength; } if(totalLength < stripFromStart + stripFromEnd) return []; const copiedPath = path.map(pt => [...pt]); while(true) { if(pathLengths.length == 0) return []; const cLength = pathLengths.pop(); const cPoint = copiedPath.pop(); stripFromEnd -= cLength; if(0 <= stripFromEnd) continue; copiedPath.push(lerp2( copiedPath[copiedPath.length - 1], cPoint, -stripFromEnd / cLength )); //pathLengths.push(-stripFromEnd); break; } while(true) { if(pathLengths.length == 0) return []; const cLength = pathLengths.shift(); const cPoint = copiedPath.shift(); stripFromStart -= cLength; if(0 <= stripFromStart) continue; copiedPath.unshift(lerp2( copiedPath[0], cPoint, -stripFromStart / cLength )); //pathLengths.push(-stripFromStart); break; } return copiedPath; } function uniformlyDistributePath(path, steps = null) { if(steps !== null && steps < 2) throw new Error('Cannot distribute length over less than 2 points'); if(path.length < 2) throw new Error('Not a valid path'); const pathLengths = path.map((v, i, a) => len2(sub2(v, a[(i+1)%a.length]))); pathLengths.pop(); const totalLength = pathLengths.reduce((p, c) => p+c, 0); if(steps == null) steps = totalLength | 0; const lengthPerStep = totalLength / steps; const copiedPath = path.map(pt => [...pt]); const resultPath = [copiedPath[0]]; let remainingLength = lengthPerStep; for(let i = 0; i < pathLengths.length; i++) { if(pathLengths[i] < remainingLength) { remainingLength -= pathLengths[i]; continue; } const newPoint = lerp2( copiedPath[i], copiedPath[i + 1], remainingLength / pathLengths[i] ); resultPath.push(newPoint); copiedPath[i] = newPoint; pathLengths[i] -= remainingLength; remainingLength = lengthPerStep; i--; } if(resultPath.length == steps + 1) { resultPath.pop(); } resultPath.push([...path[path.length - 1]]); resultPath.forEach((pt, i, a) => drawPoint(turtle, pt)); return resultPath; } // Fisher-Yates (aka Knuth) Shuffle // https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array#2450976 function shuffle(array) { let currentIndex = array.length, randomIndex; // While there remain elements to shuffle. while (currentIndex > 0) { // Pick a remaining element. randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex]]; } return array; } //////////////////////////////////////////////////////////////// // Polygon Clipping utility code - Created by Reinder Nijhoff 2019 // (Polygon binning by Lionel Lemarie 2021) // https://turtletoy.net/turtle/a5befa1f8d //////////////////////////////////////////////////////////////// function Polygons(){const t=[],s=25,e=Array.from({length:s**2},t=>[]),n=class{constructor(){this.cp=[],this.dp=[],this.aabb=[]}addPoints(...t){let s=1e5,e=-1e5,n=1e5,h=-1e5;(this.cp=[...this.cp,...t]).forEach(t=>{s=Math.min(s,t[0]),e=Math.max(e,t[0]),n=Math.min(n,t[1]),h=Math.max(h,t[1])}),this.aabb=[s,n,e,h]}addSegments(...t){t.forEach(t=>this.dp.push(t))}addOutline(){for(let t=0,s=this.cp.length;t<s;t++)this.dp.push(this.cp[t],this.cp[(t+1)%s])}draw(t){for(let s=0,e=this.dp.length;s<e;s+=2)t.jump(this.dp[s]),t.goto(this.dp[s+1])}addHatching(t,s){const e=new n;e.cp.push([-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);const h=Math.sin(t)*s,o=Math.cos(t)*s,a=200*Math.sin(t),i=200*Math.cos(t);for(let t=.5;t<150/s;t++)e.dp.push([h*t+i,o*t-a],[h*t-i,o*t+a]),e.dp.push([-h*t+i,-o*t-a],[-h*t-i,-o*t+a]);e.boolean(this,!1),this.dp=[...this.dp,...e.dp]}inside(t){let s=0;for(let e=0,n=this.cp.length;e<n;e++)this.segment_intersect(t,[.1,-1e3],this.cp[e],this.cp[(e+1)%n])&&s++;return 1&s}boolean(t,s=!0){const e=[];for(let n=0,h=this.dp.length;n<h;n+=2){const h=this.dp[n],o=this.dp[n+1],a=[];for(let s=0,e=t.cp.length;s<e;s++){const n=this.segment_intersect(h,o,t.cp[s],t.cp[(s+1)%e]);!1!==n&&a.push(n)}if(0===a.length)s===!t.inside(h)&&e.push(h,o);else{a.push(h,o);const n=o[0]-h[0],i=o[1]-h[1];a.sort((t,s)=>(t[0]-h[0])*n+(t[1]-h[1])*i-(s[0]-h[0])*n-(s[1]-h[1])*i);for(let n=0;n<a.length-1;n++)(a[n][0]-a[n+1][0])**2+(a[n][1]-a[n+1][1])**2>=.001&&s===!t.inside([(a[n][0]+a[n+1][0])/2,(a[n][1]+a[n+1][1])/2])&&e.push(a[n],a[n+1])}}return(this.dp=e).length>0}segment_intersect(t,s,e,n){const h=(n[1]-e[1])*(s[0]-t[0])-(n[0]-e[0])*(s[1]-t[1]);if(0===h)return!1;const o=((n[0]-e[0])*(t[1]-e[1])-(n[1]-e[1])*(t[0]-e[0]))/h,a=((s[0]-t[0])*(t[1]-e[1])-(s[1]-t[1])*(t[0]-e[0]))/h;return o>=0&&o<=1&&a>=0&&a<=1&&[t[0]+o*(s[0]-t[0]),t[1]+o*(s[1]-t[1])]}};return{list:()=>t,create:()=>new n,draw:(n,h,o=!0)=>{reducedPolygonList=function(n){const h={},o=200/s;for(var a=0;a<s;a++){const c=a*o-100,r=[0,c,200,c+o];if(!(n[3]<r[1]||n[1]>r[3]))for(var i=0;i<s;i++){const c=i*o-100;r[0]=c,r[2]=c+o,n[0]>r[2]||n[2]<r[0]||e[i+a*s].forEach(s=>{const e=t[s];n[3]<e.aabb[1]||n[1]>e.aabb[3]||n[0]>e.aabb[2]||n[2]<e.aabb[0]||(h[s]=1)})}}return Array.from(Object.keys(h),s=>t[s])}(h.aabb);for(let t=0;t<reducedPolygonList.length&&h.boolean(reducedPolygonList[t]);t++);h.draw(n),o&&function(n){t.push(n);const h=t.length-1,o=200/s;e.forEach((t,e)=>{const a=e%s*o-100,i=(e/s|0)*o-100,c=[a,i,a+o,i+o];c[3]<n.aabb[1]||c[1]>n.aabb[3]||c[0]>n.aabb[2]||c[2]<n.aabb[0]||t.push(h)})}(h)}}} //////////////////////////////////////////////////////////////// // Uniform Point Distribution code - Created by Jurgen Westerhof 2023 //////////////////////////////////////////////////////////////// function UniformPointDistributor(leftTop = [-100, -100], rightBottom = [100, 100]) { class UniformPointDistributor { constructor(leftTop = [-100, -100], rightBottom = [100, 100]) { this.leftTop = leftTop; this.rightBottom = rightBottom; this.width = rightBottom[0]-leftTop[0]; this.height = rightBottom[1]-leftTop[1]; this.maxDist = (this.width**2+this.height**2)**.5; this.pts = []; } *getPointIterator(radiusFunction = null, candidates = 20, maxTries = 1000) { if(radiusFunction == null) radiusFunction = (x, y, maximum) => 0; const randomPoint = () => [Math.random()*this.width+this.leftTop[0],Math.random()*this.height+this.leftTop[1]]; this.pts.push([randomPoint()].map(pt => [...pt, radiusFunction(...pt)])[0]); yield this.pts[this.pts.length - 1]; while(true) { let pt = [0,0,-1]; let tries = 0; while(pt[2] < 0 && tries < maxTries) { tries++; //using [length] candidate points pt = Array.from({length: candidates}) //which are random points .map(i => randomPoint()) //then add the distance to that candidate minus the radius of each point it is compared to .map(i => [i[0], i[1], this.pts.map(j => [j[0], j[1], Math.hypot(i[0]-j[0], i[1]-j[1]) - j[2]]) //so that it is the smallest distance from the //candidate to any of the already chosen points .reduce((prev, current) => (current[2] < prev[2])? current: prev, [0,0,this.maxDist])[2] ]) //then pick the candidate that has the largest minimum distance from the group of candidates .reduce((prev, current) => prev == null? current: ((current[2] > prev[2])? current: prev), null) //and set the 3rd position to its own radius instead of the distance to the nearest point .map((v, i, arr) => i < 2? v: radiusFunction(arr[0], arr[1], v)) ////and remove the distance before promoting the candidate //.filter((i, k) => k < 2) } if(tries == maxTries) return false; //add a point to the list this.pts.push(pt); yield pt; } } } return new UniformPointDistributor(leftTop, rightBottom); }