Showing posts with label sphere. Show all posts
Showing posts with label sphere. Show all posts

Wednesday, June 13, 2018

Flower Shape Path / Fourier series

Generates a path 
in the shape of a Fourier series flower.
Compounding random amplifications for each octave.
random number of octaves and repeating symmetries 
Non Self intersecting path for any values. 


Usage:


function FlowerF(r=100,isteps=5,w,a,h=2,h2)=
let(steps=min(isteps*w,300))
[  for(t=[0:1/steps:1])
let( r2= r*1.05+vsum([
for (k = [h2:h:max(9,22-w)])     a[k]*(sin(k*t*w*360)/k)*r] ),
  x =r2* sin(t*360), 
 y =r2* cos(t*360)  )
[x,y] ];




module polyline(p) {for(i=[0:max(0,len(p)-2)])line(p[i],p[i+1]);}
module line(p1, p2 ,width=0.5) 
{
    hull() {
        translate(p1) sphere(width);
        translate(p2) sphere(width);
    }
}

a=concat([rnd(0.5),rnd(0.75)],[for (k = [0:1:30])rnd(1)]);
p= (FlowerF(100,200,
    round(rnd(0,3))*2+1,a,
     min(2,round(rnd(1,3))),min(2,round(rnd(1,3)))));
 
polygon(p); 
//polyline(p); 
// function close adds a last point equal yo the first function close(p)= concat(p,[p[0]]); function rnd(a = 1, b = 0, s = []) = s == [] ? (rands(min(a, b), max( a, b), 1)[0]) : (rands(min(a, b), max(a, b), 1, s)[0]); function vsum(l) = len(l) > 0 ? [ for(li=l) 1 ] * l : undef;



 



Friday, August 18, 2017

Points inside a ellipsoid

Generates a list of random points that lie inside a ellipsoid

function random_points_inside_ellipsoid(rx,ry,rz,n)=
[for(i=[1:n])ellipsoid_point(rx,ry,rz)];

function ellipsoid_point(rx,ry,rz)=
let (
r=[rx,ry,rz],
p=[
rands(-rx,rx,1)[0],
rands(-ry,ry,1)[0],
rands(-rz,rz,1)[0] 
] ,
d= ((
sq2(p.x)/sq2(r.x)+
sq2(p.y)/sq2(r.y)+
sq2(p.z)/sq2(r.z)) - 1) * min(r.x,r.y,r.z)  ) 
 (d)>0?ellipsoid_point(rx,ry,rz):p;
function sq2(v)=pow(v,2);

p=random_points_inside_ellipsoid(50,50,100,1000);
for(t=p)translate(t)sphere(4);
echo(p);
 

Tuesday, August 8, 2017

Points Inside A Cylinder


Generates a list of random points that lie inside a cylinder

function random_points_inside_cylinder(r,h,n)=
[for(i=[1:n])cylinder_point(r,h)];

function cylinder_point(r,h)=
let (p=[
rands(-r,r,1)[0],
rands(-r,r,1)[0],
rands(0,h,1)[0] ],
d=(pow(p.x,2) + pow(p.y,2) )) 
d > pow(r,2)?cylinder_point(r,h):p;


p=random_points_inside_cylinder(50,100,1000);
for(t=p)translate(t)sphere(4);
echo(p);
 

Sunday, August 6, 2017

Points inside a tube


Generates a list of random points that lie inside a tube

function random_points_inside_tube(r,r2,h,n)=
          [for(i=[1:n])tube_point(r,r2,h)];

function tube_point(r,r2,h)=
let (p=[
rands(-r,r,1)[0],
rands(-r,r,1)[0],
rands(0,h,1)[0] ],
d=(pow(p.x,2) + pow(p.y,2) ))

 d > pow(r,2)||d < pow(r2,2)?tube_point(r,r2,h):p;


p=random_points_inside_tube(50,30,100,1000);
for(t=p)translate(t) sphere(4);
echo(p);
 

Sunday, July 9, 2017

Volume Of A Sphere By Radius



function Volume_Of_A_Sphere_By_Radius(r )=(4/3)*PI* r*r*r ;

Tuesday, June 27, 2017

Wednesday, June 21, 2017

Great Circle / Concentric Small Circle By Two Lat Long Points

