1
0
mirror of https://github.com/Pomax/BezierInfo-2.git synced 2025-08-30 19:50:01 +02:00

offsetting

This commit is contained in:
Pomax
2020-09-04 22:01:35 -07:00
parent 83dcab57cb
commit 7e5c6e2eba
38 changed files with 15520 additions and 412 deletions

View File

@@ -12,5 +12,10 @@ Like normal offsetting we cut up our curve in sub-curves, and then check at whic
At each of the relevant points (start, end, and the projections of the control points onto the curve) we know the curve's normal, so offsetting is simply a matter of taking our original point, and moving it along the normal vector by the offset distance for each point. Doing so will give us the following result (these have with a starting width of 0, and an end width of 40 pixels, but can be controlled with your up and down arrow keys):
<Graphic title="Offsetting a quadratic Bézier curve" setup={this.setupQuadratic} draw={this.draw} onKeyDown={this.props.onKeyDown}/>
<Graphic title="Offsetting a cubic Bézier curve" setup={this.setupCubic} draw={this.draw} onKeyDown={this.props.onKeyDown}/>
<graphics-element title="Offsetting a quadratic Bézier curve" src="./offsetting.js" data-type="quadratic">
<input type="range" min="5" max="50" step="1" value="20" class="slide-control">
</graphics-element>
<graphics-element title="Offsetting a cubic Bézier curve" src="./offsetting.js" data-type="cubic">
<input type="range" min="5" max="50" step="1" value="20" class="slide-control">
</graphics-element>

View File

@@ -1,37 +0,0 @@
module.exports = {
statics: {
keyHandlingOptions: {
propName: "distance",
values: {
"38": 1, // up arrow
"40": -1 // down arrow
}
}
},
setup: function(api, curve) {
api.setCurve(curve);
api.distance = 20;
},
setupQuadratic: function(api) {
var curve = api.getDefaultQuadratic();
this.setup(api, curve);
},
setupCubic: function(api) {
var curve = api.getDefaultCubic();
this.setup(api, curve);
},
draw: function(api, curve) {
api.reset();
api.drawSkeleton(curve);
api.drawCurve(curve);
api.setColor("blue");
var outline = curve.outline(0,0,api.distance,api.distance);
outline.curves.forEach(c => api.drawCurve(c));
}
};

View File

@@ -0,0 +1,63 @@
let curve;
setup() {
const type = this.parameters.type ?? `quadratic`;
if (type === `quadratic`) {
curve = Bezier.defaultQuadratic(this);
} else {
curve = Bezier.defaultCubic(this);
}
setMovable(curve.points);
setSlider(`.slide-control`, `distance`, 20);
}
draw() {
clear();
noFill();
curve.drawSkeleton();
curve.drawCurve(`lightblue`);
this.outline(curve, this.distance).forEach(c => this.drawCurve(c));
curve.drawPoints();
};
drawCurve(c) {
setStroke( randomColor() );
start()
c.getLUT(16).forEach(p => vertex(p.x, p.y));
end();
}
outline(curve, d) {
const reduced = curve.reduce(),
fcurves = [];
let bcurves = [],
alen = 0,
tlen = curve.length();
// form curve oulines
reduced.forEach(segment => {
let slen = segment.length();
fcurves.push(segment.scale(this.linearDistanceFunction(d, tlen, alen, slen)));
bcurves.push(segment.scale(this.linearDistanceFunction(-d, tlen, alen, slen)));
alen += slen;
});
// reverse the "return" outline
bcurves = bcurves
.map(s => {
s.points = s.points.reverse();
return s;
})
.reverse();
return [...fcurves, ...bcurves];
}
linearDistanceFunction(d, tlen, alen, slen) {
return v => {
const f1 = alen / tlen,
f2 = (alen + slen) / tlen;
return map(v, 0, 1, f1 * d, f2 * d);
};
}

View File

