// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(-1);

// Global code will be evaluated once.
const turtle = new Turtle();
const sw = SegmentWriter();

turtle.jump(-83, -50);
sw.write(turtle, '16-SEGMENT');

sw.setSkew(-.5);
turtle.jump(-60, -28);
sw.write(turtle, 'FONT-FACE');

sw.setSize(10);
sw.setRatio(.7);
sw.setThickness(.3);
sw.setMargin(.6);
sw.setSkew(0);
sw.setEnabledHatching(1, .4)
turtle.jump(-90, -8);
sw.write(turtle, 'the quick brown fox\njumps over the lazy dog\n0*[12+34*5/67-89]=0.');

const date = new Date();
const h = date.getHours(); // 0 - 23
const m = date.getMinutes(); // 0 - 59

sw.setSize(50);
sw.setRatio(.65);
sw.setThickness(.4);
sw.setMargin(.3);
sw.setSkew(.3);
sw.drawDisabled();
sw.setEnabledHatching(1, .15)
sw.setDisabledHatching(2, 2)
turtle.jump(-92, 80);
sw.write(turtle, (h<10?'0':'')+h+':'+(m<10?'0':'')+m);

sw.setSize(10);
sw.setRatio(.7);
sw.setThickness(.3);
sw.setMargin(.6);
sw.setSkew(0);
sw.drawDisabled(false);
turtle.jump(-90, -65);
turtle.left(30);
sw.write(turtle, '*new*');