A great circle is any circle drawn on a  sphere with a center at the center of the sphere and thus the same radius.

function face_normal(point_a,point_b,point_c)=
let(u=point_a-point_b,v=point_a-point_c)
un([u[1]*v[2]-u[2]*v[1],u[2]*v[0]-
u[0]*v[2],u[0]*v[1]-u[1]*v[0]]);

function un(v)=v/max(norm(v),1e-64);

function look_at(p,o=[0,0,0],up=[0,0,1])=
let(
a=up,
b=p-o,
c=cross(a,b) ,
d=angle(a,b))
[d,c];

function angle (a,b)=
atan2(
sqrt((cross(a, b)*cross(a, b))), 
(a* b)  );

function rnd(a = 1, b = 0, s = []) =
s == [] ?
(rands(min(a, b), max(
a, b), 1)[0]) :
(rands(min(a, b), max(a, b), 1, s)[0]);

function Great_circle_axis(p1,p2,r)=
let(v1=face_normal([0,0,0],p1,p2))
v1;

module Great_circle(p1,p2,r){
v1=face_normal([0,0,0],p1,p2);
look_at(v1)torus(r,0.05);
}
module Concentric_small_circle(p1,p2,r,r2){
v1=face_normal([0,0,0],p1,p2);
look_at(v1)translate([0,0,sign(r2)*r*cos(90*(r2/r))])
torus(r*sin(90*(r2/r)),0.05);
}

module torus(r1,r2)
{rotate_extrude($fn=40)translate([r1,0,0])circle(r2,$fn=12);
}
module look_at(lookpoint,origin=[0,0,0],rotatefrom=[0,0,1]){
rotations=look_at(lookpoint,origin ,rotatefrom);
rotate(rotations[0],rotations[1]) children();
}
radius=5;
small_radius=radius*rnd();
#sphere(5,$fn=40);
lat1=rnd(-90,90);
long1=rnd(0,360);
lat2=rnd(-90,90);
long2=rnd(0,360);

p1= ([sin(long1),cos(long1)*sin(lat1),cos(lat1)])*radius;
p2= ([sin(long2),cos(long2)*sin(lat2),cos(lat2)])*radius;
echo(p1,p2);
translate(p1) sphere(0.3,$fn=40);
translate(p2) sphere(0.3,$fn=40);

Great_circle(p1,p2,radius);
Concentric_small_circle(p1,p2,radius,-small_radius);
Concentric_small_circle(p1,p2,radius,small_radius);


 

Tuesday, June 20, 2017

Great-Circle Distance between two lat long positions

This formula doesn't count the flattening of the earth at the poles. 
The earth has been approximated to a sphere with a radius of 6378 km.
 


function Great_circle_distance(latA,longA,latB,longB) =   
acos ( 
sin (latA) * sin (latB) +
cos (latA) * cos (latB) * cos (longB - longA) 
)*111.195  ;//(6371/57.295779513)

echo (Great_circle_distance(48.8566, -2.3522,52.5200 , -13.4050) );
//INFERNAL ;)
echo (Great_circle_distance(0, 90, 0, 0) );
 
 

Points inside a cube

Generates a list of random points that lie inside a cuboid.

function random_points_inside_cuboid(p1,p2,n)=
    [for(i=[1:n])cuboid_point(p1,p2)];

function cuboid_point(p1,p2)= 
  [rands(-p1.x,p2.x,1)[0],
   rands(-p1.y,p2.y,1)[0],
   rands(-p1.z,p2.z,1)[0]] ;

 


p1=[0,0,0];
p2=[100,100,100];
p=random_points_inside_cuboid(p1,p2,1000);
for(t=p)translate(t)sphere(4);
echo(p);
 

Friday, June 16, 2017

Points inside a sphere

Generates a list of random points that lie inside a sphere

function random_points_inside_sphere(r,n)=
[for(i=[1:n])sphere_point(r)];

function sphere_point(r)=
let (p=rands(-r,r,3)) 
(pow(p.x,2) + pow(p.y,2) + pow(p.z,2) > pow(r,2))?sphere_point(r):p;


p=random_points_inside_sphere(50,1000);
for(t=p)translate(t)sphere(4);
echo(p);


Thursday, June 8, 2017

Square / Rectangle Path