@@ -57,9 +57,14 @@ So, you cannot offset a Bézier curve perfectly with another Bézier curve, no m
A good way to do this reduction is to first find the curve's extreme points, as explained in the earlier section on curve extremities, and use these as initial splitting points. After this initial split, we can check each individual segment to see if it's "safe enough" based on where the center of the curve is. If the on-curve point for `t=0.5` is too far off from the center, we simply split the segment down the middle. Generally this is more than enough to end up with safe segments.
The following graphics show off curve offsetting, and you can use your up and down arrow keys to control the distance at which the curve gets offset. The curve first gets reduced to safe segments, each of which is then offset at the desired distance. Especially for simple curves, particularly easily set up for quadratic curves, no reduction is necessary, but the more twisty the curve gets, the more the curve needs to be reduced in order to get segments that can safely be scaled.
The following graphics show off curve offsetting, and you can use the slider to control the distance at which the curve gets offset. The curve first gets reduced to safe segments, each of which is then offset at the desired distance. Especially for simple curves, particularly easily set up for quadratic curves, no reduction is necessary, but the more twisty the curve gets, the more the curve needs to be reduced in order to get segments that can safely be scaled.
<Graphic title="Offsetting a quadratic Bézier curve" setup={this.setupQuadratic} draw={this.draw} onKeyDown={this.props.onKeyDown} />
<Graphic title="Offsetting a cubic Bézier curve" setup={this.setupCubic} draw={this.draw} onKeyDown={this.props.onKeyDown} />
<graphics-element title="Offsetting a quadratic Bézier curve" src="./offsetting.js" data-type="quadratic">
<input type="range" min="5" max="50" step="1" value="20" class="slide-control">
</graphics-element>
<graphics-element title="Offsetting a cubic Bézier curve" src="./offsetting.js" data-type="cubic">
<input type="range" min="5" max="50" step="1" value="20" class="slide-control">
</graphics-element>
You may notice that this may still lead to small 'jumps' in the sub-curves when moving the curve around. This is caused by the fact that we're still performing a naive form of offsetting, moving the control points the same distance as the start and end points. If the curve is large enough, this may still lead to incorrect offsets.

View File

@@ -1,58 +0,0 @@
module.exports = {
statics: {
keyHandlingOptions: {
propName: "distance",
values: {
"38": 1, // up arrow
"40": -1 // down arrow
}
}
},
setup: function(api, curve) {
api.setCurve(curve);
api.distance = 20;
},
setupQuadratic: function(api) {
var curve = api.getDefaultQuadratic();
this.setup(api, curve);
},
setupCubic: function(api) {
var curve = api.getDefaultCubic();
this.setup(api, curve);
},
draw: function(api, curve) {
api.reset();
api.drawSkeleton(curve);
var reduced = curve.reduce();
reduced.forEach(c => {
api.setRandomColor();
api.drawCurve(c);
api.drawCircle(c.points[0], 1);
});
var last = reduced.slice(-1)[0];
api.drawPoint(last.points[3] || last.points[2]);
api.setColor("red");
var offset = curve.offset(api.distance);
offset.forEach(c => {
api.drawPoint(c.points[0]);
api.drawCurve(c);
});
last = offset.slice(-1)[0];
api.drawPoint(last.points[3] || last.points[2]);
api.setColor("blue");
offset = curve.offset(-api.distance);
offset.forEach(c => {
api.drawPoint(c.points[0]);
api.drawCurve(c);
});
last = offset.slice(-1)[0];
api.drawPoint(last.points[3] || last.points[2]);
}
};

View File