function SegmentWriter(height = 20, ratio = .75, thickness = .5, margin=.5, skew = .4) {
    const args = [height, ratio, thickness, margin, skew];
    
    //wrapped 2d functions
    function mul2(a, b) { return [a[0]*b[0], a[1]*b[1]]; }
    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 lenSq2(a) { return a[0]**2+a[1]**2; }
    function len2(a) { return Math.sqrt(lenSq2(a)); }   
    function scale2(a, s) { return mul2(a, [s,s]); }
    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]]; }
    function ray_intersect2(a,b,d,c, inclusive = true) {
        const e=(c[1]-d[1])*(b[0]-a[0])-(c[0]-d[0])*(b[1]-a[1]);
        if(0==e)return false;
        c=((c[0]-d[0])*(a[1]-d[1])-(c[1]-d[1])*(a[0]-d[0]))/e;
        d=((b[0]-a[0])*(a[1]-d[1])-(b[1]-a[1])*(a[0]-d[0]))/e;
        return [a[0]+c*(b[0]-a[0]),a[1]+c*(b[1]-a[1])];
    }
    
    TYPE_HORIZONTAL = 1;
    TYPE_VERTICAL = 2;
    TYPE_DIAGBS = 4;
    TYPE_DIAGS = 8;
    
    class SegmentWriter {
        constructor(height = 20, ratio = .75, thickness = .5, margin=.5, skew = .4) {
            this.argHeight = height;
            this.argRatio = ratio;
            this.argThickness = thickness;
            this.argMargin = margin;
            this.argSkew = skew;
            
            this.polygons = false;
            this.enabledHatching = [1, .15];
            this.disabledHatching = false;
            this.showDisabled = false;
            this.calibrate();
        }
        calibrate() {
            this.segmentPoints = [];

            this.height = this.argHeight;
            this.width = this.argRatio * this.argHeight;
            this.thickness = this.argHeight*this.argThickness/5;
            this.margin =  this.argHeight*this.argMargin/10;
            this.skew = this.argHeight * this.argSkew;

            this.points = points.map(pt => mul2(pt, [this.width - this.thickness, this.height - this.thickness])).map(pt => add2(pt, [this.thickness / 2, -this.thickness / 2]));
            this.skewAngle = Math.atan(this.skew/this.height);
        }
        getType(segmentId) {
            return [0, 1, 7, 8, 14, 15].includes(segmentId)? TYPE_HORIZONTAL: 
                    ([2, 4, 6, 9, 11, 13].includes(segmentId)? TYPE_VERTICAL: (
                    ([3, 12].includes(segmentId)? TYPE_DIAGBS: TYPE_DIAGS)));
        }
        getSegmentPoints(segmentId) {
            if(!this.segmentPoints[segmentId]) {
                const type = this.getType(segmentId);
                
                const skewPoint = (pt) => [pt[0] - this.skew*pt[1]/this.height, pt[1]];
                
                const anchors = segmentPoints[segmentId].map(i => this.points[i]);
                const skewedAnchors = anchors.map(pt => skewPoint(pt));
                
                const segmentDirection = sub2(skewedAnchors[1], skewedAnchors[0]);
                const normDir = scale2(segmentDirection, 1/len2(segmentDirection));
                
                if(type == TYPE_DIAGBS || type == TYPE_DIAGS) {
                    const operator = type == TYPE_DIAGBS? 1: -1;
                    const diagAnchors = [
                        add2(anchors[0], [operator * (this.thickness/2 + this.margin), this.thickness/2 + this.margin]),
                        sub2(anchors[1], [operator * (this.thickness/2 + this.margin), this.thickness/2 + this.margin])
                    ].map(pt => skewPoint(pt));
                    skewedAnchors[0] = diagAnchors[0];
                    skewedAnchors[1] = diagAnchors[1];
                } else {
                    const marginDir = scale2(normDir, this.margin / 2);
                    skewedAnchors[0] = add2(skewedAnchors[0], marginDir);
                    skewedAnchors[1] = sub2(skewedAnchors[1], marginDir);
                }
                
                const sideDirection = scale2(normDir, this.thickness / 2);
                const constraintDirections = [trans2(rot2(Math.PI/2), sideDirection), trans2(rot2(-Math.PI/2), sideDirection)];
                
                const leftConstraint = [
                    add2(skewedAnchors[0], constraintDirections[0]),
                    sub2(skewedAnchors[1], constraintDirections[1])
                ];
                const rightConstraint = [
                    add2(skewedAnchors[0], constraintDirections[1]),
                    sub2(skewedAnchors[1], constraintDirections[0])
                ];
                
                const arrowAngle = Math.PI / 4;
                let sides = null;
                switch(type) {
                    case TYPE_HORIZONTAL:
                        sides = [trans2(rot2(arrowAngle - this.skewAngle/2), sideDirection), trans2(rot2(-arrowAngle - this.skewAngle/2), sideDirection)];
                        break;
                    case TYPE_DIAGS:
                        sides = [trans2(rot2(-this.skewAngle), [0,1]), [-1, 0]];
                        break;
                    case TYPE_VERTICAL:
                        sides = [trans2(rot2(arrowAngle + this.skewAngle/2), sideDirection), trans2(rot2(-arrowAngle + this.skewAngle/2), sideDirection)];
                        break;
                    case TYPE_DIAGBS:
                        sides = [[1,0], trans2(rot2(-this.skewAngle), [0, -1])];
                        break;
                }
    
                const from = [
                    ray_intersect2(skewedAnchors[0], add2(skewedAnchors[0], sides[0]), ...leftConstraint),
                	skewedAnchors[0],
                    ray_intersect2(skewedAnchors[0], add2(skewedAnchors[0], sides[1]), ...rightConstraint)
                ];
                
                const to = [
                    ray_intersect2(skewedAnchors[1], sub2(skewedAnchors[1], sides[0]), ...rightConstraint),
                	skewedAnchors[1],
                    ray_intersect2(skewedAnchors[1], sub2(skewedAnchors[1], sides[1]), ...leftConstraint),
                ];
                
                this.segmentPoints[segmentId] = [
                    ...from,
                    ...to
                ];
            }
            return this.segmentPoints[segmentId];
        }
        setSkew(skew) {
            this.argSkew = skew;
            this.calibrate();
        }
        setEnabledHatching(...hatching) {
            this.enabledHatching = hatching;
        }
        setDisabledHatching(...hatching) {
            this.disabledHatching = hatching;
        }
        setSize(size) {
            this.argHeight = size;
            this.calibrate();
        }
        setRatio(ratio) {
            this.argRatio = ratio;
            this.calibrate();
        }
        setThickness(thickness) {
            this.argThickness = thickness;
            this.calibrate();
        }
        setMargin(margin) {
            this.argMargin = margin;
            this.calibrate();
        }
        usePolygons(polygons) {
            this.polygons = polygons;
        }
        writeCharacter(turtle, character) {
            const segments = Array.from({length: 16}).map((v, i) => this.getSegmentPoints(i));
            
            if(characterSegments[character.toUpperCase()] === undefined) {
                throw new Error('Character ' + character.toUpperCase() + ' is not defined');
            }
            
            const onSegs = characterSegments[character.toUpperCase()];
            
            const rot = rot2(-2*Math.PI*turtle.h() / turtle._fullCircle);

            const pos = turtle.pos();
            const origin = turtle.pos().map(a => a);
            segments.forEach((s, i) => {
                const p = (this.polygons === false? polygons.create(): this.polygons.create());
                p.addPoints(...s.map(pt => add2(trans2(rot, pt), origin)));
                p.addOutline();
                (onSegs.includes(i) && this.enabledHatching !== false)? p.addHatching(...this.enabledHatching):'';
                (this.showDisabled && !onSegs.includes(i) && this.disabledHatching !== false)? p.addHatching(...this.disabledHatching):'';
                (onSegs.includes(i) || this.showDisabled)? (this.polygons === false? polygons.draw(turtle, p): this.polygons.draw(turtle, p)):'';
                
            });
            turtle.jump(add2(pos, trans2(rot, [this.width + this.margin * 1.5, 0])));
        }
        write(turtle, line) {
            const pos = turtle.pos();
            const lineVec = trans2(rot2(-2*Math.PI*turtle.h() / turtle._fullCircle), [0, this.height * 1.3]);
            let lines = 0;
            for(let i = 0; i < line.length; i++) {
                if(line[i] == "\n") {
                    turtle.jump(add2(pos, scale2(lineVec, ++lines)));
                    continue;
                }
                this.writeCharacter(turtle, line[i]);
            }
        }
        drawDisabled(drawDisabled = true) {
            this.showDisabled = drawDisabled == true;
        }
    }

    /*
            0     1         0-1-2
         2  3  4  5  6      |\|/|
            7     8         3-4-5
         9 10 11 12  13     |/|\|
           14     15        6-7-8
    */
    characterSegments = {'0': [0, 1, 6, 13, 15, 14, 9, 2, 5, 10],'1': [6, 13],'2': [0, 1, 6, 8, 7, 9, 14, 15],'3': [0, 1, 6, 8, 13, 14, 15],'4': [2, 6, 7, 8, 13],'5': [0, 1, 2, 7, 8, 13, 14, 15],'6': [0, 1, 2, 7, 8, 9, 13, 14, 15],'7': [0, 1, 5, 11],'8': [0, 1, 2, 6, 7, 8, 9, 13, 14, 15],'9': [0, 1, 2, 6, 7, 8, 13, 14, 15],'A': [0, 1, 2, 6, 7, 8, 9, 13],'B': [0, 1, 14, 15, 4, 11, 8, 6, 13],'C': [0, 1, 2, 9, 14, 15],'D': [0, 1, 14, 15, 6, 13, 4, 11],'E': [0, 1, 2, 7, 9, 14, 15],'F': [0, 1, 2, 7, 9],'G': [0, 1, 2, 9, 14, 15, 13, 8],'H': [2, 9, 6, 13, 7, 8],'I': [4, 11, 0, 1, 14, 15],'J': [1, 6, 13, 15, 14, 9],'K': [2, 9, 7, 5, 12],'L': [2, 9, 14, 15],'M': [2, 9, 6, 13, 3, 5],'N': [2, 9, 3, 12, 6, 13],'O': [0, 1, 6, 13, 15, 14, 9, 2],'P': [0, 1, 6, 8, 7, 2, 9],'Q': [0, 1, 2, 6, 7, 8, 13],'R': [0, 1, 2, 6, 9, 7, 8, 12],'S': [0, 1, 2, 7, 8, 13, 14, 15],'T': [0, 1, 4, 11],'U': [2, 9, 14, 15, 6, 13],'V': [2, 9, 10, 5],'W': [2, 9, 10, 12, 13, 6],'X': [3, 5, 10, 12],'Y': [3, 5, 11],'Z': [0, 1, 5, 10, 14, 15],'+': [4, 11, 7, 8],'-': [7, 8],'*': [3, 5, 10, 12, 7, 8, 4, 11],'/': [10, 5],'\\': [3, 12],'[': [1, 4, 11, 15],']': [0, 4, 11, 14],'(': [5, 12],')': [3, 10],'\'': [6],'"': [4, 6],'@': [11, 7, 9, 14, 15, 13, 6, 1, 0],'.': [15],',': [12, 15],'%': [0, 2, 4, 7, 8, 11, 15, 13, 10, 5],'?': [0, 1, 6, 8, 11],'{': [0, 3, 10, 14, 7],'}': [1, 5, 12, 15, 8],'=': [7, 8, 14, 15],'&': [1, 5, 9,7, 14, 4, 11, 15],'|': [4, 11],'_': [14, 15],':': [8, 15],';': [6, 12, 15],'#': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],' ': []}
    points   = Array.from({length: 3}).flatMap((v, y) => Array.from({length: 3}).map((v, x) => [x/2, (y/2)-1]));
    segmentPoints = [
                [0, 1],         [1, 2],
        [0, 3], [0, 4], [1, 4], [2, 4], [2, 5],
                [3, 4],         [4, 5],
        [3, 6], [4, 6], [4, 7], [4, 8], [5, 8],
                [6, 7],         [7, 8]
    ];
    
    //Wrapped Polygon Clipping utility code - Created by Reinder Nijhoff 2019
    //so this class can be used without it. Although it does implement a usePolygons(polygons) method
    //to support adding polygons to existing Polygons instances (or remove Polygons defining line).
            
    ////////////////////////////////////////////////////////////////
    // 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)}}}
    const polygons = new Polygons;

    return new SegmentWriter(...args)
}