Generates a path in the shape of a rectangle .
Steps are rounded to evens for obvious reasons
Usage:


function figureL7(x=40,y=20,step=52)=
let(total=(x+x+y+y),steps_x=round(step/total*x),steps_y=round(step/total*y))
concat(
[for(t=[0:steps_x-1])[(-x/2+(x/steps_x)*t),y/2]],
[for(t=[0:steps_y-1])[x/2,y/2-((y/steps_y)*t)]],
[for(t=[0:steps_x-1])[x/2-((x/steps_x)*t),-y/2]],
[for(t=[0:steps_y-1])[-x/2,-y/2+(y/steps_y)*t]]);

function close(p)=concat(p,[p[0]]);
module polyline(p){for(i=[0:max(0,len(p)-2)])color([i%2])line(p[i],p[i+1]);}
module line(p1,p2,width=0.5){hull(){
    translate(p1)sphere(width);
    translate(p2)sphere(width);}}


polyline(close(figureL7()));
 
 

Circle Path

Generates a path in the shape of a circle

 
function circle(r=100,steps=100)=
[ for(t=[0:1/steps:1])
let(  x =r* sin(t*360),   y =r*cos(t*360)  )
[x,y] ];
// function close adds a last point equal yo the first
function close(p)= concat(p,[p[0]]);

module polyline(p) {for(i=[0:max(0,len(p)-2)])line(p[i],p[i+1]);} module line(p1, p2 ,width=0.5) { hull() { translate(p1) sphere(width); translate(p2) sphere(width); } } polyline(close(circle()));

Wednesday, June 7, 2017

Figure Eight Path

Generates a path in the shape of figure eight


function figure8(m=100)=[for(t=[0:1:360])
let(scale = 2 / (3 - cos(2*t)),x =m* scale * cos(t),y =m* scale * sin(2*t) / 2)
[x,y]];

function close(p)= concat(p,[p[0]]);

module polyline(p) {for(i=[0:max(0,len(p)-2)])line(p[i],p[i+1]);}
module line(p1, p2 ,width=0.5) 
{
    hull() {
        translate(p1) sphere(width);
        translate(p2) sphere(width);
    }
}


polyline(close(figure8(50))); 

Tuesday, June 6, 2017

Recursive Tangential Circle Approximation To Any Mix Of 3 Points, Lines, Circles Or Rectangles

Recursively try to find circles that touch outside three random features
of either point, line, circle or rectangle. 




Approximation start at a seed point and steps towards the smaller error 
until the summed error is smaller than a threshold.
First attempt starts at features common average  midpoint. 

If approximation error is smaller than threshold  the search is halted. 

Next starting points from around perimeter are tried and then a bunch of 
random starting  points.

Solution inside circles and squares hare not handled.
Results are not scientific exact, enough for construction of drawing.

Some unsolved edge cases fail, reducing overall usefulness.


Demo choose random features
Usage:



threshold = 1e-5;
workarea = 100;


function  AcmeSolver(f0, f1, f2, ifind = undef, maxi = 6000) =
let (
find = ifind == undef ? 
    (featurecenter(f0)   + featurecenter(f1)  
    + featurecenter(f2)  ) /3: ifind, 
d0 =distancetofeature(f0, find), 
nf0 = normaltofeature(f0, find),
d1 = distancetofeature(f1, find), 
nf1 = normaltofeature(f1, find),
d2 = distancetofeature(f2, find), 
nf2 = normaltofeature(f2, find),
sum = abs(d0 - d1) + abs(d1 - d2) + abs(d2 - d0), 
avrg = (d0 + d2 +    d1) / 3,  
cf0 = (find + nf0 * (max(0, d0) - avrg) * 0.999),  
cf1 = (    find + nf1 * (max(0, d1) - avrg) * 0.999),  
cf2 = (find + nf2 * (    max(0, d2) - avrg) * 0.999),  
newfind = (cf0 + cf1 + cf2) / 3 )
sum < threshold || maxi < 0 ? 
[find, avrg,   sum]
:  AcmeSolver(f0,
f1, f2, newfind, maxi - 1);