@@ -0,0 +1,118 @@
let curve;
setup() {
const type = this.parameters.type ?? `quadratic`;
if (type === `quadratic`) {
curve = Bezier.defaultQuadratic(this);
} else {
curve = Bezier.defaultCubic(this);
}
setMovable(curve.points);
setSlider(`.slide-control`, `distance`, 20);
}
draw() {
clear();
noFill();
curve.drawSkeleton();
var reduced = this.reduce(curve);
reduced.forEach(c => {
setStroke( randomColor() );
this.drawCurve(c);
circle(c.points[0].x, c.points[0].y, 2);
});
var last = reduced.slice(-1)[0];
let p = last.points[3] ?? last.points[2];
circle(p.x, p.y, 3);
setStroke(`#FF000050`);
var offset = curve.offset(this.distance);
offset.forEach(c => {
circle(c.points[0].x, c.points[0].y, 2);
this.drawCurve(c);
});
last = offset.slice(-1)[0];
p = last.points[3] ?? last.points[2];
circle(p.x, p.y, 3);
setStroke(`#0000FF50`);
var offset = curve.offset(-this.distance);
offset.forEach(c => {
circle(c.points[0].x, c.points[0].y, 2);
this.drawCurve(c);
});
last = offset.slice(-1)[0];
p = last.points[3] ?? last.points[2];
circle(p.x, p.y, 3);
curve.drawPoints();
}
drawCurve(c) {
start()
c.getLUT(16).forEach(p => vertex(p.x, p.y));
end();
}
reduce(curve) {
let i,
t1 = 0,
t2 = 0,
step = 0.01,
segment,
pass1 = [],
pass2 = [];
// first pass: split on extrema
let extrema = curve.extrema().values;
if (extrema.indexOf(0) === -1) {
extrema = [0].concat(extrema);
}
if (extrema.indexOf(1) === -1) {
extrema.push(1);
}
for (t1 = extrema[0], i = 1; i < extrema.length; i++) {
t2 = extrema[i];
segment = curve.split(t1, t2);
segment._t1 = t1;
segment._t2 = t2;
pass1.push(segment);
t1 = t2;
}
// second pass: further reduce these segments to simple segments
pass1.forEach(p1 => {
t1 = 0;
t2 = 0;
while (t2 <= 1) {
for (t2 = t1 + step; t2 <= 1 + step; t2 += step) {
segment = p1.split(t1, t2);
if (!segment.simple()) {
t2 -= step;
if ( abs(t1 - t2) < step) {
// we can never form a reduction
return [];
}
segment = p1.split(t1, t2);
segment._t1 = map(t1, 0, 1, p1._t1, p1._t2);
segment._t2 = map(t2, 0, 1, p1._t1, p1._t2);
pass2.push(segment);
t1 = t2;
break;
}
}
}
if (t1 < 1) {
segment = p1.split(t1, 1);
segment._t1 = map(t1, 0, 1, p1._t1, p1._t2);
segment._t2 = p1._t2;
pass2.push(segment);
}
});
return pass2;
}

View File

