mirror of
https://bitbucket.org/Mattrixwv/octavefunctions.git
synced 2025-12-06 18:53:57 -05:00
96 lines
2.5 KiB
Matlab
96 lines
2.5 KiB
Matlab
% Bezier example
|
|
|
|
% This goes in a file named BezierExample.m
|
|
|
|
close all
|
|
clear all
|
|
|
|
x_nodes = [];
|
|
y_nodes = [];
|
|
|
|
% Initialize figure window
|
|
|
|
figure
|
|
hold on
|
|
xlim([0 1])
|
|
ylim([0 1])
|
|
|
|
% Collect nodes
|
|
|
|
disp('Click several points on curve. Hit enter to exit')
|
|
index = 1;
|
|
while(true)
|
|
[x,y,button] = ginput(1);
|
|
|
|
if (isempty(x))
|
|
break
|
|
end
|
|
|
|
if (button ~= 1)
|
|
continue
|
|
end
|
|
|
|
% Add the new point and plot the new line segment
|
|
|
|
x_nodes(index) = x(1);
|
|
y_nodes(index) = y(1);
|
|
if (index > 1)
|
|
plot(x_nodes(index-1:index),y_nodes(index-1:index))
|
|
end
|
|
|
|
index = index + 1;
|
|
end
|
|
|
|
% Points have been entered. Build the collection of nodes and control
|
|
% points that define the curve
|
|
|
|
number_curves = length(x_nodes) - 1;
|
|
bezier_points = cell(number_curves,4);
|
|
for k = 1:number_curves
|
|
|
|
% Insert the nodes
|
|
|
|
bezier_points{k,1} = [x_nodes(k) y_nodes(k)];
|
|
bezier_points{k,4} = [x_nodes(k+1) y_nodes(k+1)];
|
|
|
|
% Create the control points
|
|
|
|
if (k == 1)
|
|
bezier_points{k,2} = [x_nodes(1) y_nodes(1)] + ([x_nodes(2) y_nodes(2)] - [x_nodes(1) y_nodes(1)])/3;
|
|
else
|
|
|
|
% Compute positions for control points. Arbitrarily, they will be
|
|
% collinear with the node in between and 1/3 of the way to the next
|
|
% node
|
|
|
|
vector_1 = [x_nodes(k) y_nodes(k)] - [x_nodes(k-1) y_nodes(k-1)];
|
|
length_1 = norm(vector_1);
|
|
vector_1 = vector_1/length_1;
|
|
|
|
vector_2 = [x_nodes(k) y_nodes(k)] - [x_nodes(k+1) y_nodes(k+1)];
|
|
length_2 = norm(vector_2);
|
|
vector_2 = vector_2/length_2;
|
|
|
|
vector_sum = vector_1 + vector_2;
|
|
n = vector_sum/norm(vector_sum);
|
|
|
|
% If vector_1 X vector_2 is negative, reverse the direction of n
|
|
|
|
if ((vector_1(1)*vector_2(2) - vector_2(1)*vector_1(2)) < 0)
|
|
n = -n;
|
|
end
|
|
n_p = [-n(2) n(1)];
|
|
|
|
bezier_points{k-1,3} = [x_nodes(k) y_nodes(k)] + n_p*length_1/3;
|
|
bezier_points{k,2} = [x_nodes(k) y_nodes(k)] - n_p*length_2/3;
|
|
|
|
if (k == (number_curves))
|
|
|
|
bezier_points{k,3} = [x_nodes(number_curves+1) y_nodes(number_curves+1)] + ...
|
|
([x_nodes(number_curves) y_nodes(number_curves)] - [x_nodes(number_curves+1) y_nodes(number_curves+1)])/3;
|
|
end
|
|
end
|
|
end
|
|
|
|
PlotBezier(bezier_points)
|