function featurecenter(feat) = 
len(feat) == 2 && len(feat[0]) ==  undef ? feat :
len(feat) == 3 && len(feat[0]) == undef ? [feat.x,feat.y] : 
len(feat) == 2 && len(feat[0]) == 2 ? (feat[0] + feat[1]) /2 :
len(feat) == 2 && len(feat[0]) == 2 ? 
(feat[0] + feat[1]+feat[2] + feat[3]) /  4 : [0, 0];

function distancetofeature(feat, find) = 
len(feat) == 2 && len(feat[0]) ==  undef ? norm(feat - find) : 
len(feat) == 3 && len(feat[0]) == undef ?  
distancetocircle(feat, find) : 
len(feat) == 2 && len(feat[0]) == 2 ?  distancetoline(feat, find) : 
len(feat) == 4 && len(feat[0]) == 2 ?  distancetosquare(feat, find) :
0;

function normaltofeature(feat, find) = 
len(feat) == 2 && len(feat[0]) ==  undef ? normaltopoint(feat, find) :
 len(feat) == 3 && len(feat[0]) ==  undef ? 
normaltocircle(feat, find) : 
len(feat) == 2 && len(feat[0]) ==  2 ? normaltoline(feat, find) :
len(feat) == 4 && len(feat[0]) ==  2 ? normaltosquare(feat, find) :
 0;

function distancetopoint(point, find) = norm(point - find);

function distancetocircle(circle, find) = 
norm([circle.x, circle.y] -  find) - circle[2];

function distancetoline(line, p) =
let (a = line[0], b = line[1], 
pa = p - a, ba = b - a, h =  ((pa * ba) /
  (ba * ba)))norm(pa - ba * h);

function distancetosquare(square, p) =min (
distancetosegment([square[0],square[1]],p),
distancetosegment([square[1],square[2]],p),
distancetosegment([square[2],square[3]],p),
distancetosegment([square[3],square[0]],p)

);

function distancetosegment(line, p) =
let (a = line[0], b = line[1], pa = p - a, ba = b - a,
 h =  clamp((pa * ba) /  (ba * ba)))
norm(pa - ba * h);
function clamp(a, b = 0, c = 1) = min(max(a, b), c); 

function normaltopoint(point, find) = 
(point - find) / norm(point -  find);

function normaltocircle(circle, find) = 
([circle.x, circle.y] - find) /norm([circle.x, circle.y] - find);

function normaltoline(line, find) =
let (a = line[0], b = line[1], dtl2 = distancetoline(line, find))
un([distancetoline(line, find + [-1, 0]) -
 dtl2, distancetoline(line,  find + [0, -1]) - dtl2]);

function normaltosegment(line, find) =
let (a = line[0], b = line[1],c=un(a-b))[-c.y,c.x];
 

function normaltosquare(square, find) =
let (  base = distancetosquare(square, find))
un([distancetosquare(square, find + [-1, 0]) - 
base, distancetosquare(square, find+ [0, -1]) - base]);

function un(v) = v / max(1e-15, norm(v));

// demo code

function allines(f0,f1,f2)=isline(feature0)
&&isline(feature1)&&isline(feature2);
function isline(feat)=len(feat) == 2 
&& len(feat[0]) == 2 ?true:false;
function randomfeature() =
let (s0 = round( rnd(3)
))
(s0 == 0) ? [rnd(workarea), rnd(workarea), rnd(1, workarea * 0.5)] :
(s0 == 1) ? [rnd(workarea), rnd(workarea)] : 
(s0 == 2) ? [[rnd(  workarea), rnd(workarea)],
 [rnd(workarea), rnd(workarea)]] :
(s0 == 3) ? let(
p1=[rnd(workarea), rnd(workarea)],
p2=p1+[rnd(workarea)/2, rnd(workarea)/2],
r=rnd(360),p3=(p1+p2)/2)
[rotp(r,p1,p3),rotp(r,[p2.x,p1.y],p3),
rotp(r,p2,p3),rotp(r,[p1.x,p2.y],p3) ] :
 ["err"];

function rotp(r,ip,p3)=
let( p=ip-p3, s = sin(r),
  c = cos(r),
    xnew = p.x * c - p.y * s,
    ynew = p.x * s + p.y * c)