@@ -0,0 +1,133 @@
let shape1, shape2, ox=50, oy=50;
setup() {
let d = 30;
let p = [
{ x: d*2, y: d*1}, { x: d*1, y: d*2}, { x: d*1, y: d*4},
{ x: d*2, y: d*5}, { x: d*3, y: d*4}, { x: d*5, y: d*4},
{ x: d*6, y: d*5}, { x: d*7, y: d*4}, { x: d*7, y: d*2},
{ x: d*6, y: d*1}, { x: d*5, y: d*2}, { x: d*3, y: d*2},
]
shape1 = [
new Bezier(this, p[0].x, p[0].y, p[1].x, p[1].y, p[2].x, p[2].y, p[3].x, p[3].y),
new Bezier(this, p[3].x, p[3].y, p[4].x, p[4].y, p[5].x, p[5].y, p[6].x, p[6].y),
new Bezier(this, p[6].x, p[6].y, p[7].x, p[7].y, p[8].x, p[8].y, p[9].x, p[9].y),
new Bezier(this, p[9].x, p[9].y, p[10].x, p[10].y, p[11].x, p[11].y, p[0].x, p[0].y),
];
shape2 = [
new Bezier(this, p[0].x, p[0].y, p[1].x, p[1].y, p[2].x, p[2].y, p[3].x, p[3].y),
new Bezier(this, p[3].x, p[3].y, p[4].x, p[4].y, p[5].x, p[5].y, p[6].x, p[6].y),
new Bezier(this, p[6].x, p[6].y, p[7].x, p[7].y, p[8].x, p[8].y, p[9].x, p[9].y),
new Bezier(this, p[9].x, p[9].y, p[10].x, p[10].y, p[11].x, p[11].y, p[0].x, p[0].y),
];
// link the curves into paths
shape1.forEach((s, i) => (s.next = shape1[(i+1) % shape1.length]));
shape2.forEach((s, i) => (s.next = shape2[(i+1) % shape2.length]));
shape2.forEach(s => s.points.forEach(p => { p.x += ox; p.y += oy; }));
}
draw() {
clear();
/*
noFill();
shape2.forEach(c => c.points.forEach(p => {
p.x -= ox;
p.y -= oy;
}));
if (this.cursor.down) {
ox += this.cursor.diff.x;
oy += this.cursor.diff.y;
}
shape2.forEach(c => c.points.forEach(p => {
p.x += ox;
p.y += oy;
}));
shape1.forEach(curve => this.drawSegment(curve));
shape2.forEach(curve => this.drawSegment(curve));
this.drawBoolean(shape1, shape2);
*/
}
drawSegment(segment) {
setStroke( randomColor(0.2) );
start()
segment.getLUT(16).forEach(p => vertex(p.x, p.y))
end();
}
drawBoolean(s1, s2) {
let intersections = [];
// We're going to test for intersections in an *incredibly* naive fashion,
// simply checking each curve against each other curve. Normally you'd first
// throw way all curves that can't intersect, using bounding box checks or
// oct-tree space reduction, etc.
s1.forEach(curve1 => {
s2.forEach(curve2 => {
let ti = curve1.intersects(curve2);
if (ti.length) {
ti = ti.map(s => s.split(`/`).map(parseFloat));
// remove "near enough to be considered duplicate" t pairs
for(let i=ti.length-1; i>0; i--) {
if ( abs(ti[i][0] - ti[i-1][0]) < 0.01 && abs(ti[i][1] - ti[i-1][1]) < 0.01) {
ti.splice(i,1);
}
}
// store this curve pair with intersection t value(s)
intersections.push({ curve1, curve2, ti })
}
});
});
intersections.forEach(i => {
const { curve1, curve2, ti } = i;
ti.forEach(t => {
let c1 = curve1.get(t[0]); circle(c1.x, c1.y, 3);
let c2 = curve2.get(t[1]); circle(c2.x, c2.y, 3);
});
});
let nodes = [...s1, ...s2];
let sequence = [];
let node = nodes[0];
for(let i=0; i<2; i++) {
let entry = intersections.find(v => v.curve1 === node || v.curve2 === node);
if (entry) {
const { curve1, curve2, ti } = entry;
console.log(ti);
let c1, c2;
c1 = curve1.split(t[0]);
c2 = curve2.split(t[1]);
// resolve the intersections
console.log(`resolve `,entry);
sequence.push(node);
node = node.next;
} else {
sequence.push(node);
node = node.next;
}
}
sequence.forEach(c => c.drawCurve(`black`));
}
onMouseMove() {
if (this.cursor.down) {
redraw();
}
}

View File

@@ -1,3 +1,5 @@
# THIS SECTION IS CURRENTLY NOT PART OF THE MAIN DOCUMENT, AS IT DOES NOT ACTUALLY TEACH ANYTHING USEFUL.
# Boolean shape operations
We can apply the topics covered so far in this primer to effect boolean shape operations: getting the union, intersection, or exclusion, between two or more shapes that involve Bézier curves. For simplicity (well... sort of, more homogeneity), we'll be looking at poly-Bézier shapes only, but a shape that consists of a mix of lines and Bézier curves is technically a simplification. (Although it does mean we need to write a definition for the class of shapes that mix lines and Bézier curves. Since poly-Bézier curves are a superset, we'll be using those in the following examples.)
@@ -17,33 +19,32 @@ Once we have all the new poly-Bézier curves, we run the first step of the desir
- Union: discard all poly-Bézier curves that lie "inside" our union of our shapes. E.g. if we want the union of two overlapping circles, the resulting shape is the outline.
- Intersection: discard all poly-Bézier curves that lie "outside" the intersection of the two shapes. E.g. if we want the intersection of two overlapping circles, the resulting shape is the tapered ellipse where they overlap.
- Exclusion: none of the sections are discarded, but we will need to link the shapes back up in a special way. Flip any section that would qualify for removal under UNION rules.
- Exclusion: none of the sections are discarded, but we will need to link the shapes back up in a special way. Flip any section that would qualify for removal under "union" rules.
<table class="sketch"><tbody><tr>
<td class="labeled-image">
<div class="grid">
<figure>
<img src="images/op_base.gif" height="169"/>
Two overlapping shapes.
</td>
<td class="labeled-image">
<figcaption>Two overlapping shapes</figcaption>
</figure>
<figure class="labeled-image">
<img src="images/op_union.gif" height="169"/>
The unified region.
</td>
<td class="labeled-image">
<figcaption>Their union</figcaption>
</figure>
<figure class="labeled-image">
<img src="images/op_intersection.gif" height="169"/>
Their intersection.
</td>
<td class="labeled-image">
<figcaption>Their intersection</figcaption>
</figure>
<figure class="labeled-image">
<img src="images/op_exclusion.gif" height="169"/>
Their exclusion regions.
</td>
</tr></tbody></table>
<figcaption>Their exclusion (union minus intersection)</figcaption>
</figure>
</div>
The main complication in the outlined procedure here is determining how sections qualify in terms of being "inside" and "outside" of our shapes. For this, we need to be able to perform point-in-shape detection, for which we'll use a classic algorithm: getting the "crossing number" by using ray casting, and then testing for "insidedness" by applying the [even-odd rule](http://folk.uio.no/bjornw/doc/bifrost-ref/bifrost-ref-12.html): For any point and any shape, we can cast a ray from our point, to some point that we know lies outside of the shape (such as a corner of our drawing surface). We then count how many times that line crosses our shape (remember that we can perform line/curve intersection detection quite easily). If the number of times it crosses the shape's outline is even, the point did not actually lie inside our shape. If the number of intersections is odd, our point did lie inside out shape. With that knowledge, we can decide whether to treat a section that such a point lies on "needs removal" (under union rules), "needs preserving" (under intersection rules), or "needs flipping" (under exclusion rules).
These operations are expensive, and implementing your own code for this is generally a bad idea if there is already a geometry package available for your language of choice. In this case, for JavaScript the most excellent [Paper.js](http://paperjs.org) already comes with all the code in place to perform efficient boolean shape operations, so rather that implement an inferior version here, I can strongly recommend the Paper.js library if you intend to do any boolean shape work.
The following graphic shows Paper.js doing its thing for two shapes: one static, and one that is linked to your mouse pointer. If you move the mouse around, you'll see how the shape intersections are resolved. The base shapes are outlined in blue, and the boolean result is coloured red.
(Of course, as a general geometry library, Paper.js is also roughly the size of this entire primer, so for illustrative purposes the following graphic implements its own boolean operations, and may not do quite the right thing on all edge cases!)
<graphics-element title="Boolean shape operations" src="./boolean.js"></graphics-element>
<Graphic title="Boolean shape operations with Paper.js" paperjs={true} setup={this.setup} draw={this.draw} onMouseMove={this.onMouseMove}>
<button onclick="() => this.setMode(mode)">mode</button>
</Graphic>

File diff suppressed because it is too large Load Diff

View File

@@ -56,7 +56,7 @@ export default [
// "things made of more than on curve"
'polybezier',
'shapes',
// 'shapes', // I am not happy with how this section basically doesn't teach anything
// 'drawing', // still just waiting to be finished......
// curve offsetting