[xnew,ynew]+p3
;
module showfeature(feat) {
  color("black") {
    if (len(feat) == 2 && len(feat[0]) == undef) {
      echo(" point ", feat);
      translate(feat) sphere(2);
    }
    if (len(feat) == 3 && len(feat[0]) == undef) {
      echo(" circle ", feat);
      linear_extrude(1)translate([feat.x, feat.y]) difference() {
        circle(feat[2]);
        circle(feat[2] - 1);
      }
    }
    if (len(feat) == 2 && len(feat[0]) == 2) {
      echo(" line ", feat);
      linear_extrude(1)hull() {
        translate(feat[0]) circle(1);
        translate(feat[1]) circle(1);
      }
      n1 = un(feat[0] - feat[1]);
      linear_extrude(0.2)hull() {
        translate(feat[0] + n1 * workarea) circle(0.2);
        translate(feat[1] - n1 * workarea) circle(0.2);
      }
    }
if (len(feat) == 4 && len(feat[0]) == 2) {
      echo(" square ", feat);
      linear_extrude(1)hull() {
        translate(feat[0]) circle(0.5);
        translate(feat[1]) circle(0.5);
      }
 linear_extrude(1)hull() {
        translate(feat[1]) circle(0.5);
        translate(feat[2]) circle(0.5);
      }
      linear_extrude(1)hull() {
        translate(feat[2]) circle(0.5);
        translate(feat[3]) circle(0.5);
      }
      linear_extrude(1)hull() {
        translate(feat[3]) circle(0.5);
        translate(feat[0]) circle(0.5);
      }
     
    }
  }
}
module ring(d, i = 1) {
  linear_extrude(i)
  {
    translate(d[0]) difference() {
      circle(d[1], $fn = 60);
      circle(max(0,d[1] - 1), $fn = 60);
    }
  }
}

function rnd(a = 1, b = 0, s = []) = s == [] ? 
(rands(min(a, b), max(
  a, b), 1)[0]) : (rands(min(a, b), max(a, b), 1, s)[0]);



feature0 = randomfeature();
feature1 = randomfeature();
feature2 = randomfeature();
showfeature(feature0);
showfeature(feature1);
showfeature(feature2);
// try fo fit from midpoint
d =  AcmeSolver(feature0, feature1, feature2);
//[center,radius, fit]

if (d[2] < threshold &&!allines(feature0, feature1, feature2)){
echo(" Found Internal ", d);
  color("red") ring(d, 1.5);
}
else {
  color("yellow") ring(d);
  if (d[2] < workarea*0.1) {
    echo(" Found no internal solution in time. Best fit : ", d[2]);
    echo(d);    
  }
  else {
    echo(" Found no internal solution in time. Best approximation : ");
    echo(d);   
  }

// try to fit from ouside
for (i = [45: 90: 360]) {
  cme = [sin(i) * workarea * 10, cos(i) * workarea * 10];
  de =  AcmeSolver(feature0, feature1, feature2, cme,1500);
  if (norm(d[0] - de[0]) > threshold) {
    if (de[2] < threshold) {
      color([1, rnd(), rnd()]) ring(de,0.9);
      echo(" Found External ",de);
    }
    else {
      echo(" Found no external solution in time ");
    }
  }
}
// try to fit from Random State
for (i = [0:  10]) {
  cme = [rnd(-workarea,workarea*2),rnd(-workarea,workarea*2)];
  de =  AcmeSolver(feature0, feature1, feature2, cme,1500);
  if (norm(d[0] - de[0]) > threshold) {
    if (de[2] < threshold) {
      color([1, rnd(), rnd()]) ring(de);
      echo(" Found Random State solution ",de);
    }
    else {
      echo(" Found no Random State solution in time ");
    }
  }
}

}




 

Monday, June 5, 2017

Intersection Of Lines

Calculate where two lines cross defined by
segments pa1-pa2 and pb1-pb2 


Usage:


function  IntersectionOfLines(pa1, pa2, pb1, pb2)=
let(
da = [(pa1.x-pa2.x),(pa1.y-pa2.y)], 
db = [(pb1.x-pb2.x),(pb1.y-pb2.y)],
the = da.x*db.y - da.y*db.x                 )
(the == 0)? 
undef: /* no in tersection*/
let (
A = (pa1.x * pa2.y - pa1.y * pa2.x),
B = (pb1.x * pb2.y - pb1.y * pb2.x)         )
[( A*db.x - da.x*B ) / the , ( A*db.y - da.y*B ) / the]
;

// demo code
pa1=[rnd(100),rnd(100)];
pa2 =[rnd(100),rnd(100)];
pb1=[rnd(100),rnd(100)];
pb2=[rnd(100),rnd(100)];
I=IntersectionOfLines(pa1, pa2, pb1, pb2);
line(pa1, pa2);
line(pb1, pb2);


// show in red if intersecting 
// else extend linese outside segments
if(I.x>min(pa1.x,pa2.x)&&I.x<max(pa1.x,pa2.x)
&&I.y>min(pa1.y,pa2.y)&&I.y<max(pa1.y,pa2.y))
{color("red")translate(I) sphere(3);
}
else{
translate(I) sphere(3);
hull(){
translate(I) sphere(0.5);
translate(pa1) sphere(0.5);}
hull(){
translate(I) sphere(0.5);
translate(pb1) sphere(0.5);}
}


echo(I);

module line(p1,p2){hull(){
translate(p1) sphere(1);
translate(p2) sphere(1);
}}

function rnd(a = 1, b = 0, s = []) =
s == [] ?
  (rands(min(a, b), max(
    a, b), 1)[0]) :
  (rands(min(a, b), max(a, b), 1, s)[0]);
 

Wednesday, May 31, 2017

Find a point some partial length along a poly-line

len3v sum's up total length if a poly-line
v2t returns a point
 some partial length along the poly-line.
Far_Along is a 0-1 multiplier to regularize the expression with other code
Usage:



My_poly_line=make_points(6);
LengthOfIt=(len3v(My_poly_line));
Far_Along=rnd(1);
My_Point_Exactly=v2t(My_poly_line,LengthOfIt*Far_Along);
echo( str(round(Far_Along*100),"% "),My_Point_Exactly);
polyline(My_poly_line);
translate(My_Point_Exactly)color("gold")sphere(3);
translate(My_poly_line[0])color("red")sphere(2);
translate(My_poly_line[len(My_poly_line)-1])color("blue")sphere(2);

module line(p1, p2 ,width=0.1) { hull() {        
translate(p1) sphere(width);
translate(p2) sphere(width);    }}

module polyline(p) {for(i=[0:max(0,len(p)-2)])line(p[i],p[i+1]);}

function un(v)=v/max(1e-15,norm(v));
function len3v(v,acc=0,p=0)=p+1>len(v)-1?
        acc: len3v(v,acc+norm(v[p]-v[p+1]),p+1)  ;
function v2t(v,stop,p=0)=p+1>len(v)-1|| norm(v[p]-v[p+1])>stop?  
 v[p]+un(v[p+1]-v[p])*stop:v2t(v,stop-norm(v[p]-v[p+1]),p+1);
function make_points(j=10,l1=[-30,-30,-30],l2=[30,30,30])= 
     ([for(i=[1:j])[
rnd(l1.x,l2.x)/10+i*10,//linear spagetti
rnd(l1.y,l2.y),
rnd(l1.z,l2.z)]]);
function rnd(a = 1, b = 0, s = []) = 
  s == [] ? 
   (rands(min(a, b), max(   a, b), 1)[0]) 
  : 
   (rands(min(a, b), max(a, b), 1, s)[0])
  ; 

module line(p1, p2 ,width=0.1) { hull() {        
translate(p1) sphere(width);
translate(p2) sphere(width);    }}

module polyline(p) {for(i=[0:max(0,len(p)-2)])line(p[i],p[i+1]);}


 

Map Cartesian coordinates to and from Hilbert curve

Curve  in range 0-1 is mapped to   Cartesian coordinates [0,0]-[1,1]

Usage:



p=[rnd(),rnd()];
translate(p)sphere(0.05);
n=cartesian_to_curve(p);
 echo("point:",p,"on curve:",n);

step=0.003/3/3;
for(i=[0:step :1-step]){
t1=curve_to_cartesian(i);t2=curve_to_cartesian(i+step); 
color([i,sin(i*5000)*0.5+0.5,1-i]) 
hull(){translate (t1) sphere(0.005);translate (t2) sphere(0.005); }}
translate ([-0.1,-0.1])scale(0.01)text("0");
translate ([1,-0.1])scale(0.01)text("1");
 
function curve_to_cartesian
(i,order=4,a=[0,0],b=[0,1],c=[1,1],d=[1,0],s=0,e=1)=let(
p1=lerp(s,e,1/4),p2=lerp(s,e,2/4),p3=lerp(s,e,3/4),
ab=(a+b)/2,bc=(b+c)/2,cd=(c+d)/2,da=(d+a)/2,
center=(a+b+c+d)/4     )
!order>0?let(
a2=lerp(a,center,0.5),b2=lerp(b,center,0.5),
c2=lerp(c,center,0.5),d2=lerp(d,center,0.5))
along([a2,b2,c2,d2],(i-s)/max(1e-16,abs(e-s)))
: i<p1?    curve_to_cartesian(i,order-1,a,da,center,ab,s,p1):
i>p1&&i<p2?curve_to_cartesian(i,order-1,ab,b,bc,center,p1,p2):
i>p2&&i<p3?curve_to_cartesian(i,order-1,center,bc,c,cd,p2,p3):
           curve_to_cartesian(i,order-1,cd,center,da,d,p3,e);

function cartesian_to_curve
(i,order=28,a=[0,0],b=[0,1],c=[1,1],d=[1,0],s=0,e=1)=let(
p1=lerp(s,e,1/4),p2=lerp(s,e,2/4),p3=lerp(s,e,3/4),
ab=(a+b)/2,bc=(b+c)/2,cd=(c+d)/2,da=(d+a)/2,
center=(a+b+c+d)/4   )
!order>0? s : 
inbox(i,a,da,center,ab)==true?cartesian_to_curve(i,order-1,a,da,center,ab,s,p1):
inbox(i,ab,b,bc,center )==true?cartesian_to_curve(i,order-1,ab,b,bc,center,p1,p2):
inbox(i,center,bc,c,cd)==true?cartesian_to_curve(i,order-1,center,bc,c,cd,p2,p3):
           cartesian_to_curve(i,order-1,cd,center,da,d,p3,e);

function lerp(start, end, bias) = (end * bias + start * (1 - bias));
function len3v(v,acc=0,p=0)=p+1>len(v)-1?acc:len3v(v,acc+norm(v[p]-v[p+1]),p+1)  ;
function un(v)=v/max(1e-15,norm(v));
function along(v,i)=let(r=v2t(v,len3v(v)*i))[r.x,r.y,r.z];
function inbox (i,a,b,c,d)= 
i.x==max(i.x,a.x,b.x,c.x,d.x)||i.x==min(i.x,a.x,b.x,c.x,d.x)||
i.y==max(i.y,a.y,b.y,c.y,d.y)||i.y==min(i.y,a.y,b.y,c.y,d.y)? false:true;
function v2t(v,stop,p=0)=p+1>len(v)-1|| norm(v[p]-v[p+1])>stop?   v[p]+un(v[p+1]-v[p])*stop:  v2t(v,stop-norm(v[p]-v[p+1]),p+1);
function rnd(a = 1, b = 0, s = []) =
s == [] ?
  (rands(min(a, b), max(
    a, b), 1)[0]) :
  (rands(min(a, b), max(a, b), 1, s)[0]);
 

Clustering k-means

K-means clustering is a type of unsupervised learning. The algorithm works iteratively to assign each point to the closest of K groups. Each groups centroid is updated as the mean of its assigned points and groups converge. Function returns a list of means and a list of  points sorted in sublists for each group.
Usage:

 
p=make_points(75);
K=Kmeans(p,round(rnd(1,20)),round(rnd(1,10)));
for(i=[0:len(p)-1])translate(p[i])sphere(0.5);  
for(i=[0: max(0,len(K[0])-1)])
    translate(K[0][i])color("Red",0.5)sphere(2,$fn=20);
for(i=[0: max(0,len(K[1])-1)]){
    color([rnd(),rnd(),rnd()] ,0.5)hull(){
    for(j=[0: max(0,len(K[1][i])-1)])translate(K[1][i][j])sphere( 3,$fn=1 );}}

function Kmeans(v,K,c=5,inmeans=undef) =  len(v) < K ? [v,v] :
let(
maxlenv= max(0,len(v)-1),maxK=max(0,K-1),
means=inmeans==undef? /* Initailize means if not done */ [for(i=[0:maxlenv])
        (v[rnd(maxlenv)]+v[rnd(maxlenv)]+v[rnd(maxlenv)])/3]:inmeans, 
vbuckets=[for(i=[0:maxlenv])index_min([for(k=[0:maxK])norm(v[i]-means[k])])],
new_means=[for(k=[0:maxK]) mean([for(i=[0:maxlenv]) if(vbuckets[i]==k)v[i]])]   )
c>0? Kmeans(v,K,c-1,new_means):
let(inbuckets=[for(k=[0:maxK])[for(i=[0:maxlenv]) if(vbuckets[i]==k)v[i]] ])
[new_means,inbuckets] ;


function index_min(l) = search(min(l), l)[0];
function index_max(l) = search(max(l), l)[0];
function mean(a) = !(len(a) > 0)?undef:([ for(b=a) 1 ] * a )/len(a);
function make_points(j=10)= 
     ([for(i=[0:j])[rnd(-30,30),rnd(-20,20),rnd(-10,10)]]);
function rnd(a = 1, b = 0, s = [] ) = 
  s == [] ? 
   (rands(min(a, b), max(   a, b), 1)[0]) 
  : 
   (rands(min(a, b), max(a, b), 1, s)[0])
  ; 

 

Tuesday, May 30, 2017

LookAt function and module

Rotate an object towards a waypoint.
Uses angle+vector format of openSCADs native rotate operand.

Usage:

Lookatpoint=[rnd(-20,20),rnd(-20,20),rnd(-20,20)];
Origin=[rnd(-20,20),rnd(-20,20),rnd(-20,20)];
translate(Lookatpoint)color("red")sphere(2);
translate(Origin)color("blue")sphere(2);
translate(Origin)look_at(Lookatpoint ,Origin ){
translate([0,0,5])cylinder(7,2,0);
translate([0,0,-3])cylinder(9,1,1);
}
module look_at(lookpoint,origin=[0,0,0],rotatefrom=[0,0,1]){
rotations=look_at(lookpoint,origin ,rotatefrom);
rotate(rotations[0],rotations[1]) children();
}

function look_at(p,o=[0,0,0],up=[0,0,1])=
let(
a=up,
b=p-o,
c=cross(a,b) ,
d=angle(a,b))
[d,c];

function angle (a,b)=
atan2(
sqrt((cross(a, b)*cross(a, b))), 
(a* b)
);


function rnd(a = 1, b = 0, s = []) =
s == [] ?
  (rands(min(a, b), max(
    a, b), 1)[0]) :
  (rands(min(a, b), max(a, b), 1, s)[0]);



 

Monday, May 29, 2017

Incircle of a triangle in 3d


Incircle / inscribed circle of a triangle is the largest circle that fits inside a triangle and touches all three sides. 
Usage:


$fn = 50;
point_C = [rnd(-20, 20), rnd(-20, 20), rnd(-20, 20)];
point_B = [rnd(-20, 20), rnd(-20, 20), rnd(-20, 20)];
point_A = [rnd(-20, 20), rnd(-20, 20), rnd(-20, 20)];
center = Incenter(point_A, point_B, point_C);
inradius= point_to_line(center,point_A, point_B);
hull(){translate(point_A) sphere(0.1);
translate(point_B) sphere(0.1);
translate(point_C) sphere(0.1);}
color("red") translate(center) sphere(inradius);
echo(center, inradius);

function Incenter(A, B, C) =
let (
a=norm(B-C),
b=norm(A-C),
c=norm(A-B),
  p = a + b + c, 
  Ox = (a * A.x + b * B.x + c * C.x) / p, 
  Oy = (a * A.y + b * B.y + c * C.y) / p,
  Oz = (a * A.z + b * B.z + c * C.z) / p
    )
[Ox, Oy, Oz];

function point_to_line(p,a,b)=
let(
pa = p - a, 
ba = b - a,
h = clamp( (pa*ba)/ (ba*ba)))
norm( pa - ba*h ) ;
function clamp(a, b = 0, c = 1) = min(max(a, b), c); 

 
function rnd(a = 1, b = 0, s = []) =
s == [] ?
  (rands(min(a, b), max(
    a, b), 1)[0]) :
  (rands(min(a, b), max(a, b), 1, s)[0]);