./PaxHeaders.28738/geometry-3.0.00000644000000000000000000000013213066736044013206 xustar0030 mtime=1490795556.712871689 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/0002755000175000017500000000000013066736044013304 5ustar00olafolaf00000000000000geometry-3.0.0/PaxHeaders.28738/INDEX0000644000000000000000000000013213066736044013720 xustar0030 mtime=1490795556.556868803 30 atime=1490795556.556868803 30 ctime=1490795556.716871764 geometry-3.0.0/INDEX0000644000175000017500000001301713066736044014076 0ustar00olafolaf00000000000000geometry >> Computational Geometry 2D Descriptive geom2d_Contents points2d vectors2d angles2d edges2d rays2d lines2d boxes2d circles2d ellipses2d transforms2d polygons2d 2D Points centroid closedPath drawPoint findClosestPoint isCounterClockwise isPointOnRay isPointInCircle isPointOnCircle isPointOnLine isPointInEllipse midPoint minDistancePoints nndist polarPoint 2D Vectors createVector vectorNorm normalizeVector rotateVector 2D Angles angle2Points angle3Points angleAbsDiff angleDiff normalizeAngle vectorAngle angleSort lineAngle edgeAngle 2D Edges createEdge distancePointEdge drawCenteredEdge drawEdge edgeLength edgePosition edgeToLine intersectEdges intersectLineEdge reverseEdge transformEdge isPointOnEdge 2D Rays drawRay createRay 2D Lines cartesianLine createLine distancePointLine drawLine intersectLines isParallel isPerpendicular linePosition medianLine isLeftOriented orthogonalLine parallelLine pointOnLine projPointOnLine reverseLine 2D Polylines projPointOnPolyline intersectPolylines clipPolyline clipPolyline_clipper 2D Boxes clipEdge clipLine clipPoints clipRay mergeBoxes intersectBoxes drawBox randomPointInBox drawRect drawOrientedBox 2D Circles createCircle createDirectedCircle circleArcAsCurve circleAsPolygon drawCircleArc drawCircle enclosingCircle intersectCircles intersectLineCircle radicalAxis 2D Ellipses cov2ellipse drawEllipseArc drawEllipse ellipseAsPolygon ellipse2cov inertiaEllipse 2D Transformations transformLine transformPoint transformVector createBasisTransform createHomothecy createLineReflection createRotation createScaling createTranslation fitAffineTransform2d 2D Cubic Bezier drawBezierCurve cbezier2poly 2D Polygons convexHull curvature clipPolygon clipPolygon_clipper distancePointPolygon distancePointPolyline distancePolygons drawPolygon drawPolyline expandPolygon fillPolygon intersectEdgePolygon intersectLinePolygon isPointInPolygon isPolygonCCW isPolygonCW_Clipper joinPolygons medialAxisConvex minimumCaliperDiameter orientPolygon parametrize polygon2patch polygon2shape polygonArea polygonBounds polygonCentroid polygonContains polygonLoops polygonPoint polygons2d polygonSelfIntersections polygonSubcurve polylineSelfIntersections projPointOnPolyline rectAsPolygon reversePolygon reversePolyline simplifyPolygon simplifyPolyline splitPolygons supportFunction 2D Piecewise polynomial shapes curveval curve2polyline plotShape polygon2shape shape2polygon shapeCentroid transformShape 2D Polynomial curves drawPolynomialCurve polynomialCurveCentroid polynomialCurveDerivative polynomialCurveFit polynomialCurvePoint polynomialCurveSetFit 2D Others beltProblem bisector crackPattern2 crackPattern drawArrow drawLabels drawParabola drawShape hexagonalGrid squareGrid triangleGrid 3D Descriptive geom3d_Contents meshes3d_Contents angles3d boxes3d circles3d lines3d planes3d points3d polygons3d spheres vectors3d 3D Points anglePoints3d angleSort3d distancePoints drawPoint3d projPointOnPlane transformPoint3d transformVector3d 3D Lines clipLine3d distancePointLine3d drawLine3d intersectLinePlane intersectLineSphere linePosition3d transformLine3d 3D Edges drawEdge3d drawSphericalEdge 3D Planes createPlane drawPlane3d intersectPlaneSphere normalizePlane planeNormal planePoint planePosition projPointOnPlane 3D Meshes boxToMesh createCubeOctahedron createCube checkMeshAdjacentFaces clipConvexPolyhedronHP clipMeshVertices createDodecahedron createDurerPolyhedron createIcosahedron createMengerSponge createOctahedron createRhombododecahedron createSoccerBall createTetrahedron createTetrakaidecahedron cylinderMesh drawCube drawMesh drawFaceNormals drawPolyhedron ellipsoidMesh faceCentroids faceNormal intersectLineMesh3d intersectPlaneMesh mergeCoplanarFaces meshAdjacencyMatrix meshDihedralAngles meshEdgeFaces meshEdgeLength meshEdges meshFace meshFaceAdjacency meshFaceEdges meshFaceNumber meshFacePolygons meshSurfaceArea meshVolume minConvexHull polyhedra polyhedronCentroid polyhedronMeanBreadth polyhedronNormalAngle polyhedronSlice readMesh_off removeMeshVertices smoothMesh sphereMesh steinerPolytope subdivideMesh surfToMesh tetrahedronVolume torusMesh triangulateFaces trimMesh trimeshEdgeFaces trimeshMeanBreadth trimeshSurfaceArea vertexNormal 3D Spheres circle3dOrigin circle3dPoint circle3dPosition drawCircle3d drawCircleArc3d drawSphere drawSphericalTriangle 3D Boxes boundingBox3d box3dVolume drawBox3d 3D Polygons drawPolygon3d drawPolyline3d drawSphericalPolygon polygonArea3d 3D Transformations createRotation3dLineAngle createRotationOx createRotationOy createRotationOz createTranslation3d createScaling3d eulerAnglesToRotation3d recenterTransform3d rotation3dAxisAndAngle 3D Others cart2cyl cart2sph2 cart2sph2d cyl2cart drawAxis3d drawCylinder drawTorus drawVector3d revolutionSurface sph2cart2 sph2cart2d vectorAngle3d Geometric graphs descriptive graphs_Contents Geometric graphs creation boundedVoronoi2d centroidalVoronoi2d delaunayGraph knnGraph voronoi2d Geometric graphs visualization drawGraph drawGraphEdges drawNodeLabels Geometric graphs manipulation clipGraph clipGraphPolygon cvtUpdate Geometric graphs analysis grAdjacentEdges grAdjacentNodes grEdgeLengths grShortestPath Input @svg/svg @svg/plot @svg/getpath @svg/path2polygon @svg/normalize @svg/pathid @svg/height @svg/width Output data2geo Utils isAxisHandle geometry-3.0.0/PaxHeaders.28738/inst0000644000000000000000000000013113066736044014025 xustar0029 mtime=1490795556.69287132 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/0002755000175000017500000000000013066736044014261 5ustar00olafolaf00000000000000geometry-3.0.0/inst/PaxHeaders.28738/polygons2d0000644000000000000000000000013213066736044016126 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/0002755000175000017500000000000013066736044016361 5ustar00olafolaf00000000000000geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/drawPolygon.m0000644000000000000000000000013213066736044020666 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/drawPolygon.m0000644000175000017500000001656513066736044021057 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawPolygon (@var{coord}) ## @deftypefnx {Function File} {@var{h} = } drawPolygon (@var{px}, @var{py}) ## @deftypefnx {Function File} {@var{h} = } drawPolygon (@var{polys}) ## @deftypefnx {Function File} {@var{h} = } drawPolygon (@var{ax}, @dots{}) ## Draw a polygon specified by a list of points. ## ## drawPolygon (@var{coord}): ## Packs coordinates in a single N-by-2 array in the form: ## @code{[@var{x1}, @var{y1}; @var{x2}, @var{y2}; ... ; @var{xN}, @var{yN}]}. ## Multiple polygons may be drawn by using @code{[...; NaN, NaN; ...]} as a separator ## between coordinate sets. ## ## drawPolygon (@var{px}, @var{py}): ## Specifies coordinates with @var{x} and @var{y} components in separate ## column vectors. ## ## drawPolygon (@var{polys}): ## Packs coordinate of several polygons in a cell array. Each element of ## the cell array, @var{polys}, is a N-by-2 double array using the same form as described ## for @var{coord} above. ## ## drawPolygon (@var{ax}, @dots{}): ## Specifies the axis, @var{ax}, to draw the polygon on. ## ## @var{h} = drawPolygon (...): ## Also return a handle to the list of line objects. ## ## For more complete explanation of the polygon format and functions the ## user should reference the @code{polygons2d} function. ## ## @seealso{polygons2d, drawCurve} ## @end deftypefn function h = drawPolygon (px, varargin) # Store hold state state = ishold (gca); hold on; ## Check input if nargin < 1 print_usage (); end # check for empty polygons if isempty (px) return end ax = gca; if ( isAxisHandle (px) ) % extract handle of axis to draw on ax = px; px = varargin{1}; varargin(1) = []; end ## Manage cell arrays of polygons # case of a set of polygons stored in a cell array if iscell (px) opt = varargin(2:end); h = cellfun (@(x)drawPolygon (x, opt{:}), px, 'UniformOutput', 0); h = horzcat (h{:}); else # Check size vs number of arguments if (size (px, 2) == 1) if ( (nargin < 2) || (nargin == 2 && ~isnumeric(varargin{1})) ) error('Matgeom:invalid-input-arg', ... 'Should specify either a N-by-2 array, or 2 N-by-1 vectors'); else ## Parse coordinates and options # Extract coordinates of polygon vertices py = varargin{1}; varargin(1) = []; if (length (py) ~= length (px)) error ('Matgeom:invalid-input-arg', ... 'X and Y coordinates should have same numebr of rows (%d,%d)', ... length (px), length (px)) end end elseif (size (px, 2) == 2) py = px(:, 2); px = px(:, 1); else error('Matgeom:invalid-input-arg', 'Should specify a N-by-2 array'); end # Check case of polygons with holes if ( any (isnan (px(:)) ) ) polygons = splitPolygons ([px py]); h = drawPolygon (polygons, varargin{:}); else # set default line format if isempty (varargin) varargin = {'b-'}; end #TODO use patch to plot polygon txtarg = find (cellfun (@ischar, varargin)); if ismember ({'patch'},varargin(txtarg)) [~,tmp] = ismember ({'patch'}, varargin(txtarg)); varargin(txtarg(tmp)) = []; warning ('Matgeom:option-ignored', 'patch option is not implemented yet.\n'); endif ## Draw the polygon # ensure last point is the same as the first one px(end+1, :) = px(1,:); py(end+1, :) = py(1,:); # draw the polygon outline h = plot (px, py, varargin{:}); end % whether there where holes end % whether input arg was a cell if ~state hold off end end %!demo %! figure() %! p = [0 0; 0 1; 1 1; 1 0]; %ccw %! ph = p + [1.2 0]; %! # add hole %! ph(end+1,:) = nan; %! ph = [ph; ([0 0; 1 0; 1 1; 0 1]-[0.5 0.5])*0.5+[1.7 0.5]]; %! drawPolygon ({p, ph}); %!shared p, ph, pc, pch, opt %! p = [0 0; 0 1; 1 1; 1 0]; %ccw %! ph = p; %! # add hole %! ph(end+1,:) = nan; %! ph = [ph; ([0 0; 1 0; 1 1; 0 1]-[0.5 0.5])*0.5+[0.5 0.5]]; %! # cells %! pc = arrayfun(@()p+rand(length(p),2), 1:5, 'Uniformoutput', 0); %! pch = arrayfun(@()ph+rand(length(ph),2), 1:5, 'Uniformoutput', 0); %! # options %! opt = {'.-', 'color', 'r', 'linewidth', 2}; %!test %! fig = figure(); %! set (fig, 'visible', 'off'); %! # Cell %! h = drawPolygon (pc); %! h = drawPolygon (pc, opt{:}); %! close (fig) %!test %! fig = figure(); %! set (fig, 'visible', 'off'); %! # Cell with holes %! h = drawPolygon (pch); %! h = drawPolygon (pch, opt{:}); %! close (fig) %!test %! fig = figure(); %! set (fig, 'visible', 'off'); %! # X,Y coordinates in single array %! h = drawPolygon (p); %! h = drawPolygon (p, opt{:}); %! close (fig) %!test %! fig = figure(); %! set (fig, 'visible', 'off'); %! # X,Y coordinates in single array with holes %! h = drawPolygon (ph); %! h = drawPolygon (ph, opt{:}); %! close (fig) %!test %! fig = figure(); %! set (fig, 'visible', 'off'); %! # X,Y coordinates two arrays %! h = drawPolygon (p(:,1), p(:,2)); %! h = drawPolygon (p(:,1),p(:,2), opt{:}); %! close (fig) %!test %! fig = figure(); %! set (fig, 'visible', 'off'); %! # X,Y coordinates two arrays with holes %! h = drawPolygon (ph(:,1), ph(:,2)); %! h = drawPolygon (ph(:,1), ph(:,2), opt{:}); %! close (fig) %!error %! fig = figure(); %! set (fig, 'visible', 'off'); %! # Single bad-formed input arg %! h = drawPolygon (p(:,1)); %! h = drawPolygon (p(:,[1 1 2])); %! close (fig) %!warning %! fig = figure(); %! set (fig, 'visible', 'off'); %! # Future options %! opt_futur = {opt{:}, 'patch'}; %! h = drawPolygon (p, opt_futur{:}); %! h = drawPolygon (ph, opt_futur{:}); %! h = drawPolygon (pc, opt_futur{:}); %! h = drawPolygon (pch, opt_futur{:}); %! h = drawPolygon (p(:,1),p(:,2), opt_futur{:}); %! h = drawPolygon (ph(:,1), ph(:,2), opt_futur{:}); %! close (fig) geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/convexHull.m0000644000000000000000000000013213066736044020510 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/convexHull.m0000644000175000017500000000741013066736044020666 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %CONVEXHULL Convex hull of a set of points % % POLY = convexHull(POINTS) % Computes the convex hull of the set of points POINTS. This function is % mainly a wrapper to the convhull function, that format the result to a % polygon. % % [POLY, INDS] = convexHull(POINTS) % Also returns the indices of convex hull vertices within the original % array of points. % % ... = convexHull(POINTS, 'simplify', BOOL) % specifies the 'simplify' option use dfor calling convhull. By default, % the convexHull functions uses simplify equals to TRUE (contrary to the % convhull function), resulting in a more simple convex polygon. % % % Example % % Draws the convex hull of a set of random points % pts = rand(30,2); % drawPoint(pts, '.'); % hull = convexHull(pts); % hold on; % drawPolygon(hull); % % % Draws the convex hull of a paper hen % x = [0 10 20 0 -10 -20 -10 -10 0]; % y = [0 0 10 10 20 10 10 0 -10]; % poly = [x' y']; % hull = convexHull(poly); % figure; drawPolygon(poly); % hold on; axis equal; % drawPolygon(hull, 'm'); % % See also % polygons2d, convhull % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2011-04-08, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. function [hull, inds] = convexHull(points, varargin) % checkup on array size if size(points, 1) < 3 hull = points; inds = 1:size(points, 1); return; end % parse simplify option simplify = true; if nargin > 2 && strcmpi(varargin{1}, 'simplify') simplify = varargin{2}; end % compute convex hull by calling the 'convhull' function %inds = convhull(points(:,1), points(:,2), 'simplify', simplify); inds = convhull(points(:,1), points(:,2)); hull = points(inds, :); endfunction %!demo %! % Draws the convex hull of a set of random points %! pts = rand(30,2); %! drawPoint(pts, 'o'); %! hull = convexHull(pts); %! hold on; %! drawPolygon(hull); %!demo %! % Draws the convex hull of a paper hen %! x = [0 10 20 0 -10 -20 -10 -10 0]; %! y = [0 0 10 10 20 10 10 0 -10]; %! poly = [x' y']; %! hull = convexHull(poly); %! figure; drawPolygon(poly); %! hold on; axis equal; %! drawPolygon(hull, 'm'); geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/drawPolyline.m0000644000000000000000000000013213066736044021032 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/drawPolyline.m0000644000175000017500000001115413066736044021210 0ustar00olafolaf00000000000000## Copyright (C) 2003-2011 David Legland ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{} =} drawPolyline (@var{}, @var{}) ##DRAWPOLYLINE Draw a polyline specified by a list of points ## ## drawPolyline(COORD); ## packs coordinates in a single [N*2] array. ## ## drawPolyline(PX, PY); ## specifies coordinates in separate arrays. PX and PY must be column ## vectors with the same length. ## ## drawPolyline(..., TYPE); ## where TYPE is either 'closed' or 'open', specifies if last point must ## be connected to the first one ('closed') or not ('open'). ## Default is 'open'. ## ## drawPolyline(..., PARAM, VALUE); ## specify plot options as described for plot command. ## ## H = drawPolyline(...) also return a handle to the list of line objects. ## ## Example: ## @example ## # Draw a curve representing an ellipse ## t = linspace(0, 2*pi, 100)'; ## px = 10*cos(t); py = 5*sin(t); ## drawPolyline([px py], 'closed'); ## axis equal; ## ## # The same, with different drawing options ## drawPolyline([px py], 'closed', 'lineWidth', 2, 'lineStyle', '--'); ## @end example ## ## @seealso{polygons2d, drawPolygon} ## @end deftypefn function varargout = drawPolyline(varargin) # default values closed = false; # If first argument is a cell array, draw each curve individually, # and eventually returns handle of each plot. var = varargin{1}; if iscell(var) h = []; for i=1:length(var(:)) h = [h ; drawPolyline(var{i}, varargin{2:end})]; end if nargout>0 varargout{1}=h; end return; end # extract curve coordinate if size(var, 2)==1 # first argument contains x coord, second argument contains y coord px = var; if length(varargin)==1 error('Wrong number of arguments in drawPolyline'); end py = varargin{2}; varargin = varargin(3:end); else # first argument contains both coordinate px = var(:, 1); py = var(:, 2); varargin = varargin(2:end); end # check if curve is closed or open if ~isempty(varargin) var = varargin{1}; if strncmpi(var, 'close', 5) closed = true; varargin = varargin(2:end); elseif strncmpi(var, 'open', 4) closed = false; varargin = varargin(2:end); end end # if curve is closed, add first point at the end of the list if closed px = [px; px(1)]; py = [py; py(1)]; end # plot the curve, with eventually optional parameters h = plot(px, py, varargin{:}); # format output arguments if nargout>0 varargout{1}=h; end endfunction %!demo %! t = linspace (0, 2*pi, 100)'; %! px = 10*cos (t); py = 5*sin (t); %! %! subplot (1,2,1) %! drawPolyline ([px py], 'closed'); %! axis equal; %! %! subplot (1,2,2) %! drawPolyline([px py], 'closed', 'lineWidth', 2, 'lineStyle', '--'); %! axis equal; %! # ------------------------------------------------- %! # Draw a curve representing an ellipse with two drawing options geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/distancePolygons.m0000644000000000000000000000013213066736044021706 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/distancePolygons.m0000644000175000017500000000400713066736044022063 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dist} = } distancePolygons (@var{poly1},@var{poly2}) ## Compute the shortest distance between 2 polygons ## ## @end deftypefn function dist = distancePolygons(poly1, poly2) # compute distance of each vertex of a polygon to the other polygon dist1 = min(distancePointPolygon(poly1, poly2)); dist2 = min(distancePointPolygon(poly2, poly1)); # keep the minimum of the two distances dist = min(dist1, dist2); endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygonArea.m0000644000000000000000000000013213066736044020641 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygonArea.m0000644000175000017500000000752113066736044021022 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012-2016 Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{area} = } polygonArea (@var{points}) ## @deftypefnx {Function File} {@var{area} = } polygonArea (@var{px},@var{py}) ## Compute the signed area of a polygon. ## ## Compute area of a polygon defined by @var{points}. @var{points} is a N-by-2 ## matrix containing coordinates of vertices. The coordinates of the vertices of ## the polygon can also be given as two N-by-1 arrways @var{px}, @var{py}. ## ## Vertices of the polygon are supposed to be oriented Counter-Clockwise ## (CCW). In this case, the signed area is positive. ## If vertices are oriented Clockwise (CW), the signed area is negative. ## ## If polygon is self-crossing, the result is undefined. ## ## If the polygon contains holes the result is well defined only when the outer ## polygon is oriented CCW and the holes are oriented CW. In this case the ## resulting are is the sum of the signed areas. ## ## If @var{points} is a cell, each element is considered a polygon and the area ## of each one is returned in the array @var{area}. The matrix has the same shape ## as the cell. ## ## References: ## Algorithm adapted from P. Bourke web page ## http://paulbourke.net/geometry/polygonmesh/ ## ## @seealso{polygons2d, polygonCentroid, drawPolygon} ## @end deftypefn function A = polygonArea(px, py) # in case of polygon sets, computes several areas if iscell (px) A = cellfun (@func, px); else if (nargin == 2) px = [px py]; end A = func (px); end endfunction function a = func (c) if (any (isnan (c)) ) cc = splitPolygons (c); a = cellfun (@func, cc); a = sum (a); else N = size (c, 1); if (N < 3) a = 0; else iNext = [2:N 1]; a = sum (c(:,1) .* c(iNext,2) - c(iNext,1) .* c(:,2)) / 2; end end endfunction %!shared pccw, pcw %! pccw = pcw = [0 0; 1 0; 1 1; 0 1]; %! pcw([2 4],:) = pcw([4 2], :); %!assert (polygonArea (1, 0), 0); %!assert (polygonArea ([1 0 ;1 1]), 0); %!assert (polygonArea ([1; 1], [0; 1]), 0); %!assert (polygonArea (pccw), 1); %!assert (polygonArea (pcw), -1); %!assert (polygonArea ({pccw;pcw}), [1;-1]); %!assert (polygonArea ({pccw,pcw}), [1,-1]); %!assert (polygonArea([pccw; nan(1,2); 0.5*pcw+[0.25 0.25]]), 0.75) %!test %! ph = [pccw; nan(1,2); 0.5*pcw+[0.25 0.25]]; %! ph = {ph;ph}; %! assert (polygonArea(ph), [0.75; 0.75]) geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygons2d.m0000644000000000000000000000013213066736044020461 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygons2d.m0000644000175000017500000002177513066736044020651 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} polygons2d () ## Description of functions operating on 2D polygons ## ## The 'polygons' module contains functions operating on shapes composed ## of a vertex list, like polygons or polylines. ## ## We call 'polyline' the curve defined by a series of vertices. ## A polyline can be either closed or open, depending on whether the last ## vertex is connected to the first one or not. This can be given as an ## option is some functions in the module. ## A 'polygon' is the planar domain delimited by a closed polyline. We ## sometimes want to consider 'complex polygons', whose boundary is ## composed of several disjoint domains. The domain defined by a single ## closed polyline is called 'simple polygon'. ## We call 'curve' a polyline with many vertices, such that the polyline ## can be considered as a discrete approximation of a "real" curve. ## ## A simple polygon or polyline is represented by a N-by-2 array, each row ## of the array representing the coordinates of a vertex. ## Simple polygons are assumed to be closed, so there is no need to repeat ## the first vertex at the end. ## As both polygons and polylines can be represented by a list of vertex ## coordinates, some functions also consider the vertex list itself. Such ## functions are prefixed by 'pointSet'. Also, many functions prefixed by ## 'polygon' or 'polyline' works also on the other type of shape. ## ## For multiple-connected polygons, the different connected boundaries are ## separated by a row [NaN NaN]. ## ## For some functions, the orientation of the polygon can be relevant: CCW ## stands for 'Conter-Clockwise' (positive orientation), CW stands for ## 'Clockwise'. ## ## Polylines are parametrized in the following way: ## * the i-th vertex is located at position i-1 ## * points of the i-th edge have positions ranging linearly from i-1 to i ## The parametrization domain for an open polyline is from 0 to Nv-1, and ## from 0 to Nv for a closed polyline (positions 0 and Nv correspond to ## the same point). ## ## Example: ## # Simple polygon: ## P1 = [1 1;2 1;2 2;1 2]; ## drawPolygon(P1); ## axis([0 5 0 5]); ## # Multiple polygon: ## P2 = [10 10;40 10;40 40;10 40;NaN NaN;20 20;20 30;30 30;30 20]; ## figure;drawPolygon(P2); axis([0 50 0 50]); ## ## ## Point Sets ## pointSetBounds - Bounding box of a set of points ## pointSetsAverage - Compute the average of several point sets ## minimumCaliperDiameter - Minimum caliper diameter of a set of points ## findPoint - Find index of a point in an set from its coordinates ## ## Polylines ## polylinePoint - Extract a point from a polyline ## polylineLength - Return length of a polyline given as a list of points ## polylineCentroid - Compute centroid of a curve defined by a series of points ## polylineSubcurve - Extract a portion of a polyline ## reversePolyline - Reverse a polyline, by iterating vertices from the end ## isPointOnPolyline - Test if a point belongs to a polyline ## projPointOnPolyline - Compute position of a point projected on a polyline ## distancePointPolyline - Compute shortest distance between a point and a polyline ## distancePolylines - Compute the shortest distance between 2 polylines ## intersectPolylines - Find the common points between 2 polylines ## polylineSelfIntersections - Find self-intersections points of a polyline ## ## Curves (polylines with lot of vertices) ## parametrize - Parametrization of a curve, based on edges length ## curvature - Estimate curvature of a polyline defined by points ## cart2geod - Convert cartesian coordinates to geodesic coord. ## geod2cart - Convert geodesic coordinates to cartesian coord. ## curveMoment - Compute inertia moment of a 2D curve ## curveCMoment - Compute centered inertia moment of a 2D curve ## curveCSMoment - Compute centered scaled moment of a 2D curve ## ## Polygons ## polygonPoint - Extract a point from a polygon ## polygonSubcurve - Extract a portion of a polygon ## reversePolygon - Reverse a polygon, by iterating vertices from the end ## projPointOnPolygon - Compute position of a point projected on a polygon ## splitPolygons - Convert a NaN separated polygon list to a cell array of polygons ## clipPolygon - Clip a polygon with a rectangular box ## clipPolygonHP - Clip a polygon with a Half-plane defined by a directed line ## intersectLinePolygon - Intersection points between a line and a polygon ## intersectRayPolygon - Intersection points between a ray and a polygon ## polygonSelfIntersections - Find-self intersection points of a polygon ## convexHull - Convex hull of a set of points ## polygonLoops - Divide a possibly self-intersecting polygon into a set of simple loops ## expandPolygon - Expand a polygon by a given (signed) distance ## medialAxisConvex - Compute medial axis of a convex polygon ## ## Measures on Polygons ## isPointInPolygon - Test if a point is located inside a polygon ## polygonContains - Test if a point is contained in a multiply connected polygon ## polygonCentroid - Compute the centroid (center of mass) of a polygon ## polygonArea - Compute the signed area of a polygon ## polygonLength - Perimeter of a polygon ## polygonNormalAngle - Compute the normal angle at a vertex of the polygon ## polygonBounds - Compute the bounding box of a polygon ## distancePointPolygon - Compute shortest distance between a point and a polygon ## distancePolygons - Compute the shortest distance between 2 polygons ## ## Triangles ## isPointInTriangle - Test if a point is located inside a triangle ## triangleArea - Area of a triangle ## ## Functions from stochastic geometry ## steinerPoint - Compute steiner point (weighted centroid) of a polygon ## steinerPolygon - Create a Steiner polygon from a set of vectors ## supportFunction - Compute support function of a polygon ## convexification - Compute the convexification of a polygon ## ## Input, Output and conversions ## readPolygon - Read a polygon stored in a file ## polygonToRow - Convert polygon coordinates to a row vector ## rowToPolygon - Create a polygon from a row vector ## rectAsPolygon - Convert a (centered) rectangle into a series of points ## ## Drawing functions ## drawPolyline - Draw a polyline specified by a list of points ## drawPolygon - Draw a polygon specified by a list of points ## fillPolygon - Fill a polygon specified by a list of points ## ## ## Credits: ## * function intersectPolylines uses the 'interX' contribution from "NS" ## (file exchange 22441, called 'curve-intersections') ## ## ----- ## Author: David Legland ## e-mail: david.legland@@grignon.inra.fr ## created the 07/11/2005. ## Homepage: @url{http://matgeom.sourceforge.net/} ## @url{http://www.pfl-cepia.inra.fr/index.php?page=geom2d} ## Copyright INRA - Cepia Software Platform. ## ## @end deftypefn function polygons2d () help('polygons2d'); endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/parametrize.m0000644000000000000000000000013213066736044020704 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/parametrize.m0000644000175000017500000000725313066736044021067 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{par} = } parametrize (@var{poly}) ## @deftypefnx {Function File} {@var{par} = } parametrize (@var{px},@var{py}) ## @deftypefnx {Function File} {@var{par} = } parametrize (@dots{},@var{normalize}) ## ## Parametrization of a curve, based on edges length ## ## Returns a parametrization of the curve defined by the serie of points, ## based on euclidean distance between two consecutive points. ## POLY is a N-by-2 array, representing coordinates of vertices. The ## result PAR is N-by-1, and contains the cumulative length of edges until ## corresponding vertex. The function also accepts the polygon as two inputs ## @var{px} and @var{py} representinx coordinates x and y respectively. ## When optional argument @var{normalize} is non-empty @var{par} is rescaled ## such that the last element equals 1, i.e. @code{@var{par}(end)==1}. ## ## Example ## @example ## # Parametrize a circle approximation ## poly = circleToPolygon([0 0 1], 200); ## p = parametrize(poly); ## p(end) ## ans = ## 6.2829 ## p = parametrize(poly,'norm'); ## p(end) ## ans = ## 1 ## p = parametrize(poly,true); ## p(end) ## ans = ## 1 ## @end example ## ## @seealso{polygons2d, polylineLength} ## @end deftypefn function par = parametrize(varargin) ## Process inputs # extract vertex coordinates if size(varargin{1}, 2) > 1 # vertices in a single array pts = varargin{1}; normalize = numel(varargin) > 1; elseif size(varargin{1}, 2) == 1 && numel(varargin) >= 2 # points as separate arrays pts = [varargin{1} varargin{2}]; normalize = numel(varargin) > 2; end ## Parametrize polyline # compute cumulative sum of euclidean distances between consecutive # vertices, setting distance of first vertex to 0. if size(pts, 2) == 2 # process points in 2D par = [0 ; cumsum(hypot(diff(pts(:,1)), diff(pts(:,2))))]; else # process points in arbitrary dimension par = [0 ; cumsum(sqrt(sum(diff(pts).^2, 2)))]; end # eventually rescale between 0 and 1 if normalize par = par / par(end); end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/intersectEdgePolygon.m0000644000000000000000000000013213066736044022516 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/intersectEdgePolygon.m0000644000175000017500000000572513066736044022703 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %INTERSECTEDGEPOLYGON Intersection point of an edge with a polygon % % INTER = intersectEdgePolygon(EDGE, POLY) % Computes intersection(s) point(s) between the edge EDGE and the polygon % POLY. EDGE is given by [x1 y1 x2 y2]. POLY is a N-by-2 array of vertex % coordinates. % INTER is a M-by-2 array containing coordinates of intersection(s). It % can be empty if no intersection is found. % % [INTER INDS] = intersectEdgePolygon(EDGE, POLY) % Also returns index/indices of edge(s) involved in intersections. % % Example % % Intersection of an edge with a square % poly = [0 0;10 0;10 10;0 10]; % edge = [9 2 9+3*1 2+3*2]; % exp = [10 4]; % inter = intersectEdgePolygon(edge, poly) % ans = % 10 4 % % See also % edges2d, polygons2d, intersectLinePolygon, intersectRayPolygon % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-02-24, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. function [intersects, inds] = intersectEdgePolygon(edge, poly, varargin) % get computation tolerance tol = eps; if ~isempty(varargin) tol = varargin{1}; end line = edgeToLine(edge); [intersects, inds] = intersectLinePolygon(line, poly, tol); if ~isempty(intersects) pos = linePosition(intersects, line); keep = pos >= 0 & pos <= 1; intersects = intersects(keep, :); inds = inds(keep); end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/intersectPolylines.m0000644000000000000000000000013213066736044022260 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/intersectPolylines.m0000644000175000017500000001107613066736044022441 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %INTERSECTPOLYLINES Find the common points between 2 polylines % % INTERS = intersectPolylines(POLY1, POLY2) % Returns the intersection points between two polylines. Each polyline is % defined by a N-by-2 array representing coordinates of its vertices: % [X1 Y1 ; X2 Y2 ; ... ; XN YN] % INTERS is a NP-by-2 array containing coordinates of intersection % points. % % INTERS = intersectPolylines(POLY1) % Compute self-intersections of the polyline. % % Example % % Compute intersection points between 2 simple polylines % poly1 = [20 10 ; 20 50 ; 60 50 ; 60 10]; % poly2 = [10 40 ; 30 40 ; 30 60 ; 50 60 ; 50 40 ; 70 40]; % pts = intersectPolylines(poly1, poly2); % figure; hold on; % drawPolyline(poly1, 'b'); % drawPolyline(poly2, 'm'); % drawPoint(pts); % axis([0 80 0 80]); % % This function is largely based on the 'interX' function, found on the % FileExchange: % https://fr.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections % % See also % polygons2d, polylineSelfIntersections, intersectLinePolygon function pts = intersectPolylines(poly1, varargin) % Check number of inputs narginchk(1, 2); % Specific init depending on number of inputs if nargin == 1 % Compute self-intersections % -> Avoid the inclusion of common points poly2 = poly1; hF = @lt; else % Compute intersections between distinct lines poly2 = varargin{1}; hF = @le; end % Get coordinates of polyline vertices x1 = poly1(:,1); x2 = poly2(:,1)'; y1 = poly1(:,2); y2 = poly2(:,2)'; % differentiate coordinate arrays dx1 = diff(x1); dy1 = diff(y1); dx2 = diff(x2); dy2 = diff(y2); % Determine 'signed distances' S1 = dx1 .* y1(1:end-1) - dy1 .* x1(1:end-1); S2 = dx2 .* y2(1:end-1) - dy2 .* x2(1:end-1); C1 = feval(hF, D(bsxfun(@times,dx1,y2) - bsxfun(@times,dy1,x2), S1), 0); C2 = feval(hF, D((bsxfun(@times,y1,dx2) - bsxfun(@times,x1,dy2))', S2'), 0)'; % Obtain the segments where an intersection is expected [i, j] = find(C1 & C2); % Process case of no intersection if isempty(i) pts = zeros(0, 2); return; end % Transpose and prepare for output i=i'; dx2=dx2'; dy2=dy2'; S2 = S2'; L = dy2(j).*dx1(i) - dy1(i).*dx2(j); % Avoid divisions by zero i = i(L~=0); j = j(L~=0); L = L(L~=0); % Solve system of eqs to get the common points res = [dx2(j).*S1(i) - dx1(i).*S2(j), dy2(j).*S1(i) - dy1(i).*S2(j)] ./ [L L]; pts = unique(res, 'rows'); % Innre function computing a kind of cross-product function u = D(x,y) u = bsxfun(@minus, x(:,1:end-1), y) .* bsxfun(@minus, x(:,2:end), y); endfunction endfunction %!demo %! poly1 = [20 10 ; 20 50 ; 60 50 ; 60 10]; %! poly2 = [10 40 ; 30 40 ; 30 60 ; 50 60 ; 50 40 ; 70 40]; %! pts = intersectPolylines(poly1, poly2); %! figure; hold on; %! drawPolyline(poly1, 'b'); %! drawPolyline(poly2, 'm'); %! drawPoint(pts); %! axis([0 80 0 80]); %! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %! % Compute intersection points between 2 simple polylines geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/splitPolygons.m0000644000000000000000000000013213066736044021247 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/splitPolygons.m0000644000175000017500000000603413066736044021426 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012-2016 Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{polygons} = } splitPolygons (@var{polygon}) ## Convert a NaN separated polygon list to a cell array of polygons. ## ## @var{polygon} is a N-by-M array of points, with possibly couples of NaN values. ## The functions separates each component separated by NaN values, and ## returns a cell array of polygons. ## ## @seealso{polygons2d} ## @end deftypefn function [polygons inds] = splitPolygons(polygon) if iscell (polygon) # TODO: cell of nan separated polygons # case of a cell array error ("geometry:invalid-input-arg", ... "splitPolygons: can't handle cell of nan separated polygons"); %polygons = polygon; else breakr = isnan (polygon(:,1)); if all (~breakr) # single polygon -> no break polygons = {polygon}; else # find indices of NaN couples inds = find (breakr); # number of polygons N = length (inds); polygons = cell (N+1, 1); # iterate over NaN-separated regions to create new polygon polygons{1} = polygon(1:(inds(1)-1), :); polygons{end} = polygon((inds(end)+1):end, :); for i=2:N polygons{i} = polygon((inds(i-1)+1):(inds(i)-1), :); end end end endfunction %!test %! p = [1; nan; 2]; pc = {1;2}; %! assert (splitPolygons (p), pc); %!test %! p = [1; nan; 2; nan; 3]; pc = {1;2;3}; %! assert (splitPolygons (p), pc); %!test %! p = [1; nan; 2; nan; 3]; idx_ = [2;4]; %! [~,idx] = splitPolygons (p); %! assert (idx, idx_) geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/isPolygonCW_Clipper.m0000644000000000000000000000013213066736044022254 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/isPolygonCW_Clipper.m0000644000175000017500000000325013066736044022430 0ustar00olafolaf00000000000000## Copyright (C) 2015-2017 Philip Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{orientation}] = isPolygonCW_Clipper (@var{inpol}) ## Inspect winding direction of polygon(s). ## ## Based on Clipper library (polyclipping.sf.net / 3rd Party / Matlab) ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## whose winding direction should be assessed. Subpolygons are separated by ## [NaN NaN] rows. ## ## Output argument @var{orientation} contains the winding direction(s) of ## each subpolygon: 0 for clockwise, 1 for counterclockwise. ## ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2015-05-03 function [orientation] = isPolygonCW_Clipper (inpoly) ## Input validation if (nargin < 1) print_usage (); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error ("ispolycw: inpoly should be a numeric Nx2 array"); endif inpol = __dbl2int64__ (inpoly); ## Just find out orientation of polygons orientation = clipper (inpol); endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/medialAxisConvex.m0000644000000000000000000000013213066736044021624 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/medialAxisConvex.m0000644000175000017500000001323513066736044022004 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{n} @var{e}] = } medialAxisConvex (@var{polygon}) ## Compute medial axis of a convex polygon ## ## @var{polygon} is given as a set of points [x1 y1;x2 y2 ...], returns ## the medial axis of the polygon as a graph. ## @var{n} is a set of nodes. The first elements of @var{n} are the vertices of the ## original polygon. ## @var{e} is a set of edges, containing indices of source and target nodes. ## Edges are sorted according to order of creation. Index of first vertex ## is lower than index of last vertex, i.e. edges always point to newly ## created nodes. ## ## Notes: ## - Is not fully implemented, need more development (usually crashes for ## polygons with more than 6-7 points...) ## - Works only for convex polygons. ## - Complexity is not optimal: this algorithm is O(n*log n), but linear ## algorithms exist. ## ## @seealso{polygons2d, bisector} ## @end deftypefn function [nodes, edges] = medialAxisConvex(points) # eventually remove the last point if it is the same as the first one if points(1,:) == points(end, :) nodes = points(1:end-1, :); else nodes = points; end # special case of triangles: # compute directly the gravity center, and simplify computation. if size(nodes, 1)==3 nodes = [nodes; mean(nodes, 1)]; edges = [1 4;2 4;3 4]; return end # number of nodes, and also of initial rays N = size(nodes, 1); # create ray of each vertex rays = zeros(N, 4); rays(1, 1:4) = bisector(nodes([2 1 N], :)); rays(N, 1:4) = bisector(nodes([1 N N-1], :)); for i=2:N-1 rays(i, 1:4) = bisector(nodes([i+1, i, i-1], :)); end # add indices of edges producing rays (indices of first vertex, second # vertex is obtained by adding one modulo N). rayEdges = [[N (1:N-1)]' (1:N)']; pint = intersectLines(rays, rays([2:N 1], :)); #ti = linePosition(pint, rays); #ti = min(linePosition(pint, rays), linePosition(pint, rays([2:N 1], :))); ti = distancePointLine(pint, ... createLine(points([N (1:N-1)]', :), points((1:N)', :))); # create list of events. # terms are : R1 R2 X Y t0 # R1 and R2 are indices of involved rays # X and Y is coordinate of intersection point # t0 is position of point on rays events = sortrows([ (1:N)' [2:N 1]' pint ti], 5); # initialize edges edges = zeros(0, 2); # ------------------- # process each event until there is no more # start after index of last vertex, and process N-3 intermediate rays for i=N+1:2*N-3 # add new node at the rays intersection nodes(i,:) = events(1, 3:4); # add new couple of edges edges = [edges; events(1,1) i; events(1,2) i]; # find the two edges creating the new emanating ray n1 = rayEdges(events(1, 1), 1); n2 = rayEdges(events(1, 2), 2); # create the new ray line1 = createLine(nodes(n1, :), nodes(mod(n1,N)+1, :)); line2 = createLine(nodes(mod(n2,N)+1, :), nodes(n2, :)); ray0 = bisector(line1, line2); # set its origin to emanating point ray0(1:2) = nodes(i, :); # add the new ray to the list rays = [rays; ray0]; rayEdges(size(rayEdges, 1)+1, 1:2) = [n1 n2]; # find the two neighbour rays ind = sum(ismember(events(:,1:2), events(1, 1:2)), 2)==0; ir = unique(events(ind, 1:2)); ir = ir(~ismember(ir, events(1,1:2))); # create new intersections pint = intersectLines(ray0, rays(ir, :)); #ti = min(linePosition(pint, ray0), linePosition(pint, rays(ir, :))) + events(1,5); ti = distancePointLine(pint, line1); # remove all events involving old intersected rays ind = sum(ismember(events(:,1:2), events(1, 1:2)), 2)==0; events = events(ind, :); # add the newly formed events events = [events; ir(1) i pint(1,:) ti(1); ir(2) i pint(2,:) ti(2)]; # and sort them according to 'position' parameter events = sortrows(events, 5); end # centroid computation for last 3 rays nodes = [nodes; mean(events(:, 3:4))]; edges = [edges; [unique(events(:,1:2)) ones(3, 1)*(2*N-2)]]; endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/reversePolygon.m0000644000000000000000000000013213066736044021404 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/reversePolygon.m0000644000175000017500000000372313066736044021565 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{poly2} = } reversePolygon (@var{poly}) ## Reverse a polygon, by iterating vertices from the end ## ## POLY2 = reversePolygon(POLY) ## POLY2 has same vertices as POLY, but in different order. The first ## vertex of the polygon is still the same. ## ## @seealso{reversePolyline} ## @end deftypefn function rev = reversePolygon(poly) rev = poly([1 end:-1:2], :); endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygon2shape.m0000644000000000000000000000013213066736044021153 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygon2shape.m0000644000175000017500000000525213066736044021333 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{shape} = } polygon2shape (@var{polygon}) ## Converts a polygon to a shape with edges defined by smooth polynomials. ## ## @var{polygon} is a N-by-2 matrix, each row representing a vertex. ## @var{shape} is a N-by-1 cell, where each element is a pair of polynomials ## compatible with polyval. ## ## In its current state, the shape is formed by polynomials of degree 1. Therefore ## the shape representation costs more memory except for colinear points in the ## polygon. ## ## @seealso{shape2polygon, simplifyPolygon, polyval} ## @end deftypefn function shape = polygon2shape (polygon) # Filter colinear points polygon = simplifyPolygon (polygon); np = size(polygon,1); # polygonal shapes are memory inefficient!! # TODO filter the regions where edge angles are canging slowly and fit # polynomial of degree 3; pp = nan (2*np,2); # Transform edges into polynomials of degree 1; # pp = [(p1-p0) p0]; pp(:,1) = diff(polygon([1:end 1],:)).'(:); pp(:,2) = polygon.'(:); shape = mat2cell(pp, 2*ones (1,np), 2); endfunction %!test %! pp = [0 0; 1 0; 1 1; 0 1]; %! s = polygon2shape (pp); geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/isPointInPolygon.m0000644000000000000000000000013213066736044021645 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/isPointInPolygon.m0000644000175000017500000000700413066736044022022 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %ISPOINTINPOLYGON Test if a point is located inside a polygon % % B = isPointInPolygon(POINT, POLYGON) % Returns true if the point is located within the given polygon. % % This function is simply a wrapper for the function inpolygon, to avoid % decomposition of point and polygon coordinates. % % Example % pt1 = [30 20]; % pt2 = [30 5]; % poly = [10 10;50 10;50 50;10 50]; % isPointInPolygon([pt1;pt2], poly) % ans = % 1 % 0 % % poly = [0 0; 10 0;10 10;0 10;NaN NaN;3 3;3 7;7 7;7 3]; % pts = [5 1;5 4]; % isPointInPolygon(pts, poly); % ans = % 1 % 0 % % % See also % points2d, polygons2d, inpolygon, isPointInTriangle % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2009-06-19, using Matlab 7.7.0.471 (R2008b) % Copyright 2009 INRA - Cepia Software Platform. % HISTORY % 2013-04-24 add support for multiply connected polygons function b = isPointInPolygon(point, poly) % In case of a multiple polygon, decompose into a set of contours, and % performs test for each contour if iscell(poly) || any(isnan(poly(:))) % transform as a cell array of simple polygons polygons = splitPolygons(poly); N = length(polygons); Np = size(point, 1); % compute orientation of polygon, and format to have Np*N matrix areas = zeros(N, 1); for i = 1:N areas(i) = polygonArea(polygons{i}); end ccw = areas > 0; ccw = repmat(ccw', Np, 1); % test if point inside each polygon in = false(size(point, 1), N); for i = 1:N poly = polygons{i}; in(:, i) = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); end % count polygons containing point, weighted by polygon orientation b = sum(in.*(ccw==1) - in.*(ccw==0), 2) > 0; else % standard test for simple polygons b = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/joinPolygons.m0000644000000000000000000000013213066736044021053 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/joinPolygons.m0000644000175000017500000000353113066736044021231 0ustar00olafolaf00000000000000## Copyright (C) 2016 Philip Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {} {@var{outpol} =} joinPolygons (@var{inpol}) ## Convert a cell style set of polygons into an array of subpolygons ## separated by NaN rows. ## ## @var{inpol} is expected to be an Nx1 (column) cell array with each cell ## containing a matrix of Mx1 (X), Mx2 (X,Y), or Mx3 (X,Y,Z) coordinates. ## ## @var{outpol} is a numeric Px1, Px2 or Px3 array os subpolygons each ## separated by a row of NaN values. ## ## @seealso{splitPolygons} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2016-05-10 function [polys] = joinPolygons (poly) if (! iscell (poly)) error ("joinPolygons: cell array expected"); elseif (isempty (poly)) polys = []; return endif XY(1:2:2*size (poly, 1), :) = [{poly{:}}']; XY(2:2:2*size (poly, 1) - 1, :) = NaN (1, size (poly{1}, 2)); polys = cell2mat (XY); endfunction %!test %! assert (joinPolygons ({1 2}), [1 2]); %!test %! assert (joinPolygons ({}), []); %!test %! XY = joinPolygons ({[1 6; 2 5; 3 4]; [4 3; 5 2; 6 1]}); %! assert (XY, [1 6; 2 5; 3 4; NaN NaN; 4 3; 5 2; 6 1]); %!error joinPolygons ([1 2 NaN 3 4], [56 NaN 78]) geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygonPoint.m0000644000000000000000000000013213066736044021062 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygonPoint.m0000644000175000017500000000560113066736044021240 0ustar00olafolaf00000000000000## Copyright (C) 2003-2011 David Legland ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} =} polygonPoint (@var{poly}, @var{pos}) ## Extract a point from a polygon ## @seealso{polygons2d, polylinePoint} ## @end deftypefn function point = polygonPoint(poly, pos) # eventually copy first point at the end to ensure closed polygon if sum(poly(end, :)==poly(1,:))~=2 poly = [poly; poly(1,:)]; end # number of points to compute Np = length(pos(:)); # number of vertices in polygon Nv = size(poly, 1)-1; # allocate memory results point = zeros(Np, 2); # iterate on points for i=1:Np # compute index of edge (between 0 and Nv) ind = floor(pos(i)); # special case of last point of polyline if ind==Nv point(i,:) = poly(end,:); continue; end # format index to ensure being on polygon ind = min(max(ind, 0), Nv-1); # position on current edge t = min(max(pos(i)-ind, 0), 1); # parameters of current edge x0 = poly(ind+1, 1); y0 = poly(ind+1, 2); dx = poly(ind+2,1)-x0; dy = poly(ind+2,2)-y0; # compute position of current point point(i, :) = [x0+t*dx, y0+t*dy]; end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polylineSelfIntersections.m0000644000000000000000000000013213066736044023600 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polylineSelfIntersections.m0000644000175000017500000001477113066736044023766 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pts} = } polylineSelfIntersections (@var{poly}) ## @deftypefnx {Function File} {@var{pts} = } polylineSelfIntersections (@var{poly},@asis{'tolerance'},@var{tol}) ## Find self-intersections points of a polyline ## ## Return the position of self intersection points ## ## Also return the 2 positions of each intersection point (the position ## when meeting point for first time, then position when meeting point ## for the second time). ## ## Specifies an additional tolerance parameter to decide whether two intersection ## points should be considered the same, based on their euclidean ## distance. ## ## Example ## @example ## # use a gamma-shaped polyline ## poly = [0 0;0 10;20 10;20 20;10 20;10 0]; ## polylineSelfIntersections(poly) ## ans = ## 10 10 ## ## # use a 'S'-shaped polyline ## poly = [10 0;0 0;0 10;20 10;20 20;10 20]; ## polylineSelfIntersections(poly) ## ans = ## 10 10 ## @end example ## ## @seealso{polygons2d, intersectPolylines, polygonSelfIntersections} ## @end deftypefn function varargout = polylineSelfIntersections(poly, varargin) %% Initialisations % flag indicating whether the polyline is closed (polygon) or not closed = false; % the tolerance for comparing positions based on distances tol = sqrt (eps); % determine whether the polyline is open or closed if ~isempty(varargin) closed = varargin{1}; if ischar(closed) if strcmp(closed, 'closed') closed = true; varargin(1) = []; elseif strcmp(closed, 'open') closed = false; varargin(1) = []; end end end % parse optional arguments while length(varargin) > 1 pname = varargin{1}; if ~ischar(pname) error('Expect optional arguments as name-value pairs'); end if strcmpi(pname, 'tolerance') tol = varargin{2}; else error(['Unknown parameter name: ' pname]); end varargin(1:2) = []; end % if polyline is closed, ensure the last point equals the first one if closed if sum(abs(poly(end, :) - poly(1,:)) < tol) ~= 2 poly = [poly; poly(1,:)]; end end % arrays for storing results points = zeros(0, 2); pos1 = zeros(0, 1); pos2 = zeros(0, 1); % number of edges nEdges = size(poly, 1) - 1; %% Main processing % index of current intersection ip = 0; % iterate over each couple of edge ( (N-1)*(N-2)/2 iterations) for iEdge1 = 1:nEdges-1 % create first edge edge1 = [poly(iEdge1, :) poly(iEdge1+1, :)]; for iEdge2 = iEdge1+2:nEdges % create second edge edge2 = [poly(iEdge2, :) poly(iEdge2+1, :)]; % check conditions on bounding boxes, to avoid computing the % intersections if min(edge1([1 3])) > max(edge2([1 3])) continue; end if max(edge1([1 3])) < min(edge2([1 3])) continue; end if min(edge1([2 4])) > max(edge2([2 4])) continue; end if max(edge1([2 4])) < min(edge2([2 4])) continue; end % compute intersection point inter = intersectEdges(edge1, edge2, tol); if sum(isfinite(inter)) == 2 % add point to the list ip = ip + 1; points(ip, :) = inter; % also compute positions on the polyline pos1(ip, 1) = iEdge1 - 1 + edgePosition(inter, edge1); pos2(ip, 1) = iEdge2 - 1 + edgePosition(inter, edge2); end end end %% Post-processing % if polyline is closed, the first vertex was found as an intersection, so % we need to remove it if closed % identify the intersection between first and last edges using position % indices (pos1 < pos2 by construction) ind = pos1 == 0 & pos2 == size(poly,1)-1; points(ind,:) = []; pos1(ind) = []; pos2(ind) = []; end % remove multiple intersections [points, I, J] = unique(points, 'rows', 'first'); %#ok pos1 = pos1(I); pos2 = pos2(I); % remove multiple intersections, using tolerance on distance iInter = 0; while iInter < size(points, 1) - 1 iInter = iInter + 1; % for iInter = 1:size(points, 1)-1 % determine distance between current point and remaining points inds = iInter+1:size(points, 1); dists = distancePoints(points(iInter,:), points(inds, :)); % identify index of other points located in a close neighborhood inds = inds(dists < tol); % remove redundant intersection points if ~isempty(inds) points(inds, :) = []; pos1(inds) = []; pos2(inds) = []; end end %% process output arguments if nargout <= 1 varargout{1} = points; elseif nargout == 3 varargout{1} = points; varargout{2} = pos1; varargout{3} = pos2; end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygonContains.m0000644000000000000000000000013213066736044021547 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygonContains.m0000644000175000017500000000572313066736044021732 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %POLYGONCONTAINS Test if a point is contained in a multiply connected polygon % % B = polygonContains(POLYGON, POINT); % Returns TRUE if the (possibly multi-connected) polygon POLYGON contains % the point(s) given by POINT. % This is an extension of the Matlab function inpolygon for the case of % polygons with holes. % % Example % POLY = [0 0; 10 0;10 10;0 10;NaN NaN;3 3;3 7;7 7;7 3]; % PT = [5 1;5 4]; % polygonContains(POLY, PT); % ans = % 1 % 0 % % See also % polygons2d, inpolygon, isPointInPolygon % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2007-10-11, using Matlab 7.4.0.287 (R2007a) % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. function varargout = polygonContains(poly, point) % transform as a cell array of simple polygons polygons = splitPolygons(poly); N = length(polygons); Np = size(point, 1); % compute orientation of polygon, and format to have Np*N matrix areas = zeros(N, 1); for i = 1:N areas(i) = polygonArea(polygons{i}); end ccw = areas > 0; ccw = repmat(ccw', Np, 1); % test if point inside each polygon in = false(size(point, 1), N); for i = 1:N poly = polygons{i}; in(:, i) = inpolygon(point(:,1), point(:,2), poly(:,1), poly(:,2)); end % count polygons containing point, weighted by polygon orientation res = sum(in.*(ccw==1) - in.*(ccw==0), 2); varargout{1} = res; endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/rectAsPolygon.m0000644000000000000000000000013213066736044021152 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/rectAsPolygon.m0000644000175000017500000000567613066736044021344 0ustar00olafolaf00000000000000## Copyright (C) 2003-2011 David Legland ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{p} =} rectAsPolygon (@var{rect}) ## @deftypefnx {Function File} {[@var{x}, @var{y}] =} rectAsPolygon (@var{rect}) ## Convert a (centered) rectangle into a series of points ## ## Converts rectangle given as [x0 y0 w h] or [x0 y0 w h theta] into a ## 4*2 array double, containing coordinate of rectangle vertices. ## with two output arguments the coordinates are splitted in @var{x} and @var{y}. ## ## @seealso{polygons2d, drawRect, drawRect2, drawPolygon, drawShape} ## @end deftypefn function [tx ty] = rectAsPolygon (rect) theta = 0; x = rect(1); y = rect(2); w = rect(3) / 2; # easier to compute with w and h divided by 2 h = rect(4) / 2; if length (rect) > 4 theta = rect(5); endif v = [cos(theta); sin(theta)]; M = [-1 1; 1 1; 1 -1; -1 -1] .* [w h]; %M = bsxfun (@times, [-1 1; 1 1; 1 -1; -1 -1], [w h]); tx = x + M * v; ty = y + M(4:-1:1,[2 1]) * v; # tx(1) = x - w*cot + h*sit; # tx(2) = x + w*cot + h*sit; # tx(3) = x + w*cot - h*sit; # tx(4) = x - w*cot - h*sit; # ty(1) = y - h*cot - w*sit ; # ty(2) = y - h*cot + w*sit; # ty(3) = y + h*cot + w*sit; # ty(4) = y + h*cot - w*sit; if nargout == 1 tx = [tx ty]; endif endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/isPolygonCCW.m0000644000000000000000000000013213066736044020701 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/isPolygonCCW.m0000644000175000017500000001020613066736044021054 0ustar00olafolaf00000000000000## Copyright (C) 2016-2017 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {} {@var{ccw} =} isPolygonCCW (@var{p}) ## @deftypefnx {} {@var{ccw} =} isPolygonCCW (@var{px}, @var{py}) ## Returns true if the polygon @var{p} are oriented Counter-Clockwise. ## ## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates ## of the vertices of the polygon can also be given as two N-by-1 arrays ## @var{px}, @var{py}. ## ## Optional third argument @var{library} can be one of "geometry" or ## "clipper". In the latter case the potentially faster Clipper polygon ## library will be invoked to assess winding directions. The default is ## "geometry". ## ## If any polygon is self-crossing, the result is undefined. ## ## If @var{p} is a cell, each element is considered a polygon, the ## resulting @var{cww} is a cell of the same size. ## ## @seealso{polygonArea} ## @end deftypefn ## Author: Juan Pablo Carbajal function ccw = isPolygonCCW (px, py=[], lib="geometry") ## case of wrong number of input arguments if (nargin > 3 || nargin < 1) print_usage (); endif if (ischar (py)) py = lower (py); if (ismember (py, {"geometry", "clipper"})) lib = py; py = []; else error ('Octave:invalid-fun-call', "use of '%s' not implemented", lib); endif endif if (! isempty (py)) if (! strcmp (typeinfo (px), typeinfo (py))) error ('Octave:invalid-input-arg', 'X and Y should be of the same type'); endif if (any (size (px) != size (py)) ) error ('Octave:invalid-input-arg', 'X and Y should be of the same size'); endif endif if (iscell (px)) ## Cell Array Format ## Call this function on each cell if (isempty (py)) py = cell (size (px)); endif ccw = cellfun (@(u,v) isPolygonCCW (u,v,lib), px, py, "unif", 0); else ## Input are matrices ## merge them to one px = [px py]; if (isempty (px)) error ("isPolygonCW: empty input polygon encountered"); elseif (strcmpi (lib, "clipper")) ## Clipper can do all of them in one call ccw = logical (isPolygonCW_Clipper (px)); return endif if (any (isnan (px(:)))) ## Inputs are many polygons separated with NaN ## Split them and call this function on each of them px = splitPolygons (px); ccw = cellfun (@(u) isPolygonCCW (u,[],lib), px); else ## Here do the actual work ccw = polygonArea (px) > 0; endif endif endfunction %!shared pccw, pcw, pxccw, pyccw, pxnan, pynan, pnan %! pccw = [0 0; 1 0; 1 1; 0 1]; %! pcw = reversePolygon (pccw); %! pxccw = pccw(:,1); %! pyccw = pccw(:,2); %! pxnan = [2; 2; 0; 0; NaN; 0; 0; 2]; %! pynan = [0; 2; 2; 0; NaN; 0; 3; 0]; %! pnan = [pxnan pynan]; ## Native testing %!assert (isPolygonCCW (pccw)); %!assert (isPolygonCCW (pxccw, pyccw)); %!assert (isPolygonCCW ({pxccw, pxccw}, {pyccw, pyccw}), {true, true}); %!assert (~isPolygonCCW (pcw)); %!assert (isPolygonCCW ({pccw;pcw}), {true;false}); %!assert (isPolygonCCW(pnan), [true; false]); %!assert (isPolygonCCW({pnan,pcw}),{[true;false], false}); ## Clipper testing %!assert (isPolygonCCW (pccw,[],"clipper")); %!assert (isPolygonCCW (pxccw, pyccw,"clipper")); %!assert (isPolygonCCW ({pxccw, pxccw}, {pyccw, pyccw},"clipper"), {true, true}); %!assert (~isPolygonCCW (pcw,[],"clipper")); %!assert (isPolygonCCW ({pccw;pcw},[],"clipper"), {true;false}); %!xtest assert (isPolygonCCW(pnan,[],"clipper"), [true; false]); %!xtest assert (isPolygonCCW({pnan,pcw},[],"clipper"),{[true; false], false}); geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/clipPolyline.m0000644000000000000000000000013213066736044021024 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/clipPolyline.m0000644000175000017500000000547613066736044021214 0ustar00olafolaf00000000000000## Copyright (C) 2017 Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {} {@var{oline}} = polylineClip (@var{inpol}, @var{clippol}, @var{op}) ## Clip (possibly composite) polylines with polygon(s) using one of boolean ## methods. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polylines(s) ## to be clipped. Polyline sections are separated by [NaN NaN] rows. ## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the ## clip polygon(s). @var{clippol} may comprise separate and/or concentric ## polygons (the latter with holes). ## ## The argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## @end itemize ## ## Output array @var{oline} will be an Nx2 array of polyline sections ## resulting from the requested boolean operation. ## ## The optional argument @var{library} specifies which library to use for clipping. ## Currently only @asis{"clipper"} is implemented. ## ## @seealso{clipPolygon} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2017-03-21 function [olin, nlin] = clipPolyline (p1, p2, op, library = "clipper") if ~(ismember (tolower (library), {"clipper"})) error ('Octave:invalid-fun-call', "clipPolyline: unimplemented polygon clipping library: '%s'", library); endif [olin, nlin] = clipPolyline_clipper (p1, p2, op); endfunction %!demo %! sline = [0, 6.5; 1.25, 4; 1.25, 0; NaN, NaN; 0.25, 7; 1.75, 4; 1.75, 0]; %! for ii=1:10 %! sline = [sline; [NaN NaN]; [ii/2+0.25, 7; ii/2+1.75, 4; ii/2+1.75, 0]]; %! endfor %! pol2a = [1 2; 7 4; 4 7; 1 2; 2.5 3; 4 5.5; 5.5 4; 2.5 3; 1 2]; %! figure (); %! plot (sline(:, 1), sline(:, 2)); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', 2); %! [olin, nlin] = clipPolyline_clipper (sline, pol2a, 1); %! plot (olin(:, 1), olin(:, 2), 'r', 'linewidth', 3); %! [olin, nlin] = clipPolyline (sline, pol2a, 0); %! plot (olin(:, 1), olin(:, 2), 'g', 'linewidth', 3); %! grid on; %! axis equal; %! legend ({"OR", "Clip polygon", "AND"}); %! title ("Demo: clipping polylines with polygons"); geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/projPointOnPolyline.m0000644000000000000000000000013213066736044022356 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/projPointOnPolyline.m0000644000175000017500000001261113066736044022533 0ustar00olafolaf00000000000000## Copyright (C) 2003-2011 David Legland ## Copyright (C) 2015 Adapted by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Author: David Legland ## Adapted: JuanPi Carbajal ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{P}, @var{D}] =} projPointOnPolyline (@var{point}, @var{poly}) ## @deftypefnx {Function File} {[@dots{}] =} projPointOnPolyline (@dots{}, @var{closed}) ## ## Compute the position of the orthogonal projection of a point on a ## polyline. ## ## @var{point} is a 1x2 row vector containing point coordinates ## @var{poly} is a Nx2 array containing coordinates of polyline vertices ## @var{pos} is the position of the point on the polyline, between 0 and the ## number of vertices of the polyline. @var{pos} can be a non-integer value, in ## this case, the integer part correspond to the polyline edge index ## (between 0 and N-1), and the floating-point part correspond to the ## relative position on i-th edge (between 0 and 1, 0: edge start, 1: edge ## end). ## ## When @var{point} is an array of points, returns a column vector with as many ## rows as the number of points. ## ## If third input argument @var{closed} is given, it specifies if the polyline ## is closed or not. @var{closed} can be one of: ## @table @asis ## @item 'closed' ## The polyline is closed ## ## @item 'open' ## The polyline is open ## ## @item a logical column vector ## It should have the same number of elements as the number of points and it ## specifies individually if each polyline is closed (true=closed). ## ## @end table ## ## @seealso{points2d, polygons2d, polylinePoint, distancePointPolyline} ## @end deftypefn function [pos minDist] = projPointOnPolyline (point, poly, closed=false) warning ('Octave:deprecated-keyword', ... "This function is deprecated use distancePointPolyline instead.\n"); [minDist pos] = distancePointPolyline (point, poly, closed); # # check if input polyline is closed or not # if strcmp ('closed', closed) # closed = true; # elseif strcmp ('open', closed) # closed = false; # endif # # closes the polyline if necessary # if closed # poly = [poly; poly(1,:)]; # endif # # number of points # Np = size (point, 1); # # number of vertices in polyline # Nv = size (poly, 1); # # allocate memory results # pos = zeros (Np, 1); # minDist = inf (Np, 1); # # iterate on points # for p=1:Np # # compute smallest distance to each edge # for i=1:Nv-1 # # build current edge # edge = [poly(i,:) poly(i+1,:)]; # # compute distance between current point and edge # [dist edgePos] = distancePointEdge (point(p, :), edge); # # update distance and position if necessary # if dist < minDist(p) # minDist(p) = dist; # pos(p) = i - 1 + edgePos; # endif # endfor # endfor endfunction %!demo %! warning ("off", "Octave:deprecated-keyword", "local"); %! point = [2 1] .* rand (10,2) - [1 0]; %! t = linspace (0,pi,25).'; %! poly = [cos(t) sin(t)]; %! [pos d] = arrayfun (@(i)projPointOnPolyline (point(i,:),poly), (1:10).'); %! %! # Calculate the projection on the polyline to plot %! p_ = zeros (10, 2); %! %! # projection on vertices of the polyline %! isvertex = abs (pos - fix (pos)) < eps; %! p_(isvertex,:) = poly (pos(isvertex)+1,:); %! %! # the rest %! pos = pos (!isvertex); %! i = fix (pos) + 1; %! x = pos - fix (pos); %! p_(!isvertex,:) = poly(i,:) + x.*(poly(i+1,:)-poly(i,:)); %! %! # Plot %! plot (poly(:,1), poly(:,2),'.-', ... %! point(:,1), point(:,2), 'o', ... %! p_(:,1), p_(:,2),'.'); %! legend ('Polyline', 'Points', 'Projections'); %! line ([point(:,1) p_(:,1)].',[point(:,2) p_(:,2)].'); %! arrayfun (@(i)text ((p_(i,1)+point(i,1))/2, (p_(i,2)+point(i,2))/2, ... %! sprintf("%.2f", d(i))), 1:10); %! axis tight %! axis equal geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/supportFunction.m0000644000000000000000000000013213066736044021603 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/supportFunction.m0000644000175000017500000000514513066736044021764 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } suppportFunction (@var{polygon}) ## @deftypefnx {Function File} {@var{h} = } suppportFunction (@var{polygon}, @var{n}) ## @deftypefnx {Function File} {@var{h} = } suppportFunction (@var{polygon}, @var{v}) ## Compute support function of a polygon ## ## H = supportFunction(POLYGON, N) ## uses N points for suport function approximation ## ## H = supportFunction(POLYGON) ## assume 24 points for approximation ## ## H = supportFunction(POLYGON, V) ## where V is a vector, uses vector V of angles to compute support ## function. ## ## @seealso{convexification} ## @end deftypefn function h = supportFunction(polygon, varargin) N = 24; u = (0:2*pi/N:2*pi*(1-1/N)).'; if length(varargin)==1 var = varargin{1}; if length(var)==1 N = var; u = (0:2*pi/N:2*pi*(1-1/N)).'; else u = var(:); end end h = zeros(size(u)); for i=1:length(u) v = repmat([cos(u(i)) sin(u(i))], [size(polygon, 1), 1]); h(i) = max(dot(polygon, v, 2)); end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygon2patch.m0000644000000000000000000000013213066736044021152 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygon2patch.m0000644000175000017500000001576513066736044021344 0ustar00olafolaf00000000000000## Copyright (C) 2015-2017 Philip Nienhuis ## Copyright (C) 2016 - Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {} { @var{XYo} =} polygon2patch (@var{XYi}) ## @deftypefnx {} [@var{Xo}, @var{Yo} ] = polygon2patch (@var{Xi}, @var{Yi}) ## @deftypefnx {} [@var{Xo}, @var{Yo}, @var{Zo} ] = polygon2patch (@var{Xi}, @var{Yi}, @var{Zi}) ## Connect outer (filled) polygon and inner (hole) polygons using branch cuts ## such that all polygons are connected as one string of vertices, for ## subsequent plotting polygons with holes using the function @command{patch}. ## ## @var{XYi} can be a 2 or 3 dimensional array; only the X and Y coordinates ## will be optmized and Z-values will be kept with their original vertices. ## Alternatively separate X, Y and optionally Z-vectors can be specified. ## The outer polygon should appear as a first subvector, bounded by a row of ## NaN values, and have a counterclockwise winding direction. All subsequent ## inner hole polygons should also be bounded by rows of NaN values and have ## clockwise winding directions. ## ## This function expects and returns column vectors or matrices where ## each row contains coordinates of a vertex. ## ## @seealso{drawPolygon, patch} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2016-04-30 function [X, Y, Z] = polygon2patch (XX, YY=[], ZZ=[]); matinp = 0; XYsz = size (XX, 2); ## Check args if (nargin == 1) if (ismatrix (XX) && XYsz >= 2) ## apparently matrix input rather than two separate X,Y[,Z] vectors matinp = 1; XY = XX; endif elseif (nargin >= 2) ## Separate vector input XY = [XX YY ZZ]; elseif (nargin < 1) error ("Octave:invalid-input-arg", ... "polygon2patch: not enough input arguments"); endif ## Also keep track of Z. ## Z isn't (yet) in the branch cut optimization (but that could be done easily) if (isempty (ZZ) || XYsz == 2) ## At least provide pointers where Z coordinates have gone in output arrays ZZ = [1:size(XY, 1)]'; XY = [ XY ZZ ]; endif ## Find NAN separators idx = find (isnan (XY(:, 1))); if (isempty (idx)) ## No NaN separators => no subfeatures. Return if (!matinp) X = XX; Y = YY; if (nargin == 3) Z = ZZ; endif else X = XX; Y = Z = []; endif return endif ipt = [0; idx; numel(XY(:, 1))+1]; for ii=1:numel (ipt) - 1 ## Check for closed polygon if (any (abs (XY(ipt(ii)+1, 1:2) - XY(ipt(ii+1)-1, 1:2)) > eps)) ## Duplicate first vertex as last vertex of subpolygon ## First shift all subpolys down XY(ipt(ii+1)+1:end+1, :) = XY(ipt(ii+1):end, :); ipt(ii+1:end) += 1; XY(ipt(ii+1)-1, :) = XY(ipt(ii)+1, :); endif XY(ipt(ii)+1:ipt(ii+1)-1, 4) = [ ipt(ii)+1:ipt(ii+1)-1 ]'; endfor ## Silence broadcasting warning warning ("off", "Octave:broadcast", "local"); ## Compute all interdistances XY(ipt(2:end-1), :) = []; dists = distancePoints (XY(:, 1:2), XY(:, 1:2)); szdst = size (dists); dists = dists + tril (Inf (szdst(1))); X_Y = XY(1:ipt(2)-1, :); ## Keep track of which holes are still unconnected processed = [0 (ones (1, numel (ipt) - 2))]; tt = cumsum (diff (ipt) - 1); idx = [tt(1:end-1)+1 tt(2:end)]; odx = 1:(ipt(2) - 1); ody = 1:size (dists, 2); ## Find hole polygon with smallest distance to an outer vertex; afterwards ## assign that to outer vertex + restart search until all holes are processed. ## FIXME Although Octave doesn't draw the branch cuts, it may be better to ## also check that branch cuts do not cross polygons between two ## vertices belonging to other polygons (or self-intersect polygons) while (any (processed)) ## Get slice of dists with outer vertices + vertices connected to it, excl. ## columns already processed odz = setdiff (ody, odx); [~, indx] = min (dists(odx, odz)(:)); ## Get subscripts into sliced dists matrix [r, c] = ind2sub ([numel(odx),numel(odz)], indx); ## Recompute subscripts into full dists matrix rr = odx(r); ## Needed to insert new hole into place cc = odz(c); ## To rotate hole such that this vertex has ## smallest distance to outer polygon vertex ## Find hole polygon corresponding to these subscripts ii = find (cc >= idx(:, 1) & cc < idx(:, 2)); shft = idx(ii, 1) - cc; tmpXY = XY(idx(ii, 1):idx(ii, 2), :); if (shft) tmpXY(1:end-1, :) = circshift (tmpXY(1:end-1, :), [shft, 0]); ## tmpXY is always shifted upward here. Copy toprow coordinates to bottom tmpXY(end, :) = tmpXY(1, :); endif X_Y = [X_Y(1:r, :); tmpXY; X_Y(r:end, :)]; odx = [odx idx(ii, 1):idx(ii, 2)]; processed(ii+1) = 0; endwhile if (!matinp) X = X_Y(:, 1); Y = X_Y(:, 2); if (nargin == 3) Z = X_Y(:, 3); endif else X = X_Y(:, 1:XYsz); Y = Z = []; endif endfunction %!demo %! figure() %! p = [0 0; 0 1; 1 1; 1 0]; %ccw %! pp = [0 0; 1 0; 1 1; 0 1]; %cw %! ph = p + [1.2 0]; %! # add hole %! ph(end+1,:) = nan; %! ph = [ph; (pp-[0.5 0.5])*0.5+[1.7 0.5]]; %! po = polygon2patch (ph); %! patch (po(:,1), po(:,2), 'b', 'facecolor', 'c'); %! axis image %!demo %! holes = [0 0; 35 0; 35 25; 0 25; 0 0; NaN NaN; 7 1; 2 1; 3 5; 6 6; 7 1; ... %! NaN NaN; 9 2; 8 5; 18 7; 28 5; 30 2; 9 2; NaN NaN; 19 11; 18 14; 21 13; ... %! 19 11; NaN NaN; 24 24; 34 24; 34 6; 24 24; NaN NaN; 9 6; 7 14; 9 18; 9 6; ... %! NaN NaN; 27 6; 27 12; 31 9; 27 6; NaN NaN; 2 24; 23 24; 22 21; 23 19; ... %! 1 23; 2 24; NaN NaN; 18 8; 26 13; 26 7; 18 8; NaN NaN; 8 18; 6 14; 8 7; ... %! 2 9; 1 18; 5 19; 8 18; NaN NaN; 13 16; 17 8; 10 6; 13 16; NaN NaN; 34 1; ... %! 28 6; 31 8; 34 1; NaN NaN; 9 20; 26 17; 31 10; 24 15; 8 19; 9 20]; %! subplot (2, 2, 1); %! p1 = plot (holes(:, 1), holes(:, 2), 'b'); box off; axis off %! title ("Plot of array 'holes'"); %! subplot (2, 2, 2); %! p2 = patch (holes(:, 1), holes(:, 2), 'b', 'facecolor', 'c'); box off; axis off %! title ("Patch of array 'holes'\nbefore processing"); %! subplot (2, 2, 3); %! pt = polygon2patch (holes); %! p3 = plot (pt(:, 1), pt(:, 2), 'b'); box off; axis off %! title ("Plot of array 'holes'\nafter polygon2patch"); %! subplot (2, 2, 4); %! p4 = patch (pt(:, 1), pt(:, 2), 'b', 'facecolor', 'c'); box off; axis off %! title ("Patch of array 'holes'\nafter polygon2patch"); geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/orientPolygon.m0000644000000000000000000000013213066736044021231 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/orientPolygon.m0000644000175000017500000001010013066736044021375 0ustar00olafolaf00000000000000## Copyright (C) 2016 - Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {} {@var{q} =} orientPolygon (@var{p}) ## @deftypefnx {} {@dots{} =} orientPolygon (@var{p}, [], @var{dir}) ## @deftypefnx {} {[@var{qx} @var{qy}] =} orientPolygon (@var{px}, @var{py}) ## @deftypefnx {} {@dots{} =} orientPolygon (@var{px}, @var{py}, @var{dir}) ## Orient polygon counterclockwise or clockwise. ## ## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates ## of the vertices of the polygon can also be given as two N-by-1 arrways ## @var{px}, @var{py}. It can also be cells of polygons or NaN separated polygons. ## The output has the same format as the input. ## ## The optional argument @var{dir} can be @asis{"ccw"} or @asis{"cw"}. ## By default it orients polygon counterclockwise (@code{@var{dir} == "ccw"}). ## To orient the polygon clockwise, use @code{@var{dir} == "cw"}. ## ## Holes are treated as independet polygons, that is a cw polygon with a cw hole ## will be seen as two cw polygons. ## ## If polygon is self-crossing, the result is undefined. ## ## @seealso{isPolygonCCW} ## @end deftypefn function [x y] = orientPolygon (x, y=[], d = "ccw"); #case of wrong number of input arguments if (nargin > 3 || nargin < 1) print_usage (); endif if (!isempty (y)) if (!strcmp (typeinfo (x), typeinfo (y))) error ('Octave:invalid-input-arg', 'X and Y should be of the same type'); endif if(any (size (x) != size (y)) ) error ('Octave:invalid-input-arg', 'X and Y should be of the same size'); endif endif # define orientation mode mode_ccw = strcmpi (d, "ccw"); if (iscell (x)) # Cell Array Format # Call this function on each cell if (isempty (y)) y = cell (size (x)); endif [x y] = cellfun (@(u,v) orientPolygon (u,v,d), x, y, "unif", 0); else # Input are matrices # merge them to one x = [x y]; if any (isnan (x(:))) # Inputs are many polygons separated with NaN # Split them and call this function on each of them x = splitPolygons (x); x = cellfun (@(u) orientPolygon (u,[],d), x, "unif", 0); x = joinPolygons (x); else ## Here do the actual work #Check the orientation of the polygons if ( (!isPolygonCCW (x) && mode_ccw) || (isPolygonCCW (x) && !mode_ccw) ); x = reversePolygon (x); endif endif if (!isempty (y)) y = x(:,2); x = x(:,1); endif endif endfunction %!shared pccw, pcw, pxccw, pyccw, pxnan, pynan, pnan %! pccw = [0 0; 1 0; 1 1; 0 1]; %! pcw = reversePolygon (pccw); %! pxccw = pccw(:,1); %! pyccw = pccw(:,2); %! pxnan = [2; 2; 0; 0; NaN; 0; 0; 2]; %! pynan = [0; 2; 2; 0; NaN; 0; 3; 0]; %! pnan = [pxnan pynan]; %!test %! x = orientPolygon (pccw,[],"ccw"); %! assert (x, pccw); %!test %! x = orientPolygon (pccw,[],"cw"); %! assert (x, pcw); %!test %! x = orientPolygon (pcw,[],"ccw"); %! assert (x, pccw); %!test %! x = orientPolygon (pcw,[],"cw"); %! assert (x, pcw); %!test %! x = orientPolygon (pnan,[],"cw"); %! y = splitPolygons (pnan); %! y = joinPolygons ({reversePolygon(y{1}); y{2}}); %! assert (x, y); %!test %! x = orientPolygon (pnan,[],"ccw"); %! y = splitPolygons (pnan); %! y = joinPolygons ({y{1}; reversePolygon(y{2})}); %! assert (x, y); %!test %! [x y] = orientPolygon (pxccw,pyccw,"ccw"); %! assert ([x y], pccw); %!test %! [x y] = orientPolygon (pxccw,pyccw,"cw"); %! assert ([x y], pcw); geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/distancePointPolygon.m0000644000000000000000000000013213066736044022535 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/distancePointPolygon.m0000644000175000017500000000427113066736044022715 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dist} = } distancePointPolygon (@var{point},@var{poly}) ## Compute shortest distance between a point and a polygon ## ## @seealso{polygons2d, points2d, distancePointPolyline, distancePointEdge, projPointOnPolyline} ## @end deftypefn function varargout = distancePointPolygon(point, poly) # eventually copy first point at the end to ensure closed polygon if sum(poly(end, :)==poly(1,:))~=2 poly = [poly; poly(1,:)]; end # call to distancePointPolyline minDist = distancePointPolyline(point, poly); # process output arguments if nargout<=1 varargout{1} = minDist; end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygonCentroid.m0000644000000000000000000000013213066736044021540 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygonCentroid.m0000644000175000017500000000537313066736044021724 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[ @var{pt}, @var{area} ] = } polygonCentroid (@var{points}) ## @deftypefnx {Function File} {[ @dots{} ]= } polygonCentroid (@var{ptx},@var{pty}) ## Compute the centroid (center of mass) of a polygon. ## ## Computes the center of mass of a polygon defined by @var{points}. @var{points} is a ## N-by-2 matrix. The two columns can be given separately using @var{ptx} and @var{pty} ## for the x and y component respectively. ## ## The area of the polygon is returned in the second output argument. ## ## Adapted from @url{http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/} ## ## @seealso{polygons2d, polygonArea, drawPolygon} ## @end deftypefn function [pt A] = polygonCentroid(varargin) if nargin==1 var = varargin{1}; px = var(:,1); py = var(:,2); elseif nargin==2 px = varargin{1}; py = varargin{2}; end # Algorithme P. Bourke (vectorized) % vertex indices N = length (px); iNext = [2:N 1]; % compute cross products common = px .* py(iNext) - px(iNext) .* py; sx = sum ((px + px(iNext)) .* common); sy = sum ((py + py(iNext)) .* common); % area and centroid A = sum(common) / 2; pt = [sx sy] / 6 / A; endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygonSelfIntersections.m0000644000000000000000000000013213066736044023434 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygonSelfIntersections.m0000644000175000017500000000732213066736044023614 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pts} = } polygonSelfIntersections (@var{poly}) ## @deftypefnx {Function File} {[@var{pts} @var{pos1} @var{pos2}] = } polygonSelfIntersections (@var{poly}) ## @deftypefnx {Function File} {[@dots{}] = } polygonSelfIntersections (@dots{},@asis{'tolerance'}, @var{tol}) ## Find-self intersection points of a polygon ## ## Return the position of self intersection points ## ## Also return the 2 positions of each intersection point (the position ## when meeting point for first time, then position when meeting point ## for the second time). ## ## Specifies an additional tolerance parameter to decide whether two intersection ## points should be considered the same, based on their euclidean ## distance. ## ## Example ## @example ## # use a '8'-shaped polygon ## poly = [10 0;0 0;0 10;20 10;20 20;10 20]; ## polygonSelfIntersections(poly) ## ans = ## 10 10 ## @end example ## ## @seealso{polygons2d, polylineSelfIntersections} ## @end deftypefn function varargout = polygonSelfIntersections(poly, varargin) tol = 1e-14; % parse optional arguments while length(varargin) > 1 pname = varargin{1}; if ~ischar(pname) error('Expect optional arguments as name-value pairs'); end if strcmpi(pname, 'tolerance') tol = varargin{2}; else error(['Unknown parameter name: ' pname]); end varargin(1:2) = []; end % ensure the last point equals the first one if sum(abs(poly(end, :)-poly(1,:)) < tol) ~= 2 poly = [poly; poly(1,:)]; end % compute intersections by calling algo for polylines [points, pos1, pos2] = polylineSelfIntersections(poly, 'closed', 'tolerance', tol); % It may append that first vertex of polygon is detected as intersection, % the following tries to detect this. % (pos1 < pos2 by construction) n = size(poly, 1) - 1; inds = abs(pos1) < tol & abs(pos2 - n) < tol; points(inds, :) = []; pos1(inds) = []; pos2(inds) = []; %% Post-processing % process output arguments if nargout <= 1 varargout = {points}; elseif nargout == 3 varargout = {points, pos1, pos2}; end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/clipPolygon.m0000644000000000000000000000013213066736044020660 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/clipPolygon.m0000644000175000017500000001374513066736044021046 0ustar00olafolaf00000000000000## Copyright (C) 2017 Philip Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{outpol}, @var{npol}] = clipPolygon (@var{inpol}, @var{clippol}, @var{op}) ## @deftypefnx {Function File} [@var{outpol}, @var{npol}] = clipPolygon (@var{inpol}, @var{clippol}, @var{op}, @var{library}) ## @deftypefnx {Function File} [@var{outpol}, @var{npol}] = clipPolygon (@dots{}, @var{args}) ## Perform boolean operation on polygon(s) using one of boolean methods. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## to be clipped. Polygons are separated by [NaN NaN] rows. @var{clippol} = ## another Nx2 matrix of (X, Y) coordinates representing the clip polygon(s). ## ## The argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## ## @item 2: exclusiveOR ("XOR") of @var{inpol} and @var{clippol} ## ## @item 3: union ("OR") of @var{inpol} and @var{clippol} ## @end itemize ## ## The optional argument @var{library} specifies which library to use for clipping. ## Currently only @asis{"clipper"} is implemented. ## ## Output array @var{outpol} will be an Nx2 array of polygons resulting from ## the requested boolean operation, or in case of just one input argument an ## Nx1 array indicating winding direction of each subpolygon in input argument ## @var{inpol}. ## ## Optional output argument @var{npol} indicates the number of output polygons. ## ## The optional input arguments @var{args} are used to pass additonal arguments to the ## underlying library. Clipper library allows a rule to be specified about ## how to assess holes, or rather, how to assess polygon fill. This works as ## follows: start with a winding number of zero (0). From a point outside all ## polygons specified in @var{INPOL}, go to the center of the innermost ## polygon and note which polygons are crossed. For each polygon boundary ## crossing from right to left, increase the winding number, while for each ## polygon crossing from left to right, decrement it, and then assign it to ## the crossed polygon. ## By passing two extra arguments @var{rules} and @var{rulec} the user can be ## set rules individually for subject and clip polygons, respectively, as follows: ## ## @itemize ## @item 0 Even-Odd, also called Alternate (= default): ## The first polygon crossed specifies the outer boundary of a filled polygon, ## the next polygon (if present) specifies the inner boundary of that filled ## polygon, and so on. Winding direction (clockwise or counterclockwise) is ## irrelevant here. ## ## @item 1 Non-Zero: ## All polygons with a non-zero winding number are filled. ## ## @item 2 Positive: ## All polygons with a winding number > 0 are filled. This is the usual setting ## for counterclockwise polygons to be the outer, and clockwise polygons to be ## the inner boundary ("holes") of complex polygons. ## ## @item 3 Negative: ## All polygons with a winding number < 0 are filled. ## @end itemize ## (for details see ## http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/PolyFillType.htm ## ## ## @seealso{clipPolygon_clipper, clipPolyline} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2017-03-21 function [opol, npol] = clipPolygon (inpol, clipol, op, library = "clipper", varargin) if ~(ismember (tolower (library), {"clipper"})) error ('Octave:invalid-fun-call', "clipPolygon: unimplemented polygon clipping library: '%s'", library); endif [opol, npol] = clipPolygon_clipper (inpol, clipol, op, varargin{:}); endfunction %!demo %! pol1 = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3]; %! pol1a = [2 6; 2 2; 3 3; 3 5; 5 5; 5 3; 3 3; 2 2; 6 2; 6 6; 2 6]; %! pol2 = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3]; %! pol2a = [1 2; 7 4; 4 7; 1 2; 2.5 3; 4 5.5; 5.5 4; 2.5 3; 1 2]; %! lw = 2; %! %! subplot (2, 6, [2 3]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw); %! axis image %! grid on %! title ("1. Subject polygon") %! %! subplot (2, 6, [4 5]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw); %! axis image %! grid on %! title "2. Clip polygon" %! %! op = {"Sub -clip", "AND / Intersection", "Exclusive OR", "OR / Union"}; %! for i=1:numel(op) %! subplot (6, 4, [12 16]+i); %! [opol, npol] = clipPolygon (pol1, pol2, i-1); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw, 'erasemode', 'xor'); %! axis image %! grid on %! title (sprintf("%d. %s", i+2, op{i})); %! axis off %! endfor %! %! subplot (10, 4, 37); %! [opol, npol] = clipPolygon (pol2, pol1, 0); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw, 'erasemode', 'xor'); %! axis image %! grid on %! axis off %! title "7. Clip - sub"; geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/minimumCaliperDiameter.m0000644000000000000000000000013213066736044023007 xustar0030 mtime=1490795556.680871097 30 atime=1490795556.680871097 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/minimumCaliperDiameter.m0000644000175000017500000001253413066736044023170 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %MINIMUMCALIPERDIAMETER Minimum caliper diameter of a set of points % % WIDTH = minimumCaliperDiameter(POINTS) % Computes the minimum width of a set of points. As polygons and % polylines are represented as point lists, this function works also for % polygons and polylines. % % [WIDTH THETA] = minimumCaliperDiameter(POINTS) % Also returns the direction of minimum width. The direction corresponds % to the horizontal angle of the edge that minimizes the width. THETA is % given in radians, between 0 and PI. % % % Example % % Compute minimal caliper diameter, and check coords of rotated points % % have expected extent % points = randn(30, 2); % [width theta] = minimumCaliperDiameter(points); % points2 = transformPoint(points, createRotation(-theta)); % diff = max(points2) - min(points2); % abs(width - diff(2)) < 1e-10 % ans = % 1 % % References % Algorithms use rotating caliper. Implementation was based on that of % Wikipedia: % http://en.wikipedia.org/wiki/Rotating_calipers % % See also % polygons2d, convexHull, orientedBox % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-04-08, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. function [min_width, min_angle] = minimumCaliperDiameter(points) % first, compute convex hull of the polygon inds = convhull(points(:,1), points(:,2)); hull = points(inds, :); % if first and last points are the same, remove the last one if inds(1) == inds(end) hull = hull(1:end-1, :); end % number of hull vertices nV = size(hull, 1); % default values rotated_angle = 0; min_width = inf; min_angle = 0; % avoid degenerated cases if nV < 3 return; end [tmp, p_a] = min(hull(:, 2)); %#ok [tmp, p_b] = max(hull(:, 2)); %#ok caliper_a = [ 1 0]; % Caliper A points along the positive x-axis caliper_b = [-1 0]; % Caliper B points along the negative x-axis while rotated_angle < pi % compute the direction vectors corresponding to each edge ind_a2 = mod(p_a, nV) + 1; vector_a = hull(ind_a2, :) - hull(p_a, :); ind_b2 = mod(p_b, nV) + 1; vector_b = hull(ind_b2, :) - hull(p_b, :); % Determine the angle between each caliper and the next adjacent edge % in the polygon angle_a = vectorAngle(caliper_a, vector_a); angle_b = vectorAngle(caliper_b, vector_b); % Determine the smallest of these angles minAngle = min(angle_a, angle_b); % Rotate the calipers by the smallest angle caliper_a = rotateVector(caliper_a, minAngle); caliper_b = rotateVector(caliper_b, minAngle); rotated_angle = rotated_angle + minAngle; % compute current width, and update opposite vertex if angle_a < angle_b line = createLine(hull(p_a, :), hull(ind_a2, :)); width = distancePointLine(hull(p_b, :), line); p_a = mod(p_a, nV) + 1; else line = createLine(hull(p_b, :), hull(ind_b2, :)); width = distancePointLine(hull(p_a, :), line); p_b = mod(p_b, nV) + 1; end % update minimum width and corresponding angle if needed if width < min_width min_width = width; min_angle = rotated_angle; end end endfunction %!demo %! % Compute minimal caliper diameter, and check coords of rotated points %! % have expected extent %! points = randn(30, 2); %! [width theta] = minimumCaliperDiameter(points); %! points = transformPoint(points, createRotation(-theta)); %! points = transformPoint(points, createTranslation(-min(points))); %! drawPoint (points); %! hold on %! cm = centroid (points); %! drawEdge ([cm(1) 0], [cm(1) width], "linewidth", 3); %! drawPolygon (convexHull(points)) %! hold off %! axis image geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/polygonSubcurve.m0000644000000000000000000000013213066736044021567 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/polygonSubcurve.m0000644000175000017500000000635413066736044021753 0ustar00olafolaf00000000000000## Copyright (C) 2003-2011 David Legland ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{poly2} =} polygonSubcurve (@var{polygon}, @var{pos0},@var{pos1}) ## Extract a portion of a polygon ## ## Create a new polyline, by keeping vertices located between positions ## @var{pos0} and @var{pos1}, and adding points corresponding to positions @var{pos0} and ## @var{pos1} if they are not already vertices. ## ## Example: ## @example ## Nv = 100; ## poly = circleAsPolygon ([10 20 30], Nv); ## poly2 = polygonSubcurve (poly, 15, 65); ## drawPolyline (poly2); ## @end example ## ## @seealso{polygons2d, polylineSubcurve} ## @end deftypefn function res = polygonSubcurve(poly, t0, t1) # number of vertices Nv = size(poly, 1); if t0 ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %POLYGONBOUNDS Compute the bounding box of a polygon % % BOX = polygonBounds(POLY); % Returns the bounding box of the polygon. % BOX has the format: [XMIN XMAX YMIN YMAX]. % % Input polygon POLY is as a N-by-2 array containing coordinates of each % vertex. % Multiple polygons can be specified either by inserting NaN rows between % vertex coordinates, or by using a cell array, each cell containing the % vertex coordinates of a polygon loop. % % See also % polygons2d, boxes2d, boundingBox % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2007-10-12, using Matlab 7.4.0.287 (R2007a) % Copyright 2007 INRA - Cepia software platform function box = polygonBounds(polygon) % transform as a cell array of simple polygons polygons = splitPolygons(polygon); % init extreme values xmin = inf; xmax = -inf; ymin = inf; ymax = -inf; % iterate over loops for i = 1:length(polygons) polygon = polygons{i}; xmin = min(xmin, min(polygon(:,1))); xmax = max(xmax, max(polygon(:,1))); ymin = min(ymin, min(polygon(:,2))); ymax = max(ymax, max(polygon(:,2))); end % format output box = [xmin xmax ymin ymax]; endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/fillPolygon.m0000644000000000000000000000013213066736044020657 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/fillPolygon.m0000644000175000017500000000727013066736044021041 0ustar00olafolaf00000000000000## Copyright (C) 2003-2011 David Legland ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} fillPolygon (@var{p}) ## @deftypefnx {Function File} {@var{h} =} fillPolygon (@var{px},@var{py}) ## Fill a polygon specified by a list of points ## ## @var{p} is a single [N*2] array. ## With one input argument, it fills the interior of the polygon specified ## by @var{p}. The boundary of the polygon is not drawn, use 'drawPolygon' ## to do it. ## ## If @var{p} contains NaN-couples, each portion between the [NaN;NaN] will ## be filled separately. ## ## Two input arguments specify coordinates of the polygon in separate arrays. ## ## Also returns a handle to the created patch. ## ## @seealso{polygons2d, drawCurve, drawPolygon} ## @end deftypefn function h = fillPolygon (varargin) # check input if isempty (varargin) error ('need to specify a polygon'); end # case of a set of polygons stored in a cell array var = varargin{1}; if iscell (var) N = length (var); h = zeros (N, 1); for i = 1:N # check for empty polygons if ~isempty (var{i}) h(i) = fillPolygon (var{i}, varargin{2:end}); end end return; end # Extract coordinates of polygon vertices if size (var, 2) > 1 # first argument is a polygon array px = var(:, 1); py = var(:, 2); varargin(1) = []; else # arguments 1 and 2 correspond to x and y coordinate respectively if length (varargin) < 2 error ('should specify either a N*2 array, or 2 N*1 vectors'); end px = varargin{1}; py = varargin{2}; varargin(1:2) = []; end # Find position of breaks, and copies first point of each loop at the # end inds = find (isnan (px(:))); i1 = [inds ; length(px)+1]; i0 = [1 ; inds+1]; px(i1, :) = px(i0, :); py(i1, :) = py(i0, :); # set default line format if isempty (varargin) varargin = {'b'}; end # fill the polygon with desired style h = fill (px, py, varargin{:}, 'lineStyle', 'none'); endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/clipPolygon_clipper.m0000644000000000000000000000013213066736044022376 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/clipPolygon_clipper.m0000644000175000017500000001230113066736044022547 0ustar00olafolaf00000000000000## Copyright (C) 2015-2017 Philip Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}) ## @deftypefnx {Function File} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}, @var{op}) ## @deftypefnx {Function File} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}, @var{op}, @var{rules}, @var{rulec}) ## Perform boolean operation on polygon(s) using one of boolean methods. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## to be clipped. Polygons are separated by [NaN NaN] rows. @var{clippol} = ## another Nx2 matrix of (X, Y) coordinates representing the clip polygon(s). ## ## Optional argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## ## @item 2: exclusiveOR ("XOR") of @var{inpol} and @var{clippol} ## ## @item 3: union ("OR") of @var{inpol} and @var{clippol} ## @end itemize ## ## In addition a rule can be specified to instruct polyclip how to assess ## holes, or rather, how to assess polygon fill. This works as follows: start ## with a winding number of zero (0). From a point outside all polygons ## specified in @var{INPOL}, go to the center of the innermost polygon and note ## which polygons are crossed. For each polygon boundary crossing from right ## to left, increase the winding number, while for each polygon crossing from ## left to right, decrement it, and then assign it to the crossed polygon. ## @var{rules} and @var{rulec} can be set individually for subject and clip ## polygons, respectively, as follows: ## ## @itemize ## @item 0 Even-Odd, also called Alternate (= default): ## The first polygon crossed specifies the outer boundary of a filled polygon, ## the next polygon (if present) specifies the inner boundary of that filled ## polygon, and so on. Winding direction (clockwise or counterclockwise) is ## irrelevant here. ## ## @item 1 Non-Zero: ## All polygons with a non-zero winding number are filled. ## ## @item 2 Positive: ## All polygons with a winding number > 0 are filled. This is the usual setting ## for counterclockwise polygons to be the outer, and clockwise polygons to be ## the inner boundary ("holes") of complex polygons. ## ## @item 3 Negative: ## All polygons with a winding number < 0 are filled. ## @end itemize ## (for details see ## http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/PolyFillType.htm ## ## Output array @var{outpol} will be an Nx2 array of polygons resulting from ## the requested boolean operation, or in case of just one input argument an ## Nx1 array indicating winding direction of each subpolygon in input argument ## @var{inpol}. ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2015-05-03 ## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab function [outpoly, npol] = clipPolygon_clipper (inpoly, clippoly=[], method=1, rules=0, rulec=0) ## Input validation if (nargin < 3) print_usage (); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error (" clipPolygon: inpoly should be a numeric Nx2 array"); endif if (! isnumeric (clippoly) || size (clippoly, 2) < 2) error (" clipPolygon: clippoly should be a numeric Nx2 array"); elseif (! isnumeric (method) || method < 0 || method > 3) error (" clipPolygon: operation must be a number in the range [0..3]"); elseif (! isnumeric (rules) || ! isnumeric (rulec) || rules < 0 || rulec < 0) error (" clipPolygon: fill type rules must be nummbers in range [0..3]"); endif [inpol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly); clpol = __dbl2int64__ (clippoly, [], xy_mean, xy_magn); ## Perform boolean operation outpol = clipper (inpol, clpol, method, rules, rulec); npol = numel (outpol); if (! isempty (outpol)) ## Morph struct output into [X,Y] array. Put NaNs between sub-polys. First X: [tmp(1:2:2*npol, 1)] = deal ({outpol.x}); [tmp(2:2:2*npol, 1)] = ... cellfun (@(x) [x(1); NaN], tmp(1:2:2*npol, 1), "uni", 0); ## Convert back from in64 into double, wipe trailing NaN X = double (cell2mat (tmp))(1:end-1); ## Y-coordinates: [tmp(1:2:2*npol, 1)] = deal ({outpol.y}); [tmp(2:2:2*npol, 1)] = ... cellfun (@(y) [y(1); NaN], tmp(1:2:2*npol, 1), "uni", 0); Y = double (cell2mat (tmp))(1:end-1); outpoly = ([X Y] / xy_magn) + xy_mean; else outpoly = zeros (0, 2); endif endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/private0000644000000000000000000000013213066736044017600 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/private/0002755000175000017500000000000013066736044020033 5ustar00olafolaf00000000000000geometry-3.0.0/inst/polygons2d/private/PaxHeaders.28738/__dbl2int64__.m0000644000000000000000000000013213066736044022337 xustar0030 mtime=1490795556.684871172 30 atime=1490795556.684871172 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/private/__dbl2int64__.m0000644000175000017500000000367513066736044022526 0ustar00olafolaf00000000000000## Copyright (C) 2017 Philip Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . function [opol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly=[], xy_mean=[], xy_magn=[]) if (isempty (clippoly)) clippoly = zeros (0, size (inpoly, 2)); endif if (isempty (xy_mean)) ## Convert & scale to int64 (that's what Clipper works with) ## Find (X, Y) translation xy_mean = mean ([inpoly; clippoly] (isfinite ([inpoly; clippoly](:, 1)), :)); ## Find (X, Y) magnitude xy_magn = max ([inpoly; clippoly] (isfinite ([inpoly; clippoly](:, 1)), :)) ... - min ([inpoly; clippoly] (isfinite ([inpoly; clippoly](:, 1)), :)); ## Apply (X,Y) multiplication (floor (log10 (intmax ("int64"))) = 18) xy_magn = 10^(17 - ceil (max (log10 (xy_magn)))); endif ## Scale inpoly coordinates to optimally use int64 inpoly(:, 1:2) -= xy_mean; inpoly *= xy_magn; idin = [ 0 find(isnan (inpoly (:, 1)))' numel(inpoly (:, 1))+1 ]; ## Provisional preallocation npolx = size (inpoly, 1) / numel (idin-1); npoly = size (inpoly, 2); opol = repmat (struct ("x", zeros (npolx, npoly), "y", zeros (npolx, npoly)), ... 1, numel(idin) - 1); for ii=1:numel (idin) - 1 opol(ii).x = int64 (inpoly(idin(ii)+1:idin(ii+1)-1, 1)); opol(ii).y = int64 (inpoly(idin(ii)+1:idin(ii+1)-1, 2)); endfor endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/simplifyPolygon.m0000644000000000000000000000013213066736044021565 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/simplifyPolygon.m0000644000175000017500000000543413066736044021747 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012-2016 Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{spoly} = } simplifyPolygon (@var{poly}) ## Simplify a polygon using the Ramer-Douglas-Peucker algorithm. ## ## @var{poly} is a N-by-2 matrix, each row representing a vertex. ## ## @seealso{simplifyPolyline, shape2polygon} ## @end deftypefn function polygonsimp = simplifyPolygon (polygon, varargin) polygonsimp = simplifyPolyline (polygon,varargin{:}); # Remove parrallel consecutive edges PL = polygonsimp(1:end-1,:); PC = polygonsimp(2:end,:); PR = polygonsimp([3:end 1],:); a = PL - PC; b = PR - PC; tf = find (isParallel(a,b))+1; polygonsimp (tf,:) = []; endfunction %!test %! P = [0 0; 1 0; 0 1]; %! P2 = [0 0; 0.1 0; 0.2 0; 0.25 0; 1 0; 0 1; 0 0.7; 0 0.6; 0 0.3; 0 0.1]; %! assert(simplifyPolygon (P2),P,min(P2(:))*eps) %!demo %! %! P = [0 0; 1 0; 0 1]; %! P2 = [0 0; 0.1 0; 0.2 0; 0.25 0; 1 0; 0 1; 0 0.7; 0 0.6; 0 0.3; 0 0.1]; %! Pr = simplifyPolygon (P2); %! %! cla %! drawPolygon(P,'or;Reference;'); %! hold on %! drawPolygon(P2,'x-b;Redundant;'); %! drawPolygon(Pr,'*g;Simplified;'); %! hold off %! %! # -------------------------------------------------------------------------- %! # The two polygons describe the same figure, a triangle. Extra points are %! # removed from the redundant one. geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/curvature.m0000644000000000000000000000013213066736044020401 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/curvature.m0000644000175000017500000001421513066736044020560 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{kappa} = } curvature (@var{t}, @var{px}, @var{py},@var{method},@var{degree}) ## @deftypefnx {Function File} {@var{kappa} = } curvature (@var{t}, @var{poly},@var{method},@var{degree}) ## @deftypefnx {Function File} {@var{kappa} = } curvature (@var{px}, @var{py},@var{method},@var{degree}) ## @deftypefnx {Function File} {@var{kappa} = } curvature (@var{points},@var{method},@var{degree}) ## @deftypefnx {Function File} {[@var{kappa} @var{poly} @var{t}] = } curvature (@dots{}) ## Estimate curvature of a polyline defined by points. ## ## First compute an approximation of the curve given by PX and PY, with ## the parametrization @var{t}. Then compute the curvature of approximated curve ## for each point. ## @var{method} used for approximation can be only: 'polynom', with specified degree. ## Further methods will be provided in a future version. ## @var{t}, @var{px}, and @var{py} are N-by-1 array of the same length. The points ## can be specified as a single N-by-2 array. ## ## If the argument @var{t} is not given, the parametrization is estimated using ## function @code{parametrize}. ## ## If requested, @var{poly} contains the approximating polygon evlauted at the ## parametrization @var{t}. ## ## @seealso{parametrize, polygons2d} ## @end deftypefn function [kappa, varargout] = curvature(varargin) # default values degree = 5; t=0; # parametrization of curve tc=0; # indices of points wished for curvature # ================================================================= # Extract method and degree ------------------------------ nargin = length(varargin); varN = varargin{nargin}; varN2 = varargin{nargin-1}; if ischar(varN2) # method and degree are specified method = varN2; degree = varN; varargin = varargin(1:nargin-2); elseif ischar(varN) # only method is specified, use degree 6 as default method = varN; varargin = varargin{1:nargin-1}; else # method and degree are implicit : use 'polynom' and 6 method = 'polynom'; end # extract input parametrization and curve. ----------------------- nargin = length(varargin); if nargin==1 # parameters are just the points -> compute caracterization. var = varargin{1}; px = var(:,1); py = var(:,2); elseif nargin==2 var = varargin{2}; if size(var, 2)==2 # parameters are t and POINTS px = var(:,1); py = var(:,2); t = varargin{1}; else # parameters are px and py px = varargin{1}; py = var; end elseif nargin==3 var = varargin{2}; if size(var, 2)==2 # parameters are t, POINTS, and tc px = var(:,1); py = var(:,2); t = varargin{1}; else # parameters are t, px and py t = varargin{1}; px = var; py = varargin{3}; end elseif nargin==4 # parameters are t, px, py and tc t = varargin{1}; px = varargin{2}; py = varargin{3}; tc = varargin{4}; end # compute implicit parameters -------------------------- # if t and/or tc are not computed, use implicit definition if t==0 t = parametrize(px, py, 'norm'); end # if tc not defined, compute curvature for all points if tc==0 tc = t; else # else convert from indices to parametrization values tc = t(tc); end # ================================================================= # compute curvature for each point of the curve if strcmp(method, 'polynom') # compute coefficients of interpolation functions x0 = polyfit(t, px, degree); y0 = polyfit(t, py, degree); # compute coefficients of first and second derivatives. In the case of a # polynom, it is possible to compute coefficient of derivative by # multiplying with a matrix. derive = diag(degree:-1:0); xp = circshift(x0*derive, [0 1]); yp = circshift(y0*derive, [0 1]); xs = circshift(xp*derive, [0 1]); ys = circshift(yp*derive, [0 1]); # compute values of first and second derivatives for needed points xprime = polyval(xp, tc); yprime = polyval(yp, tc); xsec = polyval(xs, tc); ysec = polyval(ys, tc); # compute value of curvature kappa = (xprime.*ysec - xsec.*yprime)./ ... power(xprime.*xprime + yprime.*yprime, 3/2); if nargout > 1 varargout{1} = [polyval(x0,tc(:)) polyval(y0,tc(:))]; if nargout > 2 varargout{2} = tc; end end else error('unknown method'); end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/expandPolygon.m0000644000000000000000000000013213066736044021210 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/expandPolygon.m0000644000175000017500000000673613066736044021400 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{loops} = } expandPolygon (@var{poly}, @var{dist}) ## Expand a polygon by a given (signed) distance ## ## Associates to each edge of the polygon @var{poly} the parallel line located ## at distance @var{dist} from the current edge, and compute intersections with ## neighbor parallel lines. The resulting polygon is simplified to remove ## inner "loops", and can be disconnected. ## The result is a cell array, each cell containing a simple linear ring. ## ## This is a kind of dilation, but behaviour on corners is different. ## This function keeps angles of polygons, but there is no direct relation ## between length of 2 polygons. ## ## It is also possible to specify negative distance, and get all points ## inside the polygon. If the polygon is convex, the result equals ## morphological erosion of polygon by a ball with radius equal to the ## given distance. ## ## @seealso{polygons2d} ## @end deftypefn function loops = expandPolygon(poly, dist) # eventually copy first point at the end to ensure closed polygon if sum(poly(end, :)==poly(1,:))~=2 poly = [poly; poly(1,:)]; end # number of vertices of the polygon N = size(poly, 1)-1; # find lines parallel to polygon edges located at distance DIST lines = zeros(N, 4); for i=1:N side = createLine(poly(i,:), poly(i+1,:)); lines(i, 1:4) = parallelLine(side, dist); end # compute intersection points of consecutive lines lines = [lines;lines(1,:)]; poly2 = zeros(N, 2); for i=1:N poly2(i,1:2) = intersectLines(lines(i,:), lines(i+1,:)); end # split result polygon into set of loops (simple polygons) loops = polygonLoops(poly2); # keep only loops whose distance to original polygon is correct distLoop = zeros(length(loops), 1); for i=1:length(loops) distLoop(i) = distancePolygons(loops{i}, poly); end loops = loops(abs(distLoop-abs(dist)) ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{loops} = } polygonLoops (@var{poly}) ## @deftypefn {Function File} {@var{loops} = } polygonLoops (@var{poly}, @var{tol}) ## Divide a possibly self-intersecting polygon into a set of simple loops ## ## @var{poly} is a polygone defined by a series of vertices, ## The optional argument @var{tol} defines the tolerance for detecting when ## two vertices are equal, default value @code{sqrt (eps)}. ## @var{loops} is a cell array of polygons, containing the same vertices of the ## original polygon, but no loop self-intersect, and no couple of loops ## intersect each other. ## ## Example: ## @example ## poly = [0 0;0 10;20 10;20 20;10 20;10 0]; ## loops = polygonLoops(poly); ## figure(1); hold on; ## drawPolygon(loops); ## polygonArea(loops) ## @end example ## ## @seealso{polygons2d, polygonSelfIntersections} ## @end deftypefn function loops = polygonLoops(poly, tol = sqrt (eps)) % compute intersections [inters, pos1, pos2] = polygonSelfIntersections(poly, 'tolerance', tol); % case of a polygon without self-intersection if isempty(inters) loops = {poly}; return; end % array for storing loops loops = cell(0, 1); % sort intersection points with respect to their position on the polygon [positions, order] = sortrows([pos1 pos2 ; pos2 pos1]); inters = [inters ; inters]; inters = inters(order, :); %% First loop % initialize the beginning of the loop pos0 = 0; loop = polygonSubcurve(poly, pos0, positions(1, 1)); loop(end, :) = inters(1,:); vertex = inters(1,:); % prepare iteration on positions pos = positions(1, 2); positions(1, :) = []; inters(1,:) = []; while true % index of next intersection point ind = find(positions(:,1) > pos, 1, 'first'); % if not index is found, the current loop is complete if isempty(ind) break; end % compute the portion of curve between the two intersection points portion = polygonSubcurve(poly, pos, positions(ind, 1)); % ensure extremities have been computed only once portion(1, :) = vertex; vertex = inters(ind, :); portion(end, :) = vertex; % add the current portion of curve loop = [loop; portion]; %#ok % update current position on the polygon pos = positions(ind, 2); % remove processed intersection positions(ind, :) = []; inters(ind,:) = []; end % append the last portion of curve loop = [loop ; polygonSubcurve(poly, pos, pos0)]; % remove redundant vertices loop(sum(loop(1:end-1,:) == loop(2:end,:) ,2)==2, :) = []; if sum(diff(loop([1 end], :)) == 0) == 2 loop(end, :) = []; end % add current loop to the list of loops loops{1} = loop; %% Other loops Nl = 1; while ~isempty(positions) % initialize the next loop loop = []; pos0 = positions(1, 2); pos = positions(1, 2); vertex = inters(1,:); while true % index of next intersection point ind = find(positions(:,1) > pos, 1, 'first'); % compute the portion of curve between the two intersection points portion = polygonSubcurve(poly, pos, positions(ind, 1)); % ensure extremities have been computed only once portion(1, :) = vertex; vertex = inters(ind, :); portion(end, :) = vertex; % append the current portion of curve loop = [loop ; portion]; %#ok % update current position on the polygon pos = positions(ind, 2); % remove processed intersection positions(ind, :) = []; inters(ind,:) = []; % if not found, current loop is processed if pos == pos0 break; end end % remove redundant vertices loop(sum(loop(1:end-1,:) == loop(2:end,:) ,2)==2, :) = []; %#ok if sum(diff(loop([1 end], :))==0) == 2 loop(end, :) = []; end % add current loop to the list of loops Nl = Nl + 1; loops{Nl} = loop; end endfunction %!demo %! poly = [0 0;0 10;20 10;20 20;10 20;10 0]; %! loops = polygonLoops(poly); %! figure(1); hold on; %! drawPolygon(loops); %! for i=1:numel(loops) %! c = centroid (loops{i}); %! text (c(1),c(2), sprintf ( "Loop: %d", i)); %! endfor %! hold off geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/reversePolyline.m0000644000000000000000000000013213066736044021550 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/reversePolyline.m0000644000175000017500000000366513066736044021736 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{poly2} = } reversePolyline (@var{poly}) ## Reverse a polyline, by iterating vertices from the end ## ## POLY2 = reversePolyline(POLY) ## POLY2 has same vertices as POLY, but POLY2(i,:) is the same as ## POLY(END-i+1,:). ## ## @seealso{reversePolygon} ## @end deftypefn function rev = reversePolyline(poly) rev = poly(end:-1:1, :); endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/clipPolyline_clipper.m0000644000000000000000000000013213066736044022542 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/clipPolyline_clipper.m0000644000175000017500000000610313066736044022716 0ustar00olafolaf00000000000000## Copyright (C) 2017 Philip Nienhuis ## ## This program is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{olin}, @var{nlin}] = clipPolyline_clipper (@var{inlin}, @var{clippol}) ## @deftypefnx {Function File} [@var{olin}, @var{nlin}] = clipPolyline_clipper (@var{inlin}, @var{clippol}, @var{op}) ## Clip (possibly composite) polylines with polygon(s) using one of boolean ## methods. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polylines(s) ## to be clipped. Polyline sections are separated by [NaN NaN] rows. ## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the ## clip polygon(s). @var{clippol} may comprise separate and/or concentric ## polygons (the latter with holes). ## ## Optional argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## @end itemize ## ## Output array @var{oline} will be an Nx2 array of polyline sections ## resulting from the requested boolean operation. ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2017-03-21 ## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab function [olin, nlin] = clipPolyline_clipper (inpoly, clippoly, method=1) ## Input validation if (nargin < 2) print_usage (); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error (" clipPolyline: inpoly should be a numeric Nx2 array"); endif if (! isnumeric (clippoly) || size (clippoly, 2) < 2) error (" clipPolyline: clippoly should be a numeric Nx2 array"); elseif (! isnumeric (method) || method < 0 || method > 3) error (" clipPolyline: operation must be a numeric 0 or 1"); endif [inpol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly); clpol = __dbl2int64__ (clippoly, [], xy_mean, xy_magn); ## Perform boolean operation olin = clipper (inpol, clpol, method, -1); nlin = numel (olin); if (! isempty (olin)) ## Morph struct output into [X,Y] array. Put NaNs between sub-polys. First X: [tmp(1:2:2*nlin, 1)] = deal ({olin.x}); [tmp(2:2:2*nlin-1, 1)] = NaN; ## Convert back from in64 into double, wipe trailing NaN X = double (cell2mat (tmp)); ## Y-coordinates: [tmp(1:2:2*nlin, 1)] = deal ({olin.y}); [tmp(2:2:2*nlin-1, 1)] = NaN; Y = double (cell2mat (tmp)); olin = ([X Y] / xy_magn) + xy_mean; else olin = zeros (0, 2); endif endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/intersectLinePolygon.m0000644000000000000000000000013213066736044022541 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/intersectLinePolygon.m0000644000175000017500000001172213066736044022720 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %INTERSECTLINEPOLYGON Intersection points between a line and a polygon % % P = intersectLinePolygon(LINE, POLY) % Returns the intersection points of the lines LINE with polygon POLY. % LINE is a 1-by-4 row vector containing parametric representation of the % line (in the format [x0 y0 dx dy], see the function 'createLine' for % details). % POLY is a NV-by-2 array containing coordinates of the polygon vertices % P is a K-by-2 array containing the coordinates of the K intersection % points. % % P = intersectLinePolygon(LINE, POLY, TOL) % Specifies the tolerance for geometric tests. Default is 1e-14. % % [P INDS] = intersectLinePolygon(...) % Also returns the indices of edges involved in intersections. INDS is a % K-by-1 column vector, such that P(i,:) corresponds to intersection of % the line with the i-th edge of the polygon. If the intersection occurs % at a polygon vertex, the index of only one of the two neighbor edges is % returned. % Note that due to numerical approximations, the use of function % 'isPointOnEdge' may give results not consistent with this function. % % % Examples % % compute intersections between a square and an horizontal line % poly = [0 0;10 0;10 10;0 10]; % line = [5 5 1 0]; % intersectLinePolygon(line, poly) % ans = % 10 5 % 0 5 % % also return indices of edges % [inters inds] = intersectLinePolygon(line, poly) % inters = % 10 5 % 0 5 % inds = % 4 % 2 % % % compute intersections between a square and a diagonal line % poly = [0 0;10 0;10 10;0 10]; % line = [5 5 1 1]; % intersectLinePolygon(line, poly) % ans = % 0 0 % 10 10 % % See Also % lines2d, polygons2d, intersectLines, intersectRayPolygon % % --------- % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 31/10/2003. % % HISTORY % 2008-11-24 rename 'pi' as 'intersects', update doc % 2009-07-23 removed forgotten occurence of 'pi' variable (thanks to Bala % Krishnamoorthy) % 2010-01-26 rewrite using vectorisation % 2011-05-20 returns unique results % 2011-07-20 returns intersected edge indices % 2012-11-33 add 'diag' option for linePosition function [intersects, edgeIndices] = intersectLinePolygon(line, poly, varargin) % get computation tolerance tol = eps; if ~isempty(varargin) tol = varargin{1}; end % create the array of edges N = size(poly, 1); edges = [poly(1:N, :) poly([2:N 1], :)]; % compute intersections with supporting lines of polygon edges supportLines = edgeToLine(edges); intersects = intersectLines(line, supportLines, tol); % find edges that are not parallel to the input line inds = find(isfinite(intersects(:, 1))); % compute position of intersection points on corresponding lines pos = linePosition(intersects(inds, :), supportLines(inds, :), 'diag'); % and keep only intersection points located on edges b = pos > -tol & pos < 1+tol; inds = inds(b); intersects = intersects(inds, :); % remove multiple vertices (can occur for intersections located at polygon % vertices) [intersects, I, J] = unique(intersects, 'rows'); %#ok if nargout > 1 % return indices of edges involved in intersection % (in case of intersection located at a vertex, only one of the % neighbor edges is returned) edgeIndices = inds(I); end endfunction geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/simplifyPolyline.m0000644000000000000000000000013213066736044021731 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/simplifyPolyline.m0000644000175000017500000001166213066736044022113 0ustar00olafolaf00000000000000## Copyright (C) 2015-2016 - Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {} {[@var{pline2} @var{idx}] = } simplifyPolyline (@var{pline}) ## @deftypefnx {} {@dots{} = } simplifyPolyline (@dots{},@var{property},@var{value},@dots{}) ## Simplify or subsample a polyline using the Ramer-Douglas-Peucker algorithm, ## a.k.a. the iterative end-point fit algorithm or the split-and-merge algorithm. ## ## The @var{pline} as a N-by-2 matrix. Rows correspond to the ## verices (compatible with @code{polygons2d}). The vector @var{idx} constains ## the indexes on vetices in @var{pline} that generates @var{pline2}, i.e. ## @code{pline2 = pline(idx,:)}. ## ## @strong{Parameters} ## @table @samp ## @item 'Nmax' ## Maximum number of vertices. Default value @code{1e3}. ## @item 'Tol' ## Tolerance for the error criteria. Default value @code{1e-4}. ## @item 'MaxIter' ## Maximum number of iterations. Default value @code{10}. ## @item 'Method' ## Not implemented. ## @end table ## ## Run @code{demo simplifyPolyline} to see an example. ## ## @seealso{curve2polyline, curveval, simplifyPolygon} ## @end deftypefn function [pline idx] = simplifyPolyline (pline_o, varargin) ## TODO do not print warnings if user provided Nmax or MaxIter. # --- Parse arguments --- # parser = inputParser (); parser.FunctionName = "simplifyPolyline"; toldef = 1e-4;#max(sumsq(diff(pline_o),2))*2; parser.addParamValue ('Tol', toldef, @(x)x>0); parser.addParamValue ('Nmax', 1e3, @(x)x>0); parser.addParamValue ('MaxIter', 100, @(x)x>0); parser.parse(varargin{:}); Nmax = parser.Results.Nmax; tol = parser.Results.Tol; MaxIter = parser.Results.MaxIter; clear parser toldef msg = ["simplifyPolyline: Maximum number of points reached with maximum error %g." ... " Increase %s if the result is not satisfactory."]; # ------ # [N dim] = size (pline_o); idx = [1 N]; for iter = 1:MaxIter # Find the point with the maximum distance. [dist ii] = maxdistance (pline_o, idx); tf = dist > tol; n = sum (tf); if ( all (!tf) ); break; end idx(end+1:end+n) = ii(tf); idx = sort (idx); if length(idx) >= Nmax ## TODO remove extra points warning ('geometry:MayBeWrongOutput', sprintf (msg, max (dist),'Nmax')); break; end end if iter == MaxIter warning ('geometry:MayBeWrongOutput', sprintf (msg ,max (dist), 'MaxIter')); end pline = pline_o(idx,:); endfunction function [dist ii] = maxdistance (p, idx) ## Separate the groups of points according to the edge they can divide. idxc = arrayfun (@colon, idx(1:end-1), idx(2:end), "UniformOutput",false); points = cellfun (@(x)p(x,:), idxc, "UniformOutput",false); ## Build the edges edges = [p(idx(1:end-1),:) p(idx(2:end),:)]; edges = mat2cell (edges, ones (1,size (edges,1)), 4)'; ## Calculate distance between the points and the corresponding edge [dist ii] = cellfun (@dd, points, edges, idxc); endfunction function [dist ii] = dd (p,e,idx) [d pos] = distancePointEdge (p, e); [dist ii] = max (d); ii = idx(ii); endfunction %!demo %! t = linspace(0,1,100).'; %! y = polyval([1 -1.5 0.5 0],t); %! pline = [t y]; %! %! figure(1) %! clf %! plot (t,y,'-r;Original;','linewidth',2); %! hold on %! %! tol = [8 2 1 0.5]*1e-2; %! colors = jet(4); %! %! for i=1:4 %! pline_ = simplifyPolyline(pline,'tol',tol(i)); %! msg = sprintf('-;%g;',tol(i)); %! h = plot (pline_(:,1),pline_(:,2),msg); %! set(h,'color',colors(i,:),'linewidth',2,'markersize',4); %! end %! hold off %! %! # --------------------------------------------------------- %! # Four approximations of the initial polyline with decreasing tolerances. %!demo %! P = [0 0; 3 1; 3 4; 1 3; 2 2; 1 1]; %! func = @(x,y) linspace(x,y,5); %! P2(:,1) = cell2mat( ... %! arrayfun (func, P(1:end-1,1),P(2:end,1), ... %! 'uniformoutput',false))'(:); %! P2(:,2) = cell2mat( ... %! arrayfun (func, P(1:end-1,2),P(2:end,2), ... %! 'uniformoutput',false))'(:); %! %! P2s = simplifyPolyline (P2); %! %! plot(P(:,1),P(:,2),'s',P2(:,1),P2(:,2),'o',P2s(:,1),P2s(:,2),'-ok'); %! %! # --------------------------------------------------------- %! # Simplification of a polyline in the plane. geometry-3.0.0/inst/polygons2d/PaxHeaders.28738/distancePointPolyline.m0000644000000000000000000000013213066736044022701 xustar0030 mtime=1490795556.676871024 30 atime=1490795556.676871024 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polygons2d/distancePointPolyline.m0000644000175000017500000001030513066736044023054 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## Author: 2004-2011 David Legland ## Author: 2016 Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dist} = } distancePointPolyline (@var{point},@var{poly}) ## @deftypefnx {Function File} {[@var{dist} @var{pos}] = } distancePointPolyline (@var{point},@var{poly}) ## Compute shortest distance @var{dist} between a point and a polyline ## ## If the the second output argument @var{pos} is requested, the function also ## returns the position of closest point on the polyline. @var{pos} is comprised ## between 0 and NV, the number of polyline vertices. ## ## Example: ## @example ## pt1 = [30 20]; ## pt2 = [30 5]; ## poly = [10 10;50 10;50 50;10 50]; ## distancePointPolyline([pt1;pt2], poly) ## ans = ## 10 ## 5 ## @end example ## ## @seealso{polygons2d, points2d,distancePointEdge, projPointOnPolyline} ## @end deftypefn function [minDist pos] = distancePointPolyline (point, poly, closed = false) # check if input polyline is closed or not if strcmp ('closed', closed) closed = true; elseif strcmp ('open', closed) closed = false; endif # closes the polyline if necessary if closed poly = [poly; poly(1,:)]; endif # number of points Np = size (point, 1); # allocate memory for result minDist = inf (Np, 1); ## construct the set of edges edges = [poly(1:end-1, :) poly(2:end, :)]; ## compute distance between current each point and all edges [dist edgepos] = distancePointEdge (point, edges); ## get the minimum distance [minDist i] = min (dist, [], 2); # Contributed by Raghu Charan A 02.2016 pos = []; if nargout == 2 Ne = size (edgepos, 2); j = sub2ind ([Np,Ne], (1:Np).', i); pos = i - 1 + edgepos(j); endif endfunction %!demo %! point = [2 1] .* rand (10,2) - [1 0]; %! t = linspace (0,pi,25).'; %! poly = [cos(t) sin(t)]; %! [d pos] = distancePointPolyline (point,poly); %! %! # Calculate the projection on the polyline to plot %! p_ = zeros (10, 2); %! %! # projection on vertices of the polyline %! isvertex = abs (pos - fix (pos)) < eps; %! p_(isvertex,:) = poly (pos(isvertex)+1,:); %! %! # the rest %! pos = pos (!isvertex); %! i = fix (pos) + 1; %! x = pos - fix (pos); %! p_(!isvertex,:) = poly(i,:) + x.*(poly(i+1,:)-poly(i,:)); %! %! # Plot %! plot (poly(:,1), poly(:,2),'.-', ... %! point(:,1), point(:,2), 'o', ... %! p_(:,1), p_(:,2),'.'); %! legend ('Polyline', 'Points', 'Projections'); %! line ([point(:,1) p_(:,1)].',[point(:,2) p_(:,2)].'); %! arrayfun (@(i)text ((p_(i,1)+point(i,1))/2, (p_(i,2)+point(i,2))/2, ... %! sprintf("%.2f", d(i))), 1:10); %! axis tight %! axis equal geometry-3.0.0/inst/PaxHeaders.28738/shape2d0000644000000000000000000000013113066736044015353 xustar0029 mtime=1490795556.69287132 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/0002755000175000017500000000000013066736044015607 5ustar00olafolaf00000000000000geometry-3.0.0/inst/shape2d/PaxHeaders.28738/curveval.m0000644000000000000000000000013013066736044017434 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/curveval.m0000644000175000017500000000200313066736044017605 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{p} = } curveval (@var{curve}, @var{t}) ## Evaluates parametric @var{curve} at @var{t}. ## ## @end deftypefn function p = curveval (curve, t) dim = size (curve,1); p = zeros (length(t), dim); for i = 1:dim p(:,i) = polyval (curve(i,:), t); end endfunction geometry-3.0.0/inst/shape2d/PaxHeaders.28738/shape2polygon.m0000644000000000000000000000013013066736044020377 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/shape2polygon.m0000644000175000017500000000515013066736044020556 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{polygon} = } shape2polygon (@var{shape}) ## @deftypefnx {Function File} {@var{polygon} = } shape2polygon (@dots{},@var{property},@var{value},@dots{}) ## Transforms a 2D shape described by piecewise smooth polynomials into a polygon. ## ## @var{shape} is a n-by-1 cell where each element is a pair of polynomials ## compatible with polyval. ## @var{polygon} is a k-by-2 matrix, where each row represents a vertex. ## The property-value pairs are passed to @code{curve2polyline}. ## ## @seealso{polygon2shape, curve2poyline} ## @end deftypefn function polygon = shape2polygon (shape, varargin) polygon = cell2mat ( ... cellfun (@(x) curve2polyline(x,varargin{:}), shape,'UniformOutput',false) ); polygon = simplifyPolygon(polygon); if size (polygon, 1) == 1 polygon(2,1) = polyval (shape{1}(1,:), 1); polygon(2,2) = polyval (shape{1}(2,:), 1); end endfunction %!demo %! shape = {[-93.172 606.368 -476.054 291.429; ... %! -431.196 637.253 11.085 163.791]; ... %! [-75.3626 -253.2337 457.1678 328.5714; ... %! 438.7659 -653.6278 -7.9953 380.9336]; ... %! [-89.5841 344.9716 -275.3876 457.1429; ... %! -170.3613 237.8858 1.0469 158.0765];... %! [32.900 -298.704 145.804 437.143; ... %! -243.903 369.597 -34.265 226.648]; ... %! [-99.081 409.127 -352.903 317.143; ... %! 55.289 -114.223 -26.781 318.076]; ... %! [-342.231 191.266 168.108 274.286; ... %! 58.870 -38.083 -89.358 232.362]}; %! %! # Estimate a good tolerance %! n = cell2mat(cellfun(@(x)curveval(x,rand(1,10)), shape, 'uniformoutput',false)); %! dr = (max(n(:,1))-min(n(:,1)))*(max(n(:,2))-min(n(:,2)))*40; %! p = shape2polygon (shape,'tol',dr); %! %! figure(1) %! plotShape(shape,'-b'); %! hold on; %! drawPolygon (p,'-or'); %! hold off geometry-3.0.0/inst/shape2d/PaxHeaders.28738/transformShape.m0000644000000000000000000000013013066736044020601 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/transformShape.m0000644000175000017500000000622313066736044020762 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{nshape} = } transformShape (@var{shape}, @var{T}) ## Applies transformation to a shape defined by piecewise smooth polynomials. ## ## @var{shape} is a cell where each elements is a 2-by-(poly_degree+1) matrix ## containing a pair of polynomials. ## ## Format of @var{T} can be one of : ## @example ## @group ## [c] , [a b] , [a b c] or [a b c] ## [f] [d e] [d e f] [d e f] ## [0 0 1] ## @end group ## @end example ## ## @seealso{shape2polygon, plotShape} ## @end deftypefn function nshape = transformShape (shape, Trans) if size(Trans,1) < 2 error("geometry:invalid-input-arg", ... "Transformation can be 2x1, 2x2, 2x3 or 3x3. See help."); end if ~iscell(shape) error("geometry:invalid-input-arg", "Shape must be a cell of 2D polynomials."); end A =[]; v = []; switch size(Trans,2) case 1 # Just translation v = Trans; case 2 # Just linear transformation A = Trans; case 3 # Affine transform A = Trans(1:2,1:2); v = Trans(1:2,3); end nshape = cellfun (@(x)polytransform (x,A,v), shape, 'UniformOutput',false); endfunction function np = polytransform(p,A,v) np = p; if ~isempty (A) np = A*np; end if ~isempty (v) np(:,end) = np(:,end) + v; end endfunction %!demo %! shape = {[-93.172 606.368 -476.054 291.429; ... %! -431.196 637.253 11.085 163.791]; ... %! [-75.3626 -253.2337 457.1678 328.5714; ... %! 438.7659 -653.6278 -7.9953 380.9336]; ... %! [-89.5841 344.9716 -275.3876 457.1429; ... %! -170.3613 237.8858 1.0469 158.0765];... %! [32.900 -298.704 145.804 437.143; ... %! -243.903 369.597 -34.265 226.648]; ... %! [-99.081 409.127 -352.903 317.143; ... %! 55.289 -114.223 -26.781 318.076]; ... %! [-342.231 191.266 168.108 274.286; ... %! 58.870 -38.083 -89.358 232.362]}; %! warning ("off", 'geom2d:cw-shape',"local"); %! A = shapeArea (shape); %! T = eye(2)/sqrt(A); %! shape = transformShape (shape,T); %! T = shapeCentroid (shape)(:); %! shape = transformShape (shape,-T + [2; 0]); %! %! close %! plotShape (shape,'-r','linewidth',2); %! hold on %! for i = 1:9 %! T = createRotation (i*pi/5)(1:2,1:2)/exp(0.3*i); %! plotShape (transformShape(shape, T), 'color',rand(1,3),'linewidth',2); %! end %! hold off %! axis image geometry-3.0.0/inst/shape2d/PaxHeaders.28738/curve2polyline.m0000644000000000000000000000013013066736044020567 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/curve2polyline.m0000644000175000017500000001007513066736044020750 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{polyline} = } curve2polyline (@var{curve}) ## @deftypefnx {Function File} {@var{polyline} = } curve2polyline (@dots{},@var{property},@var{value},@dots{}) ## Adaptive sampling of a parametric curve. ## ## The @var{curve} is described as a 2-by-N matrix. Rows correspond to the ## polynomial (compatible with @code{polyval}) describing the respective component ## of the curve. The curve must be parametrized in the interval [0,1]. ## The vertices of the polyline are accumulated in regions of the curve where ## the curvature is higher. ## ## @strong{Parameters} ## @table @samp ## @item 'Nmax' ## Maximum number of vertices. Not used. ## @item 'Tol' ## Tolerance for the error criteria. Default value @code{1e-4}. ## @item 'MaxIter' ## Maximum number of iterations. Default value @code{10}. ## @item 'Method' ## Not implemented. ## @end table ## ## This function is based on the algorithm described in ## L. H. de Figueiredo (1993). "Adaptive Sampling of Parametric Curves". Graphic Gems III. ## @seealso{shape2polygon, curveval} ## @end deftypefn ## I had to remove the recursion so this version could be improved. ## Thursday, April 12 2012 -- JuanPi function [polyline t bump]= curve2polyline (curve, varargin) ## TODO make tolerance relative to the "diameter" of the curve. # --- Parse arguments --- # parser = inputParser (); parser.FunctionName = "curve2polyline"; parser.addParamValue ('Nmax', 32, @(x)x>0); parser.addParamValue ('Tol', 1e-4, @(x)x>0); parser.addParamValue ('MaxIter', 10, @(x)x>0); parser.parse(varargin{:}); Nmax = parser.Results.Nmax; tol = parser.Results.Tol; MaxIter = parser.Results.MaxIter; clear parser toldef # ------ # t = [0; 1]; tf = 1; points = 1; for iter = 1:MaxIter # Add parameter values where error is still bigger than tol. t = interleave(t, tf); nt = length (t); # Update error polyline = curveval (curve,t); bump = bumpyness (polyline); # Check which intervals must be subdivided idx = find (bump > tol); # The position of the bumps maps into intervals # 1 -> 1 2 # 2 -> 3 4 # 3 -> 5 6 # and so on idx = [2*(idx-1)+1; 2*idx](:); tf = false (nt-1,1); tf(idx) = true; if all (!tf) break; end end endfunction function f = bumpyness (p) ## Check for co-linearity ## TODO implement various method for this ## -- Area of the triangle close to zero (used currently). ## -- Angle close to pi. ## -- abs(p0-pt) + abs(pt-p1) - abs(p0-p1) almost zero. ## -- Curve's tange at 0,t,1 are almost parallel. ## -- pt is in chord p0 -> p1. ## Do this in isParallel.m and remove this function PL = p(1:2:end-2,:); PC = p(2:2:end-1,:); PR = p(3:2:end,:); a = PL - PC; b = PR - PC; f = (a(:,1).*b(:,2) - a(:,2).*b(:,1)).^2; endfunction function tt = interleave (t,varargin) nt = length (t); ntt = 2 * nt -1; tt = zeros (ntt,1); tt(1:2:ntt) = t; beta = 0.4 + 0.2 * rand (nt-1, 1); tt(2:2:ntt) = t(1:end-1) + beta .* (t(2:end)-t(1:end-1)); if nargin > 1 tf = true (ntt,1); tf(2:2:ntt) = varargin{1}; tt(!tf) = []; end endfunction %!demo %! curve = [0 0 1 0;1 -0.3-1 0.3 0]; %! polyline = curve2polyline(curve,'tol',1e-8); %! %! t = linspace(0,1,100)'; %! pc = curveval(curve,t); %! %! plot(polyline(:,1),polyline(:,2),'-o',pc(:,1),pc(:,2),'-r') geometry-3.0.0/inst/shape2d/PaxHeaders.28738/plotShape.m0000644000000000000000000000013013066736044017544 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/plotShape.m0000644000175000017500000000304113066736044017720 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {} {@var{h} = } plotShape (@var{shape}) ## @deftypefnx {} {@var{h} = } plotShape (@dots{}, @var{prop}, @var{value}) ## Pots a 2D shape defined by piecewise smooth polynomials in the current axis. ## ## @var{shape} is a cell where each elements is a 2-by-(poly_degree+1) matrix ## containing a pair of polynomials. ## ## Additional property value pairs are passed to @code{drawPolygon}. ## ## @seealso{drawPolygon, shape2polygon} ## @end deftypefn function h = plotShape(shape, varargin) #FIXME: make this an option tol = 1e-4; n = cell2mat (cellfun (@(x)curveval (x,rand(1, 11)), shape, 'unif', 0)); dr = tol * ( max (n(:,1)) - min (n(:,1))) * ( max (n(:,2)) - min (n(:,2)) ); p = shape2polygon (shape,'tol', dr); h = drawPolygon (p,varargin{:}); endfunction geometry-3.0.0/inst/shape2d/PaxHeaders.28738/shapeArea.m0000644000000000000000000000013013066736044017476 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/shapeArea.m0000644000175000017500000000555313066736044017664 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {Function File} { [@var{a}, @var{ccw}]=} shapeArea (@var{pp}) ## Calculate the area of a 2D shape defined with piecewise smooth polynomials. ## ## Shape is defined with piecewise smooth polynomials. @var{pp} is a ## cell where each elements is a 2-by-(poly_degree+1) array containing a pair of ## polynomials. ## ## @code{px(i,:) = pp@{i@}(1,:)} and @code{py(i,:) = pp@{i@}(2,:)}. ## ## The returned area is always positive even if the shape is parametrized ## in a clockwise direction. If the case of a clockwise parametrized shape ## @code{@var{ccw} == -1} otherwise @code{@var{ccw} == 1}. ## ## @seealso{shapeCentroid, shape2polygon, plotShape} ## @end deftypefn function [A ccw] = shapeArea (shape) A = sum (cellfun (@Aint, shape)); ccw = sign (A); if (A < 0) warning ('geom2d:cw-shape', ... ['Shape has negative area. ' ... 'Assuming this is due to a clockwise parametrization of the boundary']); A = ccw * A; end endfunction function dA = Aint (x) px = x(1,:); py = x(2,:); P = polyint (conv (px, polyder(py))); dA = diff (polyval (P,[0 1])); end %!demo # non-convex piece-wise polynomial shape %! boomerang = {[ 0 -2 1; ... %! -4 4 0]; ... %! [0.25 -1; ... %! 0 0]; ... %! [ 0 1.5 -0.75; ... %! -3 3 0]; %! [0.25 0.75; ... %! 0 0]}; %! A = shapeArea (boomerang) %!test %! warning('off', 'geom2d:cw-shape', 'local'); %! triangle = {[1 0; 0 0]; [-0.5 1; 1 0]; [-0.5 0.5; -1 1]}; %! A = shapeArea (triangle); %! assert (0.5, A); %!test %! warning('off', 'geom2d:cw-shape', 'local'); %! circle = {[1.715729 -6.715729 0 5; ... %! -1.715729 -1.568542 8.284271 0]; ... %! [1.715729 1.568542 -8.284271 0; ... %! 1.715729 -6.715729 0 5]; ... %! [-1.715729 6.715729 0 -5; ... %! 1.715729 1.568542 -8.284271 0]; ... %! [-1.715729 -1.568542 8.284271 0; ... %! -1.715729 6.715729 0 -5]}; %! A = shapeArea (circle); %! assert (pi*5^2, A, 5e-2); geometry-3.0.0/inst/shape2d/PaxHeaders.28738/shapeCentroid.m0000644000000000000000000000013013066736044020375 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/shape2d/shapeCentroid.m0000644000175000017500000001252313066736044020556 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {Function File} { @var{cm} =} shapeCentroid (@var{pp}) ## Centroid of a simple plane shape defined with piecewise smooth polynomials. ## ## The shape is defined with piecewise smooth polynomials. @var{pp} is a ## cell where each elements is a 2-by-(poly_degree+1) matrix containing a pair ## of polynomials. ## @code{px(i,:) = pp@{i@}(1,:)} and @code{py(i,:) = pp@{i@}(2,:)}. ## ## The edges of the shape should not self-intersect. This function does not check for the ## sanity of the shape. ## ## @seealso{shapearea, shape2polygon} ## @end deftypefn function cm = shapeCentroid (shape) cm = sum( cell2mat ( cellfun (@CMint, shape, 'UniformOutput', false)), 1); [A ccw] = shapeArea (shape); cm = cm / A; if (ccw < 0) warning ('geom2d:cw-shape', ... 'Clockwise parametrized shape, inverting centroid.'); cm = -cm; end endfunction function dcm = CMint (x) px = x(1,:); py = x(2,:); Px = polyint (conv(conv (-px , py) , polyder (px))); Py = polyint (conv(conv (px , py) , polyder (py))); dcm = zeros (1,2); dcm(1) = diff(polyval(Px,[0 1])); dcm(2) = diff(polyval(Py,[0 1])); endfunction %!demo # non-convex bezier shape %! boomerang = {[ 0 -2 1; ... %! -4 4 0]; ... %! [0.25 -1; ... %! 0 0]; ... %! [ 0 1.5 -0.75; ... %! -3 3 0]; %! [0.25 0.75; ... %! 0 0]}; %! CoM = shapeCentroid (boomerang) %! Gcentroid = centroid(shape2polygon(boomerang)) %! figure(1); clf; %! plotShape(boomerang,'-o'); %! hold on %! drawPoint(CoM,'xk;shape centroid;'); %! drawPoint(Gcentroid,'xr;point centroid;'); %! hold off %! axis equal %!demo %! Lshape = {[0.00000 0.76635; -0.67579 -0.24067]; ... %! [0.77976 0.76635; 0.00000 -0.91646]; ... %! [0.00000 1.54611; 0.38614 -0.91646]; ... %! [-0.43813 1.54611; 0.00000 -0.53032]; ... %! [0.00000 1.10798; 0.28965 -0.53032]; ... %! [-0.34163 1.10798; 0.00000 -0.24067]};... %! CoM = shapeCentroid (Lshape) %! Gcentroid = centroid (shape2polygon (Lshape)) %! %! plotShape(Lshape,'-o'); %! hold on %! drawPoint(CoM,'xk;shape centroid;'); %! drawPoint(Gcentroid,'xr;point centroid;'); %! hold off %! axis equal %!test %! warning('off', 'geom2d:cw-shape', 'local'); %! square = {[1 -0.5; 0 -0.5]; [0 0.5; 1 -0.5]; [-1 0.5; 0 0.5]; [0 -0.5; -1 0.5]}; %! CoM = shapeCentroid (square); %! assert (CoM, [0 0], sqrt(eps)); %!test %! warning('off', 'geom2d:cw-shape', 'local'); %! square = {[1 -0.5; 0 -0.5]; [0 0.5; 1 -0.5]; [-1 0.5; 0 0.5]; [0 -0.5; -1 0.5]}; %! square_t = transformShape (square,[1;1]); %! CoM = shapeCentroid (square_t); %! assert (CoM, [1 1], sqrt(eps)); %!test %! warning('off', 'geom2d:cw-shape', 'local'); %! circle = {[1.715729 -6.715729 0 5; ... %! -1.715729 -1.568542 8.284271 0]; ... %! [1.715729 1.568542 -8.284271 0; ... %! 1.715729 -6.715729 0 5]; ... %! [-1.715729 6.715729 0 -5; ... %! 1.715729 1.568542 -8.284271 0]; ... %! [-1.715729 -1.568542 8.284271 0; ... %! -1.715729 6.715729 0 -5]}; %! CoM = shapeCentroid (circle); %! assert (CoM , [0 0], 5e-3); %!shared shape %! shape = {[-93.172 606.368 -476.054 291.429; ... %! -431.196 637.253 11.085 163.791]; ... %! [-75.3626 -253.2337 457.1678 328.5714; ... %! 438.7659 -653.6278 -7.9953 380.9336]; ... %! [-89.5841 344.9716 -275.3876 457.1429; ... %! -170.3613 237.8858 1.0469 158.0765];... %! [32.900 -298.704 145.804 437.143; ... %! -243.903 369.597 -34.265 226.648]; ... %! [-99.081 409.127 -352.903 317.143; ... %! 55.289 -114.223 -26.781 318.076]; ... %! [-342.231 191.266 168.108 274.286; ... %! 58.870 -38.083 -89.358 232.362]}; %!test # x-Reflection %! warning('off', 'geom2d:cw-shape', 'local'); %! v = shapeCentroid (shape)(:); %! T = createLineReflection([0 0 1 0]); %! nshape = transformShape (shape, T); %! vn = shapeCentroid (nshape)(:); %! assert(vn,T(1:2,1:2)*v); %!test # Rotation %! warning('off', 'geom2d:cw-shape', 'local'); %! v = shapeCentroid (shape)(:); %! T = createRotation(v.',pi/2); %! nshape = transformShape (shape, T); %! vn = shapeCentroid (nshape)(:); %! assert(vn,v,1e-2); %!test # Translation %! warning('off', 'geom2d:cw-shape', 'local'); %! v = shapeCentroid (shape)(:); %! nshape = transformShape (shape, -v); %! vn = shapeCentroid (nshape)(:); %! assert(vn,[0; 0],1e-2); geometry-3.0.0/inst/PaxHeaders.28738/polynomialCurves2d0000644000000000000000000000013113066736044017626 xustar0029 mtime=1490795556.69287132 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/0002755000175000017500000000000013066736044020062 5ustar00olafolaf00000000000000geometry-3.0.0/inst/polynomialCurves2d/PaxHeaders.28738/drawPolynomialCurve.m0000644000000000000000000000013213066736044024070 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/drawPolynomialCurve.m0000644000175000017500000000535613066736044024255 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawPolynomialCurve (@var{bnd}, @var{xcoef}, @var{ycoef}) ## @deftypefnx {Function File} {@var{h} =} drawPolynomialCurve (@var{bnd}, @var{coefs}) ## @deftypefnx {Function File} {@var{h} =} drawPolynomialCurve (@dots{}, @var{npts}) ## Draw a polynomial curve approximation ## @end deftypefn function varargout = drawPolynomialCurve(tBounds, varargin) ## Extract input parameters % polynomial coefficients for each coordinate var = varargin{1}; if iscell(var) xCoef = var{1}; yCoef = var{2}; varargin(1) = []; elseif size(var, 1)==1 xCoef = varargin{1}; yCoef = varargin{2}; varargin(1:2) = []; else xCoef = var(1,:); yCoef = var(2,:); varargin(1) = []; end nPts = 120; if ~isempty(varargin) nPts = varargin{1}; end # parametrization bounds t0 = tBounds(1); t1 = tBounds(end); ## Drawing the polyline approximation # generate vector of absissa t = linspace (t0, t1, nPts+1)'; # compute corresponding positions pts = polynomialCurvePoint (t, xCoef, yCoef); # draw the resulting curve h = drawPolyline (pts); if nargout > 0 varargout{1} = h; end endfunction geometry-3.0.0/inst/polynomialCurves2d/PaxHeaders.28738/polynomialCurvePoint.m0000644000000000000000000000013013066736044024262 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/polynomialCurvePoint.m0000644000175000017500000000574213066736044024450 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} =} polynomialCurvePoint (@var{t}, @var{xcoef},@var{ycoef}) ## @deftypefnx {Function File} {@var{point} =} polynomialCurvePoint (@var{t}, @var{coefs}) ## Compute point corresponding to a position ## ## @var{xcoef} and @var{ycoef} are row vectors of coefficients, in the form: ## [a0 a1 a2 ... an] ## @var{t} is a either a scalar, or a column vector, containing values of the ## parametrization variable. ## @var{point} is a 1x2 array containing coordinate of point corresponding to ## position given by @var{t}. If @var{t} is a vector, @var{point} has as many rows as @var{t}. ## ## @var{coefs} is either a 2xN matrix (one row for the coefficients of each ## coordinate), or a cell array. ## ## @seealso{polynomialCurves2d, polynomialCurveLength} ## @end deftypefn function point = polynomialCurvePoint (t, varargin) ## Extract input parameters # polynomial coefficients for each coordinate var = varargin{1}; if iscell (var) xCoef = var{1}; yCoef = var{2}; elseif size (var, 1)==1 xCoef = varargin{1}; yCoef = varargin{2}; else xCoef = var(1,:); yCoef = var(2,:); end ## compute length by numerical integration # convert polynomial coefficients to polyval convention cx = xCoef(end:-1:1); cy = yCoef(end:-1:1); # numerical integration of the Jacobian of parametrized curve point = [polyval(cx, t) polyval(cy, t)]; endfunction geometry-3.0.0/inst/polynomialCurves2d/PaxHeaders.28738/polynomialCurveFit.m0000644000000000000000000000013213066736044023715 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/polynomialCurveFit.m0000644000175000017500000002245313066736044024077 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{xc}, @var{yc}] =} polynomialCurveFit (@var{t}, @var{xt}, @var{yt}, @var{order}) ## @deftypefnx {Function File} {[@var{xc}, @var{yc}] =} polynomialCurveFit (@var{t}, @var{points}, @var{order}) ## @deftypefnx {Function File} {[@var{xc}, @var{yc}] =} polynomialCurveFit (@dots{}, @var{ti}, @var{condi}) ## Fit a polynomial curve to a series of points ## ## @var{t} is a Nx1 vector. ## ## @var{xt} and @var{yt} are coordinate for each parameter value (column vectors). ## @var{order} is the degree of the polynomial used for interpolation. ## @var{xc} and @var{yc} are polynomial coefficients, given in @var{order}+1 row vectors, ## starting from degree 0 and up to degree @var{order}. ## @var{points} specifies coordinate of points in a Nx2 array. ## ## Impose some specific conditions using @var{ti} and @var{condi}. ## ## @var{ti} is a value of the parametrization variable. @var{condi} is a cell ## array, with 2 columns, and as many rows as ## the derivatives specified for the given @var{ti}. Format for @var{condi} is: ## ## @var{condi} = @{X_I, Y_I; X_I', Y_I'; X_I", Y_I"; ...@}; ## ## with X_I and Y_I being the imposed coordinate at position @var{ti}, X_I' and ## Y_I' being the imposed first derivatives, X_I" and Y_I" the imposed ## second derivatives, and so on... ## To specify a derivative without specifying derivative with lower ## degree, value of lower derivative can be let empty, using '[]'. ## ## ## Requires the optimization Toolbox. ## ## Run @command{demo polynomialCurveFit} to see exaples of use. ## ## @seealso{polynomialCurves2d} ## @end deftypefn function varargout = polynomialCurveFit(t, varargin) ## extract input arguments # extract curve coordinate var = varargin{1}; if min(size(var))==1 # curve given as separate arguments xt = varargin{1}; yt = varargin{2}; varargin(1:2)=[]; else # curve coordinate bundled in a matrix if size(var, 1)1 Dx = var(1); Dy = var(2); else Dx = var; Dy = var; end varargin(1)=[]; ## Initialize local conditions # For a solution vector 'x', the following relation must hold: # Aeq * x == beq, # with: # Aeq Matrix M*N # beq column vector with length M # The coefficients of the Aeq matrix are initialized as follow: # First point and last point are considered successively. For each point, # k-th condition is the value of the (k-1)th derivative. This value is # computed using relation of the form: # value = sum_i ( fact(i) * t_j^pow(i) ) # with: # i indice of the (i-1) derivative. # fact row vector containing coefficient of each power of t, initialized # with a row vector equals to [1 1 ... 1], and updated for each # derivative by multiplying by corresponding power minus 1. # pow row vector of the powers of each monome. It is represented by a # row vector containing an increasing series of power, eventually # completed with zeros for lower degrees (for the k-th derivative, # the coefficients with power lower than k are not relevant). # Example for degree 5 polynom: # iter deriv pow fact # 1 0 [0 1 2 3 4 5] [1 1 1 1 1 1] # 2 1 [0 0 1 2 3 4] [0 1 2 3 4 5] # 3 2 [0 0 0 1 2 3] [0 0 1 2 3 4] # 4 3 [0 0 0 0 1 2] [0 0 0 1 2 3] # ... # The process is repeated for coordinate x and for coordinate y. # Initialize empty matrices Aeqx = zeros(0, Dx+1); beqx = zeros(0, 1); Aeqy = zeros(0, Dy+1); beqy = zeros(0, 1); # Process local conditions while ~isempty(varargin) if length(varargin)==1 warning('MatGeom:PolynomialCurveFit:ArgumentNumber', ... 'Wrong number of arguments in polynomialCurvefit'); end # extract parameter t, and cell array of local conditions ti = varargin{1}; cond = varargin{2}; # factors for coefficients of each polynomial. At the beginning, they # all equal 1. With successive derivatives, their value increase by the # corresponding powers. factX = ones(1, Dx+1); factY = ones(1, Dy+1); # start condition initialisations for i = 1:size(cond, 1) # degrees of each polynomial powX = [zeros(1, i) 1:Dx+1-i]; powY = [zeros(1, i) 1:Dy+1-i]; # update conditions for x coordinate if ~isempty(cond{i,1}) Aeqx = [Aeqx ; factY.*power(ti, powX)]; ##ok beqx = [beqx; cond{i,1}]; ##ok end # update conditions for y coordinate if ~isempty(cond{i,2}) Aeqy = [Aeqy ; factY.*power(ti, powY)]; ##ok beqy = [beqy; cond{i,2}]; ##ok end # update polynomial degrees for next derivative factX = factX.*powX; factY = factY.*powY; end varargin(1:2)=[]; end ## Initialisations # ensure column vectors t = t(:); xt = xt(:); yt = yt(:); # number of points to fit L = length(t); ## Compute coefficients of each polynomial # main matrix for x coordinate, size L*(degX+1) T = ones(L, Dx+1); for i = 1:Dx T(:, i+1) = power(t, i); end # compute interpolation # Octave compatibility - JPi 2013 xc = lsqlin (T, xt, zeros(1, Dx+1), 1, Aeqx, beqx)'; # main matrix for y coordinate, size L*(degY+1) T = ones(L, Dy+1); for i = 1:Dy T(:, i+1) = power(t, i); end # compute interpolation # Octave compatibility - JPi 2013 yc = lsqlin (T, yt, zeros(1, Dy+1), 1, Aeqy, beqy)'; ## Format output arguments if nargout <= 1 varargout{1} = {xc, yc}; else varargout{1} = xc; varargout{2} = yc; end endfunction function x = lsqlin (C, d, A, b, Aeq, beq) H = C'*C; q = -C'*d; x0 = zeros (size(C,2),size(d,2)); x = qp (x0, H, q, Aeq, beq, [], [],[], A, b); endfunction %!demo %! # defines a curve (circle arc) with small perturbations %! N = 50; %! t = linspace(0, 3*pi/4, N)'; %! xp = cos(t) + 5e-2*randn(size(t)); %! yp = sin(t) + 5e-2*randn(size(t)); %! %! [xc yc] = polynomialCurveFit(t, xp, yp, 3); %! %! figure(1); %! clf; %! drawPolynomialCurve(t([1 end]), xc, yc); %! hold on %! plot(xp,yp,'.g'); %! hold off %! axis tight %! axis equal %!demo %! # defines a curve (circle arc) with small perturbations %! N = 100; %! t = linspace(0, 3*pi/4, N)'; %! xp = cos(t) + 7e-2*randn(size(t)); %! yp = sin(t) + 7e-2*randn(size(t)); %! %! # plot the points %! figure (1); clf; hold on; %! axis ([-1.2 1.2 -.2 1.2]); axis equal; %! drawPoint (xp, yp, ".g"); %! %! # fit without knowledge on bounds %! [xc0 yc0] = polynomialCurveFit (t, xp, yp, 5); %! h = drawPolynomialCurve (t([1 end]), xc0, yc0); %! set(h, "color", "b") %! %! # fit by imposing coordinate on first point %! [xc1 yc1] = polynomialCurveFit (t, xp, yp, 5, 0, {1, 0}); %! h = drawPolynomialCurve (t([1 end]), xc1, yc1); %! set(h, "color", "r") %! %! # fit by imposing coordinate (1,0) and derivative (0,1) on first point %! [xc2 yc2] = polynomialCurveFit (t, xp, yp, 5, 0, {1, 0;0 1}); %! h = drawPolynomialCurve (t([1 end]), xc2, yc2); %! set(h, "color", "m") %! %! # fit by imposing several conditions on various points %! [xc3 yc3] = polynomialCurveFit (t, xp, yp, 5, ... %! 0, {1, 0;0 1}, ... # coord and first derivative of first point %! 3*pi/4, {-sqrt(2)/2, sqrt(2)/2}, ... # coord of last point %! pi/2, {[], [];-1, 0}); # derivative of point on the top of arc %! h = drawPolynomialCurve (t([1 end]), xc3, yc3); %! set(h, "color", "k") %! axis tight %! axis equal geometry-3.0.0/inst/polynomialCurves2d/PaxHeaders.28738/polynomialCurveDerivative.m0000644000000000000000000000013213066736044025275 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/polynomialCurveDerivative.m0000644000175000017500000000575513066736044025465 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{v} =} polynomialCurveDerivative (@var{t}, @var{xcoef},@var{ycoef}) ## @deftypefnx {Function File} {@var{v} =} polynomialCurveDerivative (@var{t}, @var{coefs}) ## Compute derivative vector of a polynomial curve ## ## @var{xcoef} and @var{ycoef} are row vectors of coefficients, in the form: ## [a0 a1 a2 ... an] ## @var{v} is a 1x2 array containing direction of derivative of polynomial ## curve, computed for position @var{t}. If @var{t} is a vector, @var{v} has as many rows ## as the length of @var{t}. ## ## @var{coefs} is either a 2xN matrix (one row for the coefficients of each ## coordinate), or a cell array. ## ## @seealso{polynomialCurves2d, polynomialCurveNormal, polynomialCurvePoint, ## polynomialCurveCurvature} ## @end deftypefn function v = polynomialCurveDerivative(t, varargin) ## Extract input parameters # polynomial coefficients for each coordinate var = varargin{1}; if iscell(var) xCoef = var{1}; yCoef = var{2}; elseif size(var, 1)==1 xCoef = varargin{1}; yCoef = varargin{2}; else xCoef = var(1,:); yCoef = var(2,:); end # convert to Octave polynomial convention xCoef = xCoef(end:-1:1); yCoef = yCoef(end:-1:1); # compute derivative of the polynomial dx = polyder (xCoef); dy = polyder (yCoef); # numerical integration of the Jacobian of parametrized curve v = [polyval(dx, t) polyval(dy, t)]; endfunction geometry-3.0.0/inst/polynomialCurves2d/PaxHeaders.28738/polynomialCurveCentroid.m0000644000000000000000000000013213066736044024742 xustar0030 mtime=1490795556.688871245 30 atime=1490795556.688871245 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/polynomialCurveCentroid.m0000644000175000017500000000775113066736044025130 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{c} =} polynomialCurveCentroid (@var{t}, @var{xcoef}, @var{ycoef}) ## @deftypefnx {Function File} {@var{c} =} polynomialCurveCentroid (@var{t}, @var{coefs}) ## @deftypefnx {Function File} {@var{c} =} polynomialCurveCentroid (@dots{}, @var{tol}) ## Compute the centroid of a polynomial curve ## ## @var{xcoef} and @var{ycoef} are row vectors of coefficients, in the form: ## [a0 a1 a2 ... an] ## @var{t} is a 1x2 row vector, containing the bounds of the parametrization ## variable: @var{t} = [T0 T1], with @var{t} taking all values between T0 and T1. ## @var{c} contains coordinate of the polynomial curve centroid. ## ## @var{coefs} is either a 2xN matrix (one row for the coefficients of each ## coordinate), or a cell array. ## ## @var{tol} is the tolerance fo computation (absolute). ## ## @seealso{polynomialCurves2d, polynomialCurveLength} ## @end deftypefn function centroid = polynomialCurveCentroid(tBounds, varargin) ## Extract input parameters # parametrization bounds t0 = tBounds(1); t1 = tBounds(end); # polynomial coefficients for each coordinate var = varargin{1}; if iscell(var) cx = var{1}; cy = var{2}; varargin(1) = []; elseif size(var, 1)==1 cx = varargin{1}; cy = varargin{2}; varargin(1:2)=[]; else cx = var(1,:); cy = var(2,:); varargin(1)=[]; end # convert to Octave polyval format cx = cx(end:-1:1); cy = cy(end:-1:1); # tolerance tol = 1e-6; if ~isempty(varargin) tol = varargin{1}; end ## compute length by numerical integration # compute derivative of the polynomial dx = polyder (cx); dy = polyder (cy); # compute curve length by integrating the Jacobian L = quad(@(t)sqrt(polyval(dx, t).^2+polyval(dy, t).^2), t0, t1, tol); # compute first coordinate of centroid xc = quad(@(t)polyval(cx, t).*sqrt(polyval(dx, t).^2+polyval(dy, t).^2), t0, t1, tol); # compute first coordinate of centroid yc = quad(@(t)polyval(cy, t).*sqrt(polyval(dx, t).^2+polyval(dy, t).^2), t0, t1, tol); # divide result of integration by total length of the curve centroid = [xc yc]/L; endfunction %!demo %! bounds = [-1 1]; %! coefs = [0 1 1; 0 -1 2]; %! c = polynomialCurveCentroid (bounds, coefs); %! %! drawPolynomialCurve (bounds, coefs(1,:), coefs(2,:)); %! hold on %! plot (c(1),c(2),'sr') %! hold off %! # ------------------------------------------------- %! # Centriod of a polynomial curve geometry-3.0.0/inst/polynomialCurves2d/PaxHeaders.28738/polynomialCurveSetFit.m0000644000000000000000000000013013066736044024367 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/polynomialCurves2d/polynomialCurveSetFit.m0000644000175000017500000001773713066736044024564 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{coefs}=} polynomialCurveSetFit (@var{img}) ## @deftypefnx {Function File} {@dots{} =} polynomalCurveSetFit (@var{img}, @var{deg}) ## @deftypefnx {Function File} {[@dots{} @var{lbl}] =} polynomalCurveSetFit (@dots{}) ## Fit a set of polynomial curves to a segmented image ## ## Result is a cell array of matrices. Each matrix is @var{deg}+1-by-2, and ## contains coefficients of polynomial curve for each coordinate. ## @var{bnds} contains the boundary of the parametrizations. ## @var{img} is first binarised, then skeletonized. ## ## Also returns an image of labels @var{lbl} for the segmented curves. The max label ## is the number of curves, and the length of @var{coefs}. ## ## Requires the toolboxes: ## - Optimization ## - Image Processing ## ## @seealso{polynomialCurves2d, polynomialCurveFit} ## @end deftypefn function [coefs lblBranches] = polynomialCurveSetFit(seg, varargin) # default degree for curves deg = 2; if ~isempty(varargin) deg = varargin{1}; end # ajoute un contour seg([1 end], :) = 1; seg(:, [1 end]) = 1; # skeletise le segmentat seg = bwmorph (seg, 'shrink', Inf); # compute image of multiple points (intersections between curves) imgNodes = imfilter (double (seg), ones ([3 3])) .* seg > 3; # compute coordinate of nodes, as c entroids of the multiple points lblNodes = bwlabel (imgNodes, 8); strct = regionprops (lblNodes, 'Centroid'); nodes = zeros (length (strct), 2); for i = 1:length (strct) nodes(i, [2 1]) = strct(i).Centroid; end # debug # figure(1) # subplot(1,2,1) # imshow(seg); # hold on # plot(nodes(:,1),nodes(:,2),'og') # subplot(1,2,2) # imshow(imgNodes); # hold on # plot(nodes(:,1),nodes(:,2),'og') # keyboard # enleve les bords de l'image seg([1 end], :) = 0; seg(:, [1 end]) = 0; # Isolate the branches imgBranches = seg & ~imgNodes; lblBranches = bwlabel (imgBranches, 8); # # donne une couleur a chaque branche, et affiche # map = colorcube(max(lblBranches(:))+1); # rgbBranches = label2rgb(lblBranches, map, 'w', 'shuffle'); # imshow(rgbBranches); # number of curves nBranches = max (lblBranches(:)); # allocate memory coefs = cell (nBranches, 1); bnds = cell (nBranches, 1); # For each curve, find interpolated polynomial curve for i = 1:nBranches # extract points corresponding to current curve imgBranch = lblBranches == i; points = chainPixels (imgBranch); # check number of points is sufficient if size (points, 1) < max (deg+1-2, 2) # find labels of nodes inds = unique (lblNodes(imdilate(imgBranch, true (3,3)))); inds = inds(inds ~= 0); if length (inds) < 2 warning ("geometry:poylnomialCurveSetFit", ... "Could not find extremities of branch number %d\n", i); continue; end # consider extremity nodes node0 = nodes(inds(1), :); node1 = nodes(inds(2), :); # use only a linear approximation xc = zeros(1, deg+1); yc = zeros(1, deg+1); xc(1) = node0(1); yc(1) = node0(2); xc(2) = node1(1)-node0(1); yc(2) = node1(2)-node0(2); # assigne au tableau de courbes coefs{i} = [xc;yc]; # next branch continue; end # find nodes closest to first and last points of the current curve [dist, ind0] = minDistancePoints (points(1, :), nodes); ##ok<*ASGLU> [dist, ind1] = minDistancePoints (points(end, :), nodes); # add nodes to the curve. points = [nodes(ind0,:); points; nodes(ind1,:)]; ##ok # parametrization of the polyline t = parametrize (points); t = t / max (t); # fit a polynomial curve to the set of points [xc yc] = polynomialCurveFit (... t, points, deg, ... 0, {points(1,1), points(1,2)},... 1, {points(end,1), points(end,2)}); #debug # plot(points(:,1),points(:,2),'or') # hold on # drawPolynomialCurve ([0 1], xc,yc); # axis tight # v = axis(); # hold off # imshow (~imgBranch) # hold on # plot(points(:,1),points(:,2),'or') # drawPolynomialCurve ([0 1], xc,yc); # axis xy # axis (v); # pause # stores result coefs{i} = [xc;yc]; end endfunction function points = chainPixels(img, varargin) #CHAINPIXELS return the list of points which constitute a curve on image # output = chainPixels(input) conn = 8; if ~isempty(varargin) conn = varargin{1}; end # matrice de voisinage if conn == 4 f = [0 1 0;1 1 1;0 1 0]; elseif conn == 8 f = ones([3 3]); end # find extremity points nb = imfilter(double(img), f) .* img; imgEnding = nb == 2 | nb == 1; [yi xi] = find(imgEnding); # extract coordinates of points [y x] = find(img); # index of first point if isempty(xi) # take arbitrary point ind = 1; else ind = find(x==xi(1) & y==yi(1)); end # allocate memory points = zeros(length(x), 2); if conn == 8 for i = 1:size(points, 1) # avoid multiple neighbors (can happen in loops) ind = ind(1); # add current point to chained curve points(i,:) = [x(ind) y(ind)]; # remove processed coordinate x(ind) = []; y(ind) = []; # find next candidate ind = find(abs(x-points(i,1))<=1 & abs(y-points(i,2))<=1); end else for i = 1:size(points, 1) # avoid multiple neighbors (can happen in loops) ind = ind(1); # add current point to chained curve points(i,:) = [x(ind) y(ind)]; # remove processed coordinate x(ind) = []; y(ind) = []; # find next candidate ind = find(abs(x-points(i,1)) + abs(y-points(i,2)) <=1 ); end end endfunction #FIXME not the best photo %!demo %! try %! pkg load image %! catch %! error ('You need the image package'); %! end %! disp ('Affected by bug https://savannah.gnu.org/bugs/?49757'); %! %! [m, cmap] = imread ("default.img"); %! m = ind2gray (m, cmap); %! mbw = im2bw(m, graythresh(m)*1.3); %! %! warning ("off", "geometry:poylnomialCurveSetFit", "local"); %! [c t] = polynomialCurveSetFit (mbw); %! %! figure(1) %! clf; %! imshow (m) %! hold on %! for i=1:numel(c) %! if !isempty (c{i}) %! drawPolynomialCurve ([0 1], c{i}); %! endif %! endfor %! hold off geometry-3.0.0/inst/PaxHeaders.28738/meshes3d0000644000000000000000000000013213066736044015541 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/0002755000175000017500000000000013066736044015774 5ustar00olafolaf00000000000000geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createDodecahedron.m0000644000000000000000000000013213066736044021537 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createDodecahedron.m0000644000175000017500000000776513066736044021732 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createDodecahedron() %CREATEDODECAHEDRON Create a 3D mesh representing a dodecahedron % % [V, E, F] = createDodecahedron; % Create a 3D mesh representing a dodecahedron % V is the 20-by-3 array of vertex coordinates % E is the 30-by-2 array of edge vertex indices % F is the 12-by-5 array of face vertex indices % % [V, F] = createDodecahedron; % Returns only the vertices and the face vertex indices. % % MESH = createDodecahedron; % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % Example % [v, e, f] = createDodecahedron; % drawMesh(v, f); % % Use values given by P. Bourke, see: % http://local.wasp.uwa.edu.au/~pbourke/geometry/platonic/ % faces are re-oriented to have normals pointing outwards. % % See also % meshes3d, drawMesh % createCube, createOctahedron, createIcosahedron, createTetrahedron % % --------- % author : David Legland % e-mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 29/07/2010. % % HISTORY % golden ratio phi = (1+sqrt(5))/2; % coordinates pre-computations b = 1 / phi ; c = 2 - phi ; % use values given by P. Bourke, see: % http://local.wasp.uwa.edu.au/~pbourke/geometry/platonic/ tmp = [ ... c 0 1 ; b b b ; 0 1 c ; -b b b ; -c 0 1 ; ... -c 0 1 ; -b -b b ; 0 -1 c ; b -b b ; c 0 1 ; ... c 0 -1 ; b -b -b ; 0 -1 -c ; -b -b -b ; -c 0 -1 ; ... -c 0 -1 ; -b b -b ; 0 1 -c ; b b -b ; c 0 -1 ; ... 0 1 -c ; 0 1 c ; b b b ; 1 c 0 ; b b -b ; ... 0 1 c ; 0 1 -c ; -b b -b ; -1 c 0 ; -b b b ; ... 0 -1 -c ; 0 -1 c ; -b -b b ; -1 -c 0 ; -b -b -b ; ... 0 -1 c ; 0 -1 -c ; b -b -b ; 1 -c 0 ; b -b b ; ... 1 c 0 ; b b b ; c 0 1 ; b -b b ; 1 -c 0 ; ... 1 -c 0 ; b -b -b ; c 0 -1 ; b b -b ; 1 c 0 ; ... -1 c 0 ; -b b -b ; -c 0 -1 ; -b -b -b ; -1 -c 0 ; ... -1 -c 0 ; -b -b b ; -c 0 1 ; -b b b ; -1 c 0 ; ... ]; % extract coordinates of unique vertices [verts, M, N] = unique(tmp, 'rows', 'first'); %#ok % compute indices of face vertices, put result in a 12-by-5 index array ind0 = reshape((1:60), [5 12])'; faces = N(ind0); % extract edges from faces edges = [reshape(faces(:, 1:5), [60 1]) reshape(faces(:, [2:5 1]), [60 1])]; edges = unique(sort(edges, 2), 'rows'); % format output varargout = formatMeshOutput(nargout, verts, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/trimMesh.m0000644000000000000000000000013213066736044017564 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/trimMesh.m0000644000175000017500000000612613066736044017745 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = trimMesh(vertices, edges, faces) %TRIMMESH Reduce memory footprint of a polygonal mesh % % [V2 F2] = trimMesh(V, F) % Reduces the size occupied by mesh, by keeping only vertices that are % referenced by at least one face, and relabel face indices. % % Example % [V F] = createIcosahedron; % F(13:20, :) = []; % [V2 F2] = trimMesh(V, F); % figure; drawMesh(V2, F2) % view(3); axis equal; % axis([-1 1 -1 1 0 2]) % % See also % meshes3d % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2014-08-01, using Matlab 8.3.0.532 (R2014a) % Copyright 2014 INRA - Cepia Software Platform. % check input number if nargin == 2 faces = edges; end % identify vertices referenced by a face vertexUsed = false(size(vertices, 1), 1); if isnumeric(faces) vertexUsed(unique(faces(:))) = true; elseif iscell(faces) for iFace = 1:length(faces) face = faces{iFace}; vertexUsed(face) = true; end end vertices2 = vertices(vertexUsed, :); % compute map from old index to new index inds = find(vertexUsed); newInds = zeros(size(vertices, 1), 1); for iIndex = 1:length(inds) newInds(inds(iIndex)) = iIndex; end % change labels of vertices referenced by faces if isnumeric(faces) faces2 = newInds(faces); elseif iscell(faces) faces2 = cell(1, length(faces)); for iFace = 1:length(faces) faces2{iFace} = newInds(faces{iFace}); end end % format output arguments varargout = formatMeshOutput(nargout, vertices2, faces2); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshVolume.m0000644000000000000000000000013213066736044020120 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshVolume.m0000644000175000017500000000642413066736044020302 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function vol = meshVolume(vertices, edges, faces) %MESHVOLUME Volume of the space enclosed by a polygonal mesh % % V = meshVolume(VERTS, FACES) % Computes the volume of the space enclosed by the polygonal mesh % represented by vertices VERTS (as a Nv-by-3 array of cooridnates) and % the array of faces FACES (either as a Nf-by-3 array of vertex indices, % or as a cell array of arrays of vertex indices). % % The volume is computed as the sum of the signed volumes of tetrahedra % formed by triangular faces and the centroid of the mesh. Faces need to % be oriented such that normal points outwards the mesh. See: % http://stackoverflow.com/questions/1838401/general-formula-to-calculate-polyhedron-volume % % Example % % computes the volume of a unit cube (should be equal to 1...) % [v f] = createCube; % meshVolume(v, f) % ans = % 1 % % See also % meshes3d, meshSurfaceArea, tetrahedronVolume % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2012-10-01, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. % HISTORY % 2013-08-16 speed improvement by Sven Holcombe % check input number if nargin == 2 faces = edges; end % ensure mesh has triangle faces faces = triangulateFaces(faces); % initialize an array of volume nFaces = size(faces, 1); vols = zeros(nFaces, 1); % Shift all vertices to the mesh centroid vertices = bsxfun(@minus, vertices, mean(vertices,1)); % compute volume of each tetraedron for i = 1:nFaces % consider the tetrahedron formed by face and mesh centroid tetra = vertices(faces(i, :), :); % volume of current tetrahedron vols(i) = det(tetra) / 6; end vol = sum(vols); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/trimeshMeanBreadth.m0000644000000000000000000000013213066736044021542 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/trimeshMeanBreadth.m0000644000175000017500000000724413066736044021725 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function mb = trimeshMeanBreadth(vertices, faces) %TRIMESHMEANBREADTH Mean breadth of a triangular mesh % % MB = trimeshMeanBreadth(VERTICES, FACES) % Computes the mean breadth (proporitonal to the integral of mean % curvature) of a triangular mesh. % % Example % [V, F] = createCube; % F2 = triangulateFaces(F); % MB = trimeshMeanBreadth(V, F2) % MB = % 1.5000 % % See also % meshes3d, trimeshSurfaceArea, trimeshEdgeFaces, polyhedronMeanBreadth % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2015-08-19, using Matlab 8.5.0.197613 (R2015a) % Copyright 2015 INRA - Cepia Software Platform. %% Compute edge and edgeFaces arrays % Uses the same code as in trimeshEdgeFaces % compute vertex indices of each edge (in increasing index order) edges = sort([faces(:,[1 2]) ; faces(:,[2 3]) ; faces(:,[3 1])], 2); % create an array to keep indices of faces "creating" each edge nFaces = size(faces, 1); edgeFaceInds = repmat( (1:nFaces)', 3, 1); % sort edges, keeping indices [edges, ia, ib] = unique(edges, 'rows'); %#ok nEdges = size(edges, 1); % allocate memory for result edgeFaces = zeros(nEdges, 2); % iterate over edges, to identify incident faces for iEdge = 1:nEdges inds = find(ib == iEdge); edgeFaces(iEdge, 1:length(inds)) = edgeFaceInds(inds); end %% Compute dihedral angle for each edge % compute normal of each face normals = faceNormal(vertices, faces); % allocate memory for resulting angles alpha = zeros(nEdges, 1); % iterate over edges for iEdge = 1:nEdges % indices of adjacent faces indFace1 = edgeFaces(iEdge, 1); indFace2 = edgeFaces(iEdge, 2); % normal vector of adjacent faces normal1 = normals(indFace1, :); normal2 = normals(indFace2, :); % compute dihedral angle of two vectors alpha(iEdge) = vectorAngle3d(normal1, normal2); end %% Compute mean breadth % integrate the dihedral angles weighted by the length of each edge % compute length of each edge lengths = meshEdgeLength(vertices, edges); % compute product of length by angles mb = sum(alpha .* lengths) / (4*pi); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createSoccerBall.m0000644000000000000000000000013213066736044021171 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createSoccerBall.m0000644000175000017500000000526313066736044021353 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createSoccerBall() %CREATESOCCERBALL Create a 3D mesh representing a soccer ball % % It is basically a wrapper of the 'bucky' function in matlab. % [V, E, F] = createSoccerBall % return vertices, edges and faces that constitute a soccerball % V is a 60-by-3 array containing vertex coordinates % E is a 90-by-2 array containing indices of neighbor vertices % F is a 32-by-1 cell array containing vertex indices of each face % Example % [v, f] = createSoccerBall; % drawMesh(v, f); % % See also % meshes, drawMesh, bucky % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2006-08-09 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). % HISTORY % 2007-01-04 remove unused variables, enhance output processing % 2010-12-07 clean up edges, uses formatMeshOutput % get vertices and adjacency matrix of the buckyball [b, n] = bucky; % compute edges [i, j] = find(b); e = [i j]; e = unique(sort(e, 2), 'rows'); % compute polygons that correspond to each 3D face f = minConvexHull(n)'; % format output varargout = formatMeshOutput(nargout, n, e, f); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/boxToMesh.m0000644000000000000000000000013213066736044017704 xustar0030 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/boxToMesh.m0000644000175000017500000000657413066736044020074 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = boxToMesh(varargin) % BOXTOMESH Convert a box into a quad mesh with the same size % % [V E F] = boxToMesh(BOX) % Create a box as a polyhedra representation. The box is defined by its % coordinate extents: BOX = [XMIN XMAX YMIN YMAX ZMIN ZMAX] % The result has the form [V E F], where V is a 8-by-3 array with vertex % coordinates, E is a 12-by-2 array containing indices of neighbour % vertices, and F is a 6-by-4 array containing vertices array of each % face. % % [V F] = boxToMesh(BOX) % Returns only the vertices and the face vertex indices. % % MESH = boxToMesh(BOX) % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % ... = boxToMesh() % Creates a unit cube % % Example % [v, f] = boxToMesh([-2 -1 0 pi 2 3]) % drawMesh(v, f); % % See also % meshes3d, drawMesh, triangulateFaces % --------- % authors: David Legland, oqilipo % created the 22/09/2016. p = inputParser; boxDefault = [0 1 0 1 0 1]; boxDatatype = {'numeric'}; boxAttribs = {'nonempty','vector','numel',6,'real','finite'}; addOptional(p,'box',boxDefault,@(x)validateattributes(x,boxDatatype,boxAttribs)) parse(p,varargin{:}) xmin = p.Results.box(1); xmax = p.Results.box(2); ymin = p.Results.box(3); ymax = p.Results.box(4); zmin = p.Results.box(5); zmax = p.Results.box(6); vertices = [... xmin, ymin, zmin; ... xmax, ymin, zmin; ... xmin, ymax, zmin; ... xmax, ymax, zmin; ... xmin, ymin, zmax; ... xmax, ymin, zmax; ... xmin, ymax, zmax; ... xmax, ymax, zmax; ... ]; edges = [1 2;1 3;1 5;2 4;2 6;3 4;3 7;4 8;5 6;5 7;6 8;7 8]; % faces are oriented such that normals point outwards faces = [1 3 4 2;5 6 8 7;2 4 8 6;1 5 7 3;1 2 6 5;3 7 8 4]; % format output varargout = formatMeshOutput(nargout, vertices, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/ellipsoidMesh.m0000644000000000000000000000013213066736044020575 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/ellipsoidMesh.m0000644000175000017500000001003313066736044020746 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = ellipsoidMesh(elli, varargin) %ELLIPSOIDMESH Convert a 3D ellipsoid to face-vertex mesh representation % % [V, F] = ellipsoidMesh(ELLI) % ELLI is given by: % [XC YC ZC A B C PHI THETA PSI], % where (XC, YC, ZC) is the ellipsoid center, A, B and C are the half % lengths of the ellipsoid main axes, and PHI THETA PSI are Euler angles % representing ellipsoid orientation, in degrees. % % % See also % meshes3d, drawEllipsoid, sphereMesh, inertiaEllipsoid % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-03-12, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. %% Default values % number of meridians nPhi = 32; % number of parallels nTheta = 16; %% Extract input arguments % Parse the input (try to extract center coordinates and radius) if nargin == 0 % no input: assumes ellipsoid with default shape elli = [0 0 0 5 4 3 0 0 0]; end % default set of options for drawing meshes options = {'FaceColor', 'g', 'linestyle', 'none'}; while length(varargin) > 1 switch lower(varargin{1}) case 'nphi' nPhi = varargin{2}; case 'ntheta' nTheta = varargin{2}; otherwise % assumes this is drawing option options = [options varargin(1:2)]; %#ok end varargin(1:2) = []; end %% Parse numerical inputs % Extract ellipsoid parameters xc = elli(:,1); yc = elli(:,2); zc = elli(:,3); a = elli(:,4); b = elli(:,5); c = elli(:,6); k = pi / 180; ellPhi = elli(:,7) * k; ellTheta = elli(:,8) * k; ellPsi = elli(:,9) * k; %% Coordinates computation % convert unit basis to ellipsoid basis sca = createScaling3d(a, b, c); rotZ = createRotationOz(ellPhi); rotY = createRotationOy(ellTheta); rotX = createRotationOx(ellPsi); tra = createTranslation3d([xc yc zc]); % concatenate transforms trans = tra * rotZ * rotY * rotX * sca; %% parametrisation of ellipsoid % spherical coordinates theta = linspace(0, pi, nTheta+1); phi = linspace(0, 2*pi, nPhi+1); % convert to cartesian coordinates sintheta = sin(theta); x = cos(phi') * sintheta; y = sin(phi') * sintheta; z = ones(length(phi),1) * cos(theta); % transform mesh vertices [x, y, z] = transformPoint3d(x, y, z, trans); % convert to FV mesh [vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', false, 'yPeriodic', true); % format output varargout = formatMeshOutput(nargout, vertices, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshEdgeLength.m0000644000000000000000000000013213066736044020657 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshEdgeLength.m0000644000175000017500000000421313066736044021033 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function lengths = meshEdgeLength(vertices, edges, faces) %#ok %MESHEDGELENGTH Lengths of edges of a polygonal or polyhedral mesh % % output = meshEdgeLength(V, E, F) % % Example % meshEdgeLength % % See also % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % extract vertices p1 = vertices(edges(:, 1), :); p2 = vertices(edges(:, 2), :); % compute euclidean distance betwenn the two vertices lengths = sqrt(sum((p2-p1).^2, 2)); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createMengerSponge.m0000644000000000000000000000013213066736044021551 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createMengerSponge.m0000644000175000017500000001137013066736044021727 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createMengerSponge() %CREATEMENGERSPONGE Create a cube with an inside cross removed % % [n, e, f] = createMengerSponge; % Main use is to test possibility of drawing polyhedra with complex faces % (polygonal faces with holes) % % Example % [n, e, f] = createMengerSponge; % drawMesh(n, f); % % See also % meshes3d, drawMesh % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2007-10-18 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. % HISTORY % 2008-10-17 finishes implementation nodes =[... ... % main cube corners (1->8) 0 0 0; ... 3 0 0; ... 0 3 0; ... 3 3 0; ... 0 0 3; ... 3 0 3; ... 0 3 3; ... 3 3 3; ... ... % outer cube inner face corners 1 1 0; ... % face z=0 (9->12) 2 1 0; ... 1 2 0; ... 2 2 0; ... 1 1 3; ... % face z=3 (13->16) 2 1 3; ... 1 2 3; ... 2 2 3; ... 1 0 1; ... % face y=0 (17->20) 2 0 1; ... 1 0 2; ... 2 0 2; ... 1 3 1; ... % face y=3 (21->24) 2 3 1; ... 1 3 2; ... 2 3 2; ... 0 1 1; ... % face x=0 (25->28) 0 2 1; ... 0 1 2; ... 0 2 2; ... 3 1 1; ... % face x=3 (29->32) 3 2 1; ... 3 1 2; ... 3 2 2; ... ... % inner cube corners (33->40) 1 1 1; ... 2 1 1; ... 1 2 1; ... 2 2 1; ... 1 1 2; ... 2 1 2; ... 1 2 2; ... 2 2 2; ... ]; edges = [... 1 2;1 3;2 4;3 4;5 6;5 7;6 8;7 8;1 5;2 6;3 7;4 8;... % outer cube 9 10;9 11;10 12;11 12;13 14;13 15;14 16;15 16; ... 17 18;17 19;18 20;19 20; 21 22;21 23;22 24;23 24; ... 25 26;25 27;26 28;27 28; 29 30;29 31;30 32;31 32; ... 33 34;33 35;34 36;35 36; 37 38;37 39;38 40;39 40; ... % inner cube 33 37;34 38;35 39;36 40; ... 9 33;10 34;11 35;12 36; ... % parallel to xy 13 37;14 38;15 39;16 40; ... 17 33;18 34;19 37;20 38; ... % parallel to yz 21 35;22 36;23 39;24 40; ... 25 33;26 35;27 37;28 39; ... % parallel to xz 29 34;30 36;31 38;32 40; ... ]; % Alternative definition for faces: % [1 2 4 3 NaN 9 11 12 10], ... % [5 6 8 7 NaN 13 15 16 14], ... % [1 5 7 3 NaN 25 26 28 27], .... % [2 6 8 4 NaN 29 30 32 31], ... % [1 2 6 5 NaN 17 18 20 19], ... % [3 4 8 7 NaN 21 22 24 23], ... faces = {... ... % 6 square faces with a square hole [1 2 4 3 1 9 11 12 10 9], ... [5 6 8 7 5 13 15 16 14 13], ... [1 5 7 3 1 25 26 28 27 25], .... [2 6 8 4 2 29 30 32 31 29], ... [1 2 6 5 1 17 18 20 19 17], ... [3 4 8 7 3 21 22 24 23 21], ... ... % faces orthogonal to XY plane, parallel to Oz axis [ 9 10 34 33], [ 9 11 35 33], [10 12 36 34], [11 12 36 35], ... [13 14 38 37], [13 15 39 37], [14 16 40 38], [15 16 40 39], ... ... % faces orthogonal to YZ plane, parallel to Oy axis [17 18 34 33], [17 19 37 33], [18 20 38 34], [19 20 38 37], ... [21 22 36 35], [21 23 39 35], [22 24 40 36], [23 24 40 39], ... ...% faces orthogonal to the YZ plane, parallel to Ox axis [25 33 35 26], [25 33 37 27], [26 35 39 28], [27 37 39 28], ... [29 30 36 34], [29 31 38 34], [30 32 40 36], [31 32 40 38], ... }; % format output varargout = formatMeshOutput(nargout, nodes, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/trimeshSurfaceArea.m0000644000000000000000000000013213066736044021551 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/trimeshSurfaceArea.m0000644000175000017500000000562613066736044021736 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function area = trimeshSurfaceArea(v, e, f) %TRIMESHSURFACEAREA Surface area of a triangular mesh % % S = trimeshSurfaceArea(V, F) % S = trimeshSurfaceArea(V, E, F) % Computes the surface area of the mesh specified by vertex array V and % face array F. Vertex array is a NV-by-3 array of coordinates. % Face array is a NF-by-3, containing vertex indices of each face. % % Example % % Compute area of an octahedron (equal to 2*sqrt(3)*a*a, with % % a = sqrt(2) in this case) % [v f] = createOctahedron; % trimeshSurfaceArea(v, f) % ans = % 6.9282 % % % triangulate a compute area of a unit cube % [v f] = createCube; % f2 = triangulateFaces(f); % trimeshSurfaceArea(v, f2) % ans = % 6 % % See also % meshes3d, meshSurfaceArea, trimeshMeanBreadth, triangulateFaces % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2011-08-26, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. % check input number if nargin == 2 f = e; end % compute two direction vectors, using first vertex of each face as origin v1 = v(f(:, 2), :) - v(f(:, 1), :); v2 = v(f(:, 3), :) - v(f(:, 1), :); % area of each triangle is half the cross product norm vn = vectorNorm3d(vectorCross3d(v1, v2)); % sum up and normalize area = sum(vn) / 2; geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/subdivideMesh.m0000644000000000000000000000013213066736044020567 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/subdivideMesh.m0000644000175000017500000001461713066736044020754 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [vertices2, faces2] = subdivideMesh(vertices, faces, n) %SUBDIVIDEMESH Subdivides each face of the mesh % % [V2 F2] = subdivideMesh(V, F, N) % Subdivides the mesh specified by (V,F) such that each face F is divided % into N^2 smaller faces. % % Example % [v f] = createOctahedron; % figure; drawMesh(v, f); view(3); % [v2 f2] = subdivideMesh(v, f, 4); % figure; drawMesh(v2, f2); view(3) % % See also % meshes3d, drawMesh % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2013-08-22, using Matlab 7.9.0.529 (R2009b) % Copyright 2013 INRA - Cepia Software Platform. %% Initialisations if ~isnumeric(faces) || size(faces, 2) ~= 3 error('Requires a triangular mesh'); end % compute the edge array % edgeVertexIndices = computeMeshEdges(faces); edges = meshEdges(faces); nEdges = size(edges, 1); % index of faces around each edge % edgeFaceIndices = meshEdgeFaces(vertices, edges, faces); % index of edges around each face faceEdgeIndices = meshFaceEdges(vertices, edges, faces); %% Create new vertices on edges % several interpolated positions t = linspace(0, 1, n + 1)'; coef2 = t(2:end-1); coef1 = 1 - t(2:end-1); % initialise the array of new vertices vertices2 = vertices; % keep an array containing index of new vertices for each original edge edgeNewVertexIndices = zeros(nEdges, n-1); % create new vertices on each edge for iEdge = 1:nEdges % extract each extremity as a point v1 = vertices(edges(iEdge, 1), :); v2 = vertices(edges(iEdge, 2), :); % compute new points newPoints = coef1 * v1 + coef2 * v2; % add new vertices, and keep their indices edgeNewVertexIndices(iEdge,:) = size(vertices2, 1) + (1:n-1); vertices2 = [vertices2 ; newPoints]; %#ok end %% Process each face faces2 = zeros(0, 3); nFaces = size(faces, 1); for iFace = 1:nFaces % compute index of each corner vertex face = faces(iFace, :); iv1 = face(1); iv2 = face(2); iv3 = face(3); % compute index of each edge faceEdges = faceEdgeIndices{iFace}; ie1 = faceEdges(1); ie2 = faceEdges(2); ie3 = faceEdges(3); % indices of new vertices on edges edge1NewVertexIndices = edgeNewVertexIndices(ie1, :); edge2NewVertexIndices = edgeNewVertexIndices(ie2, :); edge3NewVertexIndices = edgeNewVertexIndices(ie3, :); % keep vertex 1 as reference for edges 1 and 3 if edges(ie1, 1) ~= iv1 edge1NewVertexIndices = edge1NewVertexIndices(end:-1:1); end if edges(ie3, 1) ~= iv1 edge3NewVertexIndices = edge3NewVertexIndices(end:-1:1); end % create the first new face, on 'top' of the original face topVertexInds = [edge1NewVertexIndices(1) edge3NewVertexIndices(1)]; newFace = [iv1 topVertexInds]; faces2 = [faces2; newFace]; %#ok % iterate over middle strips for iStrip = 2:n-1 % index of extreme vertices of current row ivr1 = edge1NewVertexIndices(iStrip); ivr2 = edge3NewVertexIndices(iStrip); % extreme vertices as points v1 = vertices2(ivr1, :); v2 = vertices2(ivr2, :); % create additional vertices within the bottom row of the strip t = linspace(0, 1, iStrip+1)'; coef2 = t(2:end-1); coef1 = 1 - t(2:end-1); newPoints = coef1 * v1 + coef2 * v2; % compute indices of new vertices in result array newInds = size(vertices2, 1) + (1:iStrip-1); botVertexInds = [ivr1 newInds ivr2]; % add new vertices vertices2 = [vertices2 ; newPoints]; %#ok % create top faces of current strip for k = 1:iStrip-1 newFace = [topVertexInds(k) botVertexInds(k+1) topVertexInds(k+1)]; faces2 = [faces2; newFace]; %#ok end % create bottom faces of current strip for k = 1:iStrip newFace = [topVertexInds(k) botVertexInds(k) botVertexInds(k+1)]; faces2 = [faces2; newFace]; %#ok end % bottom vertices of current strip are top vertices of next strip topVertexInds = botVertexInds; end % for edge 2, keep vertex 2 of the current face as reference if edges(ie2, 1) ~= iv2 edge2NewVertexIndices = edge2NewVertexIndices(end:-1:1); end % consider new vertices together with extremities botVertexInds = [iv2 edge2NewVertexIndices iv3]; % create top faces for last strip for k = 1:n-1 newFace = [topVertexInds(k) botVertexInds(k+1) topVertexInds(k+1)]; faces2 = [faces2; newFace]; %#ok end % create bottom faces for last strip for k = 1:n newFace = [topVertexInds(k) botVertexInds(k) botVertexInds(k+1)]; faces2 = [faces2; newFace]; %#ok end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createDurerPolyhedron.m0000644000000000000000000000013213066736044022305 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createDurerPolyhedron.m0000644000175000017500000000766513066736044022477 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createDurerPolyhedron(varargin) %CREATEDURERPOLYHEDRON Create a mesh representing Durer's polyhedron % % [V, F] = createDurerPolyhedron % [V, E, F] = createDurerPolyhedron % Returns a mesh data structure that represents Durer's polyhedron shown % in "Melancholia". Vertices are stored in V as Nv-by-3 array of 3D % coordinates, faces are stored in Nf-by-1 cell array containing the % vertex indices of each face. % Several hypotheses exist on the exact geometry of the solid. The one % described in Mathworld (see references) is used here. % % Durer's polyhedron is generated from a centered unit cube. Several % transforms are applied succesively: % * Rotation around Oz by PI / 4 % * Rotation around Oy by asec(sqrt(3)) % * z-scaling by sqrt(1 + 3 / sqrt(5) ) % * truncation by two horizontal planes located at a distance of % (3 - sqrt(5)) / 2 from each azimutal vertex. % % Durer's polyhedron is composed of six pentagonal faces and 2 triangular % faces. Pentagonal faces have angles 126, 108, 72, 108, and 126 degrees. % triangular faces are equilateral. % % Example % % Display Durer's polyhedron % [v f] = createDurerPolyhedron; % figure; hold on; set(gcf, 'renderer', 'opengl'); % drawMesh(v, f, 'FaceColor', [.7 .7 .7]); % axis equal; axis([-1 1 -1 1 -1 1]); % view(3) % % See also % meshes3d, createCube, createOctahedron % % References % http://mathworld.wolfram.com/DuerersSolid.html % http://en.wikipedia.org/wiki/Dürer_graph % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2012-07-31, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. % start from a cube basis [v, f] = createCube; % recenter, rotate, and rescale v = v -.5; rot1 = createRotationOz(pi/4); rot2 = createRotationOy(asec(sqrt(3))); sca = createScaling3d([1 1 sqrt(1+3/sqrt(5))]); v = transformPoint3d(v, sca * rot2 * rot1); % compute the height of the two clipping planes d = (3 - sqrt(5)) / 2; zmax = max(v(:,3)); z1 = zmax - d; % clip by two horizontal planes plane1 = createPlane([0 0 z1], [0 0 1]); [v, f] = clipConvexPolyhedronHP(v, f, plane1); plane2 = createPlane([0 0 -z1], [0 0 -1]); [v, f] = clipConvexPolyhedronHP(v, f, plane2); % complete with edge information e = meshEdges(f); % format output varargout = formatMeshOutput(nargout, v, e, f); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/polyhedronSlice.m0000644000000000000000000000013213066736044021137 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/polyhedronSlice.m0000644000175000017500000000613613066736044021321 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function points = polyhedronSlice(nodes, faces, plane) %POLYHEDRONSLICE Intersect a convex polyhedron with a plane. % % SLICE = polyhedronSlice(NODES, FACES, PLANE) % NODES: a Nx3 array % FACES: either a cell array or a Nf*3 or Nf*4 array % PLANE: a plane representation [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]. % return the intersection polygon of the polyhedra with the plane, in the % form of a set of ordered points. % % Works only for convex polyhedra. % % Example % polyhedronSlice % % See also % polyhedra, clipConvexPolyhedronHP, intersectPlaneMesh % % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2007-09-18, using Matlab 7.4.0.287 (R2007a) % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. % if faces is a numeric array, convert it to cell array if isnumeric(faces) faces2 = cell(size(faces, 1), 1); for f = 1:length(faces2) faces2{f} = faces(f,:); end faces = faces2; else % ensure we have face with horizontal vectors... for f = 1:length(faces) face = faces{f}; faces{f} = face(:)'; end end % compute edges of the polyhedron inds = zeros(0, 2); for f = 1:length(faces) face = faces{f}'; inds = [inds ; sort([face face([2:end 1])], 2)]; %#ok end inds = unique(inds, 'rows'); edges = [nodes(inds(:,1), :) nodes(inds(:,2), :)]; % intersection of edges with plane points = intersectEdgePlane(edges, plane); points = points(sum(isfinite(points), 2)==3, :); if ~isempty(points) points = angleSort3d(points); end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/drawPolyhedron.m0000644000000000000000000000013213066736044020775 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/drawPolyhedron.m0000644000175000017500000001115313066736044021152 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = drawPolyhedron(nodes, faces, varargin) %DRAWPOLYHEDRON Draw polyhedron defined by vertices and faces % % drawPolyhedron(NODES, FACES) % Draws the polyhedron defined by vertices NODES and the faces FACES. % NODES is a NV-by-3 array containing coordinates of vertices, and FACES % is either a NF-by3 or NF-by-4 array containing indices of vertices of % the triangular or rectangular faces. % FACES can also be a cell array, in the content of each cell is an array % of indices to the nodes of the current face. Faces can have different % number of vertices. % % H = drawPolyhedron(...); % Also returns a handle to the created patche. % % Example: % [n f] = createSoccerBall; % drawPolyhedron(n, f); % % See also: % polyhedra, drawMesh, drawPolygon % % --------- % % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 10/02/2005. % % HISTORY % 07/11/2005 update doc. % 04/01/2007 typo % 18/01/2007 add support for 2D polyhedra ("nodes" is N-by-2 array), and % make 'cnodes' a list of points instead of a list of indices % 14/08/2007 add comment, add support for NaN in faces (complex polygons) % 14/09/2007 rename as drawPolyhedron % 16/10/2008 better support for colors % 27/07/2010 copy to 'drawMesh' %% Initialisations % process input arguments switch length(varargin) case 0 % default color is red varargin = {'facecolor', [1 0 0]}; case 1 % use argument as color for faces varargin = {'facecolor', varargin{1}}; otherwise % otherwise do nothing end % overwrites on current figure hold on; % if nodes are 2D points, add a z=0 coordinate if size(nodes, 2) == 2 nodes(1,3) = 0; end %% main loop : for each face if iscell(faces) % array FACES is a cell array h = zeros(length(faces(:)), 1); for f = 1:length(faces(:)) % get nodes of the cell face = faces{f}; if sum(isnan(face))~=0 % Special processing in case of multiple polygonal face. % each polygonal loop is separated by a NaN. % find indices of loops breaks inds = find(isnan(face)); % replace NaNs by index of first vertex of each polygon face(inds(2:end)) = face(inds(1:end-1)+1); face(inds(1)) = face(1); face(length(face)+1)= face(inds(end)+1); end % draw current face cnodes = nodes(face, :); h(f) = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]); end else % array FACES is a NC*NV indices array, with NV : number of vertices of % each face, and NC number of faces h = zeros(size(faces, 1), 1); for f = 1:size(faces, 1) % get nodes of the cell cnodes = nodes(faces(f,:)', :); h(f) = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]); end end % set up drawing options if ~isempty(varargin) set(h, varargin{:}); end % format output parameters if nargout > 0 varargout = {h}; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createTetrakaidecahedron.m0000644000000000000000000000013213066736044022741 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createTetrakaidecahedron.m0000644000175000017500000000671313066736044023124 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createTetrakaidecahedron() %CREATETETRAKAIDECAHEDRON Create a 3D mesh representing a tetrakaidecahedron % % [V, E, F] = createTetrakaidecahedron; % Create a mesh structure representing a tetrakaidecahedron, composed of % both square and hexagonal faces. Tetrakaidecahedron can be used to tile % the 3D Euclidean space. % % V is a 24-by-3 array with vertex coordinates, % E is a 36-by-2 array containing indices of neighbour vertices, % F is a 14-by-1 cell array containing vertex indices array of each face. % % [V, F] = createTetrakaidecahedron; % Returns only the vertices and the face vertex indices. % % MESH = createTetrakaidecahedron; % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % Example % [n, e, f] = createTetrakaidecahedron; % drawMesh(n, f); % % See also % meshes3d, drawMesh % --------- % author : David Legland % e-mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 10/02/2005. % % HISTORY % 04/01/2007: remove unused variables nodes = [... 1 0 2;0 1 2;-1 0 2;0 -1 2;... 2 0 1;0 2 1;-2 0 1;0 -2 1;... 2 1 0;1 2 0;-1 2 0;-2 1 0;-2 -1 0;-1 -2 0;1 -2 0;2 -1 0;... 2 0 -1;0 2 -1;-2 0 -1;0 -2 -1;... 1 0 -2;0 1 -2;-1 0 -2;0 -1 -2]; edges = [... 1 2;1 4;1 5;2 3;2 6;3 4;3 7;4 8;... 5 9;5 16;6 10;6 11;7 12;7 13;8 14;8 15;... 9 10;9 17;10 18;11 12;11 18;12 19;13 14;13 19;14 20;15 16;15 20;16 17;.... 17 21;18 22;19 23;20 24;21 22;21 24;22 23;23 24]; faces = {... [1 2 3 4], ... [1 4 8 15 16 5], [1 5 9 10 6 2], [2 6 11 12 7 3], [3 7 13 14 8 4],... [5 16 17 9], [6 10 18 11], [7 12 19 13], [8 14 20 15],... [9 17 21 22 18 10], [11 18 22 23 19 12], [13 19 23 24 20 14], [15 20 24 21 17 16], ... [21 24 23 22]}; faces = faces'; % format output varargout = formatMeshOutput(nargout, nodes, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/clipMeshVertices.m0000644000000000000000000000013213066736044021245 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/clipMeshVertices.m0000644000175000017500000000662613066736044021433 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [cVertices, cFaces] = clipMeshVertices(vertices, faces, box) %CLIPMESHVERTICES Clip vertices of a surfacic mesh and remove outer faces % % [V2, F2] = clipMeshVertices(V, F, B) % Clip a mesh represented by vertex array V and face array F, with the % box represented by B. The result is the set of vertices contained in % the box, and a new set of faces corresponding to original faces with % all vertices within the box. % % Example % [v, f] = createSoccerBall; % box = [-.8 2 -.8 2 -.8 2]; % [v2, f2] = clipMeshVertices(v, f, box); % figure; drawMesh(v2, f2, 'faceAlpha', .7); % view(3); axis equal; % % See also % meshes3d, clipPoints3d % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-04-07, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. % if input is given as a structure, parse fields if isstruct(vertices) box = faces; faces = vertices.faces; vertices = vertices.vertices; end % clip the vertices [cVertices, indVertices] = clipPoints3d(vertices, box); % create index array for face indices relabeling refInds = zeros(size(indVertices)); for i = 1:length(indVertices) refInds(indVertices(i)) = i; end % select the faces with all vertices within the box if isnumeric(faces) % Faces given as numeric array indFaces = sum(~ismember(faces, indVertices), 2) == 0; cFaces = refInds(faces(indFaces, :)); elseif iscell(faces) % Faces given as cell array nFaces = length(faces); indFaces = false(nFaces, 1); for i = 1:nFaces indFaces(i) = sum(~ismember(faces{i}, indVertices), 2) == 0; end cFaces = faces(indFaces, :); % re-label indices of face vertices (keeping horizontal index array) for i = 1:length(cFaces) cFaces{i} = refInds(cFaces{i})'; end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/smoothMesh.m0000644000000000000000000000013213066736044020122 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/smoothMesh.m0000644000175000017500000000721613066736044020304 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [v2, faces] = smoothMesh(vertices, faces, varargin) %SMOOTHMESH Smooth mesh by replacing each vertex by the average of its neighbors % % V2 = smoothMesh(V, F) % [V2, F2] = smoothMesh(V, F) % Performs smoothing of the values given in V, by using adjacency % information given in F. % V is a numeric array representing either vertex coordinate, or value % field associated to each vertex. F is an array of faces, given either % as a NF-by-3 or NF-by-4 numeric array, or as a cell array. % Artifact adjacencies are added if faces have more than 4 vertices. % % Example % [v f] = torusMesh([50 50 50 30 10 30 45]); % v = v + randn(size(v)); % [v2 f] = smoothMesh(v, f, 3); % figure; drawMesh(v2, f); % l = light; lighting gouraud % % See also % meshes3d, meshAdjacencyMatrix, triangulateFaces % % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2013-04-29, using Matlab 7.9.0.529 (R2009b) % Copyright 2013 INRA - Cepia Software Platform. % determine number of iterations nIter = 1; if ~isempty(varargin) nIter = varargin{1}; end % % ensure faces correspond to a triangulation % if iscell(faces) || size(faces, 2) > 3 % faces = triangulateFaces(faces); % end % compute adjacency matrix adj = meshAdjacencyMatrix(faces); % Add "self adjacencies" nv = size(adj, 1); adj = adj + speye(nv); % weight each vertex by the number of its neighbors w = spdiags(full(sum(adj, 2).^(-1)), 0, nv, nv); adj = w * adj; % do averaging to smooth the field v2 = vertices; for k = 1:nIter v2 = adj * v2; end %% Old version % % Compute vertex adjacencies % edges = computeMeshEdges(faces); % v2 = zeros(size(vertices)); % % % apply several smoothing % for iter = 1:nIter % % % replace the coords of each vertex by the average coordinate in the % % neighborhood % for i = 1:size(vertices, 1) % edgeInds = sum(edges == i, 2) > 0; % neighInds = unique(edges(edgeInds, :)); % v2(i, :) = mean(vertices(neighInds, :)); % end % % % update for next iteration % vertices = v2; % end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/polyhedronCentroid.m0000644000000000000000000000013213066736044021647 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/polyhedronCentroid.m0000644000175000017500000000646713066736044022040 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function centroid = polyhedronCentroid(vertices, faces) %#ok %POLYHEDRONCENTROID Compute the centroid of a 3D convex polyhedron % % CENTRO = polyhedronCentroid(V, F) % Computes the centroid (center of mass) of the polyhedron defined by % vertices V and faces F. % The polyhedron is assumed to be convex. % % Example % % Creates a polyhedron centered on origin, and add an arbitrary % % translation % [v, f] = createDodecahedron; % v2 = bsxfun(@plus, v, [3 4 5]); % % computes the centroid, that should equal the translation vector % centroid = polyhedronCentroid(v2, f) % centroid = % 3.0000 4.0000 5.0000 % % % See also % meshes3d, meshVolume, meshSurfaceArea, polyhedronMeanBreadth % % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2012-04-05, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. % 2015.11.13 use delaunayTriangulation instead of delaunayn (strange bug % with icosahedron...) % compute set of elementary tetrahedra DT = delaunayTriangulation(vertices); T = DT.ConnectivityList; % number of tetrahedra nT = size(T, 1); % initialize result centroid = zeros(1, 3); vt = 0; % Compute the centroid and the volume of each tetrahedron for i = 1:nT % coordinates of tetrahedron vertices tetra = vertices(T(i, :), :); % centroid is the average of vertices. centi = mean(tetra); % compute volume of tetrahedron vol = det(tetra(1:3,:) - tetra([4 4 4],:)) / 6; % add weighted centroid of current tetraedron centroid = centroid + centi * vol; % compute the sum of tetraedra volumes vt = vt + vol; end % compute by sum of tetrahedron volumes centroid = centroid / vt; geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/drawFaceNormals.m0000644000000000000000000000013213066736044021044 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/drawFaceNormals.m0000644000175000017500000000516313066736044021225 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = drawFaceNormals(varargin) %DRAWFACENORMALS Draw normal vector of each face in a mesh % % drawFaceNormals(V, E, F) % Compute and draw the face normals of the mesh defined by vertices V, % edges E and faces F. See meshes3d for format of each argument. % % H = drawFaceNormals(...) % Return handle array to the created objects. % % Example % % draw face normals of a cube % drawMesh(v, f) % axis([-1 2 -1 2 -1 2]); % hold on % drawFaceNormals(v, e, f) % % See also % meshes3d, drawMesh, drawVector3d, quiver3 % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-06, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % extract vertices and faces [vertices, faces] = parseMeshData(varargin{:}); % compute vector data c = faceCentroids(vertices, faces); n = faceNormal(vertices, faces); % display an arrow for each normal h = quiver3(c(:,1), c(:,2), c(:,3), n(:,1), n(:,2), n(:,3)); % format output if nargout > 0 varargout{1} = h; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshDihedralAngles.m0000644000000000000000000000013213066736044021517 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshDihedralAngles.m0000644000175000017500000000646213066736044021703 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function alpha = meshDihedralAngles(vertices, edges, faces) %MESHDIHEDRALANGLES Dihedral at edges of a polyhedal mesh % % ALPHA = meshDihedralAngles(V, E, F) % where V, E and F represent vertices, edges and faces of a mesh, % computes the dihedral angle between the two adjacent faces of each edge % in the mesh. ALPHA is a column array with as many rows as the number of % edges. The i-th element of ALPHA corresponds to the i-th edge. % % Note: the function assumes that the faces are correctly oriented. The % face vertices should be indexed counter-clockwise when considering the % supporting plane of the face, with the outer normal oriented outwards % of the mesh. % % Example % [v e f] = createCube; % rad2deg(meshDihedralAngles(v, e, f)) % ans = % 90 % 90 % 90 % 90 % 90 % 90 % 90 % 90 % 90 % 90 % 90 % 90 % % See also % meshes3d, polyhedronMeanBreadth, dihedralAngle, meshEdgeFaces % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % compute normal of each face normals = faceNormal(vertices, faces); % indices of faces adjacent to each edge edgeFaces = meshEdgeFaces(vertices, edges, faces); % allocate memory for resulting angles Ne = size(edges, 1); alpha = zeros(Ne, 1); % iterate over edges for i = 1:Ne % indices of adjacent faces indFace1 = edgeFaces(i, 1); indFace2 = edgeFaces(i, 2); % normal vector of adjacent faces normal1 = normals(indFace1, :); normal2 = normals(indFace2, :); % compute dihedral angle of two vectors alpha(i) = vectorAngle3d(normal1, normal2); end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/polyhedronNormalAngle.m0000644000000000000000000000013213066736044022277 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/polyhedronNormalAngle.m0000644000175000017500000001025413066736044022455 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function theta = polyhedronNormalAngle(varargin) %POLYHEDRONNORMALANGLE Compute normal angle at a vertex of a 3D polyhedron % % THETA = polyhedraNormalAngle(NODES, EDGES, FACES, IND); % THETA = polyhedraNormalAngle(NODES, FACES, IND); % where NODES is a set of 3D points, and FACES a set of faces, whose % elements are indices to NODES array, compute the normal angle at the % vertex whose index is given by IND. % % THETA = polyhedraNormalAngle(GRAPH, IND); % Uses a graph structure. GRAPH should contain at least fields : 'nodes' % and 'faces'. % % Example : % % create a simple (irregular) tetrahedra % nodes = [0 0 0;1 0 0;0 1 0;0 0 1]; % faces = [1 2 3;1 2 4;1 3 4;2 3 4]; % % compute normal angle at each vertex % theta = polyhedronNormalAngle(nodes, faces, 1:size(nodes, 1)); % % sum of normal angles should be equal to 4*pi : % sum(theta) % % % TODO works only for polyhedra with convex faces ! ! ! % % See also % polyhedra, polygon3dNormalAngle % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2005-11-30 % Copyright 2005 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). if length(varargin)==4 nodes = varargin{1}; faces = varargin{3}; ind = varargin{4}; elseif length(varargin)==3 nodes = varargin{1}; faces = varargin{2}; ind = varargin{3}; elseif length(varargin)==2 graph = varargin{1}; nodes = graph.nodes; faces = graph.faces; ind = varargin{2}; else error('wrong number of arguments'); end % number of angles to compute na = length(ind); theta = zeros(na, 1); for i=1:na thetaf = []; % find faces containing given vertex, % and compute normal angle at each face containing vertex if iscell(faces) for j=1:length(faces) if ismember(ind(i), faces{j}) % create 3D polygon face = nodes(faces{j}, :); % index of point in polygon indp = find(faces{j}==i); % compute normal angle of vertex thetaf = [thetaf polygon3dNormalAngle(face, indp)]; %#ok end end else indf = find(sum(ismember(faces, ind(i)), 2)); thetaf = zeros(length(indf), 1); for j=1:length(indf) ind2 = faces(indf(j), :); face = nodes(ind2, :); indp = find(ind2==ind(i)); thetaf(j) = pi - polygon3dNormalAngle(face, indp); end end % compute normal angle of polyhedron, by use of angle defect formula theta(i) = 2*pi - sum(thetaf); end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshFaceAdjacency.m0000644000000000000000000000013213066736044021311 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshFaceAdjacency.m0000644000175000017500000000520613066736044021470 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function adjList = meshFaceAdjacency(vertices, edges, faces) %MESHFACEADJACENCY Compute adjacency list of face around each face % % % Example % % Create a sample 3D mesh % [v, e, f] = createDodecahedron; % adjList = meshFaceAdjacency(v, e, f); % figure; hold on; axis equal; view([100 40]); % drawMesh(v, f); % % draw sample face in a different color % drawMesh(v, f(1, :), 'faceColor', 'b'); % % draw the neighbors of a sample face % drawMesh(v, f(adjList{1}, :), 'faceColor', 'g') % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. edgeFaceList = meshEdgeFaces(vertices, edges, faces); % allocate memory for adjacency list nFaces = max(edgeFaceList(:)); adjList = cell(1, nFaces); % iterate over edges to populate adjacency list for iEdge = 1:size(edgeFaceList) f1 = edgeFaceList(iEdge, 1); f2 = edgeFaceList(iEdge, 2); adjList{f1} = [adjList{f1} f2]; adjList{f2} = [adjList{f2} f1]; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/clipConvexPolyhedronHP.m0000644000000000000000000000013213066736044022402 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/clipConvexPolyhedronHP.m0000644000175000017500000001324413066736044022562 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [nodes2, faces2] = clipConvexPolyhedronHP(nodes, faces, plane) %CLIPCONVEXPOLYHEDRONHP Clip a convex polyhedron by a plane % % [NODES2, FACES2] = clipConvexPolyhedronHP(NODES, FACES, PLANE) % % return the new (convex) polyhedron whose vertices are 'below' the % specified plane, and with faces clipped accordingly. NODES2 contains % clipped vertices and new created vertices, FACES2 contains references % to NODES2 vertices. % % Example % [N E F] = createCube; % P = createPlane([.5 .5 .5], [1 1 1]); % [N2 F2] = clipConvexPolyhedronHP(N, F, P); % drawPolyhedra(N2, F2); % % See also % meshes3d, polyhedra, planes3d % % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2007-09-14, using Matlab 7.4.0.287 (R2007a) % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. %% Preprocessing % used for identifying identical vertices tol = 1e-10; % if faces is a numeric array, convert it to cell array if isnumeric(faces) faces2 = cell(size(faces, 1), 1); for f = 1:length(faces2) faces2{f} = faces(f,:); end faces = faces2; end % find vertices below the plane b = isBelowPlane(nodes, plane); % initialize results Nn = size(nodes, 1); nodes2 = zeros(0, 3); % list of new nodes faces2 = faces; % list of new faces. Start with initial list, and remove some of them %% Main iteration on faces % iterate on each face, and test if either: % - all points below plane -> keep all face % - all points up plane -> remove face % - both -> clip the polygon keep = true(length(faces), 1); for f = 1:length(faces) % current face face = faces{f}; bf = b(face); % face totally above plane if sum(bf) == 0 keep(f) = false; continue; end % face totally below plane if sum(bf == 1) == length(bf) continue; end % clip polygon formed by face poly = nodes(face, :); clipped = clipConvexPolygon3dHP(poly, plane); % identify indices of polygon vertices inds = zeros(1, size(clipped, 1)); faceb = face(bf==1); % indices of vertices still in clipped face [minDists, I] = minDistancePoints(nodes(faceb,:), clipped); %#ok for i = 1:length(I) inds(I(i)) = faceb(i); end % indices of new points in clipped polygon indNews = find(inds == 0); if size(nodes2, 1) < 2 nodes2 = [nodes2; clipped(indNews, :)]; %#ok inds(indNews(1)) = Nn + 1; inds(indNews(2)) = Nn + 2; faces2{f} = inds; continue; end % distances from new vertices to already added vertices [minDists, I] = minDistancePoints(clipped(indNews, :), nodes2); % compute index of first vertex if minDists(1) < tol inds(indNews(1)) = Nn + I(1); else nodes2 = [nodes2; clipped(indNews(1), :)]; %#ok inds(indNews(1)) = Nn + size(nodes2, 1); end % compute index of second vertex if minDists(2) < tol inds(indNews(2)) = Nn + I(2); else nodes2 = [nodes2; clipped(indNews(2), :)]; %#ok inds(indNews(2)) = Nn + size(nodes2, 1); end % stores the modified face faces2{f} = inds; end %% Postprocessing % creates a new face formed by the added nodes [sortedNodes, I] = angleSort3d(nodes2); % compute normal vector of new face, and reverse order if face points in % the opposite direction as plane normal newFaceNormal = faceNormal(sortedNodes, 1:length(sortedNodes)); if dot(newFaceNormal, planeNormal(plane)) < 0 I(2:end) = I(end:-1:2); end % compute vertex indices of new face newFace = I' + Nn; % remove faces outside plane and add the new face faces2 = {faces2{keep}, newFace}; % remove clipped nodes, and add new nodes to list of nodes N2 = size(nodes2, 1); nodes2 = [nodes(b, :); nodes2]; % new nodes are inside half-space by definition b = [b; ones(N2, 1)]; % create look up table between old indices and new indices inds = zeros(size(nodes2, 1), 1); indb = find(b); for i = 1:length(indb) inds(indb(i)) = i; end % update indices of faces for f = 1:length(faces2) face = faces2{f}; faces2{f} = inds(face)'; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshFaceNumber.m0000644000000000000000000000013213066736044020660 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshFaceNumber.m0000644000175000017500000000471213066736044021040 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function nFaces = meshFaceNumber(varargin) %MESHFACENUMBER Returns the number of faces in this mesh % % NF = meshFaceNumber(V, F) % NF = meshFaceNumber(V, E, F) % NF = meshFaceNumber(MESH) % Returns the number of faces in the given mesh. As the face array may be % represented either as numeric array or as cell array of indices, this % function is a convenient way to get the number of faces independanlty % of the mesh representation. % % Example % [v f] = createCube; % meshFaceNumber(v, f) % ans = % 6 % % See also % meshes3d % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2013-08-22, using Matlab 7.9.0.529 (R2009b) % Copyright 2013 INRA - Cepia Software Platform. [vertices, faces] = parseMeshData(varargin{:}); %#ok if iscell(faces) nFaces = length(faces); else nFaces = size(faces, 1); end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/faceNormal.m0000644000000000000000000000013213066736044020043 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/faceNormal.m0000644000175000017500000000671613066736044020231 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function normals = faceNormal(nodes, faces) %FACENORMAL Compute normal vector of faces in a 3D mesh % % NORMALS = faceNormal(VERTICES, FACES) % VERTICES is a set of 3D points (as a N-by-3 array), and FACES is either % a N-by-3 index array or a cell array of indices. The function computes % the normal vector of each face. % The orientation of the normal is defined by the sign of cross product % between vectors joining vertices 1 to 2 and 1 to 3. % % % Example % [v e f] = createIcosahedron; % normals1 = faceNormal(v, f); % centros1 = faceCentroids(v, f); % figure; drawMesh(v, f); % hold on; axis equal; view(3); % drawVector3d(centros1, normals1); % % pts = rand(50, 3); % hull = minConvexHull(pts); % normals2 = faceNormal(pts, hull); % % See also % meshes3d, drawMesh, convhull, convhulln, drawVector3d % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2006-07-05 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). if isnumeric(faces) % compute vector of first edges v1 = nodes(faces(:,2),1:3) - nodes(faces(:,1),1:3); v2 = nodes(faces(:,3),1:3) - nodes(faces(:,1),1:3); % % normalize vectors % v1 = normalizeVector3d(v1); % v2 = normalizeVector3d(v2); % compute normals using cross product (nodes have same size) normals = normalizeVector3d(cross(v1, v2, 2)); else % initialize empty array normals = zeros(length(faces), 3); for i = 1:length(faces) face = faces{i}; % compute vector of first edges v1 = nodes(face(2),1:3) - nodes(face(1),1:3); v2 = nodes(face(3),1:3) - nodes(face(1),1:3); % % normalize vectors % v1 = normalizeVector3d(v1); % v2 = normalizeVector3d(v2); % compute normals using cross product normals(i, :) = normalizeVector3d(cross(v1, v2, 2)); end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshAdjacencyMatrix.m0000644000000000000000000000013213066736044021717 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshAdjacencyMatrix.m0000644000175000017500000000575713066736044022111 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function adj = meshAdjacencyMatrix(faces, varargin) %MESHADJACENCYMATRIX Compute adjacency matrix of a mesh from set of faces % % ADJMAT = meshAdjacencyMatrix(FACES) % Returns a sparse NV-by-NV matrix (NV being the maximum vertex index) % containing vertex adjacency of the mesh represented by FACES. % FACES is either a NF-by-3, a NF-by-4 index array, or a Nf-by-1 cell % array. % % Example % [v f] = createCube; % adj = meshAdjacencyMatrix(f); % % See also % meshes3d, triangulateFaces, smoothMesh % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2013-04-30, using Matlab 7.9.0.529 (R2009b) % Copyright 2013 INRA - Cepia Software Platform. % Ensures faces is a N-by-3 or N-by-4 array if iscell(faces) || (isnumeric(faces) && size(faces, 2) > 4) faces = triangulateFaces(faces); end % populate a sparse matrix if size(faces, 2) == 3 adj = sparse(... [faces(:,1); faces(:,1); faces(:,2); faces(:,2); faces(:,3); faces(:,3)], ... [faces(:,3); faces(:,2); faces(:,1); faces(:,3); faces(:,2); faces(:,1)], ... 1.0); elseif size(faces, 2) == 4 adj = sparse(... [faces(:,1); faces(:,1); faces(:,2); faces(:,2); faces(:,3); faces(:,3); faces(:,4); faces(:,4)], ... [faces(:,4); faces(:,2); faces(:,1); faces(:,3); faces(:,2); faces(:,4); faces(:,3); faces(:,1)], ... 1.0); end % remove double adjacencies adj = min(adj, 1); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/mergeCoplanarFaces.m0000644000000000000000000000013213066736044021515 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/mergeCoplanarFaces.m0000644000175000017500000002670513066736044021703 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = mergeCoplanarFaces(nodes, varargin) %MERGECOPLANARFACES Merge coplanar faces of a polyhedral mesh % % [NODES FACES] = mergeCoplanarFaces(NODES, FACES) % [NODES EDGES FACES] = mergeCoplanarFaces(NODES, EDGES, FACES) % NODES is a set of 3D points (as a nNodes-by-3 array), % and FACES is one of: % - a nFaces-by-X array containing vertex indices of each face, with each % face having the same number of vertices, % - a nFaces-by-1 cell array, each cell containing indices of a face. % The function groups faces which are coplanar and contiguous, resulting % in a "lighter" mesh. This can be useful for visualizing binary 3D % images for example. % % FACES = mergeCoplanarFaces(..., PRECISION) % Adjust the threshold for deciding if two faces are coplanar or % parallel. Default value is 1e-5. % % Example % [v e iFace] = createCube; % figure; drawMesh(v, iFace); view(3); axis equal; % [v2 f2] = mergeCoplanarFaces(v, iFace); % figure; drawMesh(v, f2); % view(3); axis equal; view(3); % % See also % meshes3d, drawMesh, minConvexHull, triangulateFaces % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2006-07-05 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). % 20/07/2006 add tolerance for coplanarity test % 21/08/2006 fix small bug due to difference of methods to test % coplanaritity, sometimes resulting in 3 points of a face not coplanar ! % Also add control on precision % 14/08/2007 rename minConvexHull->meshReduce, and extend to non convex % shapes % 2011-01-14 code clean up % 2013-02-22 rename from meshReduce to mergeCoplanarFaces %% Process input arguments % set up precision acc = 1e-5; if ~isempty(varargin) var = varargin{end}; if length(var) == 1 acc = var; varargin(end) = []; end end % extract faces and edges if length(varargin) == 1 faces = varargin{1}; else faces = varargin{2}; end %% Initialisations % number of faces nNodes = size(nodes, 1); nFaces = size(faces, 1); % compute number of vertices of each face Fn = ones(nFaces, 1) * size(faces, 2); % compute normal of each faces normals = faceNormal(nodes, faces); % initialize empty faces and edges faces2 = cell(0, 1); edges2 = zeros(0, 2); % Processing flag for each face % 1: face to process, 0: already processed % in the beginning, every triangle face need to be processed flag = ones(nFaces, 1); %% Main iteration % iterate on each face for iFace = 1:nFaces % check if face was already performed if ~flag(iFace) continue; end % indices of faces with same normal % ind = find(abs(vectorNorm3d(cross(repmat(normals(iFace, :), [nFaces 1]), normals))) planeEdges2 = reshape(J, size(planeEdges)); % The set of coplanar faces may not necessarily form a single connected % component. The following computes label of each connected component. component = grLabel(nodes(planeNodes, :), planeEdges2); % compute degree (number of adjacent faces) of each edge. Npe = size(planeEdges, 1); edgeDegrees = zeros(Npe, 1); for i = 1:length(ind2) face = faces(ind2(i), :); faceEdges = sort([face' face([2:end 1])'], 2); for j = 1:size(faceEdges, 1) indEdge = find(sum(ismember(planeEdges, faceEdges(j,:)),2)==2); edgeDegrees(indEdge) = edgeDegrees(indEdge)+1; end end % extract unique edges and nodes of the plane planeEdges = planeEdges(edgeDegrees==1, :); planeEdges2 = planeEdges2(edgeDegrees==1, :); % find connected component of each edge planeEdgesComp = zeros(size(planeEdges, 1), 1); for iEdge = 1:size(planeEdges, 1) planeEdgesComp(iEdge) = component(planeEdges2(iEdge, 1)); end % iterate on connected faces for c = 1:max(component) % convert to chains of nodes loops = graph2Contours(nodes, planeEdges(planeEdgesComp==c, :)); % add a simple Polygon for each loop facePolygon = loops{1}; for l = 2:length(loops) facePolygon = [facePolygon, NaN, loops{l}]; %#ok end faces2{length(faces2)+1, 1} = facePolygon; % also add news edges edges2 = unique([edges2; planeEdges], 'rows'); end % mark processed faces flag(ind2) = 0; end %% Additional processing on nodes % select only nodes which appear in at least one edge indNodes = unique(edges2(:)); % for each node, compute index of corresponding new node (or 0 if dropped) refNodes = zeros(nNodes, 1); for i = 1:length(indNodes) refNodes(indNodes(i)) = i; end % changes indices of nodes in edges2 array for i = 1:length(edges2(:)) edges2(i) = refNodes(edges2(i)); end % changes indices of nodes in faces2 array for iFace = 1:length(faces2) face = faces2{iFace}; for i = 1:length(face) if ~isnan(face(i)) face(i) = refNodes(face(i)); end end faces2{iFace} = face; end % keep only boundary nodes nodes2 = nodes(indNodes, :); %% Process output arguments if nargout == 1 varargout{1} = faces2; elseif nargout == 2 varargout{1} = nodes2; varargout{2} = faces2; elseif nargout == 3 varargout{1} = nodes2; varargout{2} = edges2; varargout{3} = faces2; end function labels = grLabel(nodes, edges) %GRLABEL associate a label to each connected component of the graph % LABELS = grLabel(NODES, EDGES) % Returns an array with as many rows as the array NODES, containing index % number of each connected component of the graph. If the graph is % totally connected, returns an array of 1. % % Example % nodes = rand(6, 2); % edges = [1 2;1 3;4 6]; % labels = grLabel(nodes, edges); % labels = % 1 % 1 % 1 % 2 % 3 % 2 % % See also % getNeighbourNodes % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2007-08-14, using Matlab 7.4.0.287 (R2007a) % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. % init nNodes = size(nodes, 1); labels = (1:nNodes)'; % iteration modif = true; while modif modif = false; for i=1:nNodes neigh = getNeighbourNodes(i, edges); neighLabels = labels([i;neigh]); % check for a modification if length(unique(neighLabels))>1 modif = true; end % put new labels labels(ismember(labels, neighLabels)) = min(neighLabels); end end % change to have fewer labels labels2 = unique(labels); for i = 1:length(labels2) labels(labels==labels2(i)) = i; end function nodes2 = getNeighbourNodes(node, edges) %GETNEIGHBOURNODES find nodes adjacent to a given node % % NEIGHS = getNeighbourNodes(NODE, EDGES) % NODE: index of the node % EDGES: the complete edges list % NEIGHS: the nodes adjacent to the given node. % % NODE can also be a vector of node indices, in this case the result is % the set of neighbors of any input node. % % % ----- % % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 16/08/2004. % % HISTORY % 10/02/2004 documentation % 13/07/2004 faster algorithm % 03/10/2007 can specify several input nodes [i, j] = find(ismember(edges, node)); %#ok nodes2 = edges(i,1:2); nodes2 = unique(nodes2(:)); nodes2 = sort(nodes2(~ismember(nodes2, node))); function curves = graph2Contours(nodes, edges) %#ok %GRAPH2CONTOURS convert a graph to a set of contour curves % % CONTOURS = GRAPH2CONTOURS(NODES, EDGES) % NODES, EDGES is a graph representation (type "help graph" for details) % The algorithm assume every node has degree 2, and the set of edges % forms only closed loops. The result is a list of indices arrays, each % array containing consecutive point indices of a contour. % % To transform contours into drawable curves, please use : % CURVES{i} = NODES(CONTOURS{i}, :); % % % NOTE : contours are not oriented. To manage contour orientation, edges % also need to be oriented. So we must precise generation of edges. % % ----- % % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 05/08/2004. % curves = {}; c = 0; while size(edges,1)>0 % find first point of the curve n0 = edges(1,1); curve = n0; % second point of the curve n = edges(1,2); e = 1; while true % add current point to the curve curve = [curve n]; %#ok % remove current edge from the list edges = edges((1:size(edges,1))~=e,:); % find index of edge containing reference to current node e = find(edges(:,1)==n | edges(:,2)==n); e = e(1); % get index of next current node % (this is the other node of the current edge) if edges(e,1)==n n = edges(e,2); else n = edges(e,1); end % if node is same as start node, loop is closed, and we stop % node iteration. if n==n0 break; end end % remove the last edge of the curve from edge list. edges = edges((1:size(edges,1))~=e,:); % add the current curve to the list, and start a new curve c = c+1; curves{c} = curve; %#ok end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/drawMesh.m0000644000000000000000000000013213066736044017546 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/drawMesh.m0000644000175000017500000001554413066736044017733 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawMesh (@var{vertices}, @var{faces}) ## @deftypefnx {Function File} {@var{h} =} drawMesh (@var{mesh}) ## @deftypefnx {Function File} {@var{h} =} drawMesh (@dots{}, @var{color}) ## @deftypefnx {Function File} {@var{h} =} drawMesh (@dots{}, @var{name},@var{value}) ## Draw a 3D mesh defined by vertices and faces ## ## drawMesh(VERTICES, FACES) ## Draws the 3D mesh defined by vertices VERTICES and the faces FACES. ## vertices is a [NVx3] array containing coordinates of vertices, and FACES ## is either a [NFx3] or [NFx4] array containing indices of vertices of ## the triangular or rectangular faces. ## FACES can also be a cell array, in the content of each cell is an array ## of indices to the vertices of the current face. Faces can have different ## number of vertices. ## ## drawMesh(MESH) ## Where mesh is a structure with fields 'vertices' and 'faces', draws the ## given mesh. ## ## drawMesh(..., COLOR) ## Use the specified color to render the mesh faces. ## ## drawMesh(..., NAME, VALUE) ## Use one or several pairs of parameter name/value to specify drawing ## options. Options are the same as the 'patch' function. ## ## ## H = drawMesh(...); ## Also returns a handle to the created patch. ## ## WARNING: This function doesn't work with gnuplot (as of version 4.2) ## ## Example: ## @example ## [v f] = createSoccerBall; ## drawMesh(v, f); ## @end example ## ## @seealso{polyhedra, meshes3d, patch} ## @end deftypefn function varargout = drawMesh(vertices, faces, varargin) ## Initialisations # Check if the input is a mesh structure if isstruct(vertices) # refresh options if nargin > 1 varargin = [{faces} varargin]; end # extract data to display faces = vertices.faces; vertices = vertices.vertices; end # process input arguments switch length(varargin) case 0 # default color is red varargin = {'facecolor', [1 0 0]}; case 1 # use argument as color for faces varargin = {'facecolor', varargin{1}}; otherwise # otherwise keep varargin unchanged end # overwrites on current figure state = ishold(gca); hold on; # if vertices are 2D points, add a z=0 coordinate if size(vertices, 2)==2 vertices(1,3)=0; end ## Use different processing depending on the type of faces if isnumeric(faces) # array FACES is a NC*NV indices array, with NV : number of vertices of # each face, and NC number of faces h = patch('vertices', vertices, 'faces', faces, varargin{:}); elseif iscell(faces) # array FACES is a cell array h = zeros(length(faces(:)), 1); for f=1:length(faces(:)) # get vertices of the cell face = faces{f}; # Special processing in case of multiple polygonal face: # each polygonal loop is separated by a NaN. if sum(isnan(face))~=0 # find indices of loops breaks inds = find(isnan(face)); # replace NaNs by index of first vertex of each polygon face(inds(2:end)) = face(inds(1:end-1)+1); face(inds(1)) = face(1); face(length(face)+1)= face(inds(end)+1); end # draw current face cnodes = vertices(face, :); h(f) = patch(cnodes(:, 1), cnodes(:, 2), cnodes(:, 3), [1 0 0]); end # set up drawing options set(h, varargin{:}); else error('second argument must be a face array'); end if ~state hold off end ## Process output arguments # format output parameters if nargout>0 varargout{1}=h; end endfunction %!demo %! [v f] = createCubeOctahedron; %! drawMesh(v, f); %! view (3) geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/removeMeshVertices.m0000644000000000000000000000013213066736044021613 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/removeMeshVertices.m0000644000175000017500000000661113066736044021773 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = removeMeshVertices(vertices, faces, indsToRemove, varargin) %REMOVEMESHVERTICES Remove vertices and associated faces from a mesh % % [V2, F2] = removeMeshVertices(VERTS, FACES, VERTINDS) % Removes the vertices specified by the vertex indices VERTINDS, and % remove the faces containing one of the removed vertices. % % % Example % % remove some vertices from a soccerball polyhedron % [v, f] = createSoccerBall; % plane = createPlane([.6 0 0], [1 0 0]); % indAbove = find(~isBelowPlane(v, plane)); % [v2, f2] = removeMeshVertices(v, f, indAbove); % drawMesh(v2, f2); % axis equal; hold on; % % See also % meshes3d, trimMesh % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2016-02-03, using Matlab 8.6.0.267246 (R2015b) % Copyright 2016 INRA - Cepia Software Platform. % create array of indices to keep nVertices = size(vertices, 1); newInds = (1:nVertices)'; newInds(indsToRemove) = []; % create new vertex array vertices2 = vertices(newInds, :); % compute map from old indices to new indices oldNewMap = zeros(nVertices, 1); for iIndex = 1:size(newInds, 1) oldNewMap(newInds(iIndex)) = iIndex; end % change labels of vertices referenced by faces if isnumeric(faces) faces2 = oldNewMap(faces); % keep only faces with valid vertices faces2 = faces2(sum(faces2 == 0, 2) == 0, :); elseif iscell(faces) faces2 = cell(1, length(faces)); for iFace = 1:length(faces) newFace = oldNewMap(faces{iFace}); % add the new face only if all vertices are valid if ~any(newFace == 0) faces2{iFace} = newFace; end end % remove empty faces faces2 = faces2(~cellfun(@isempty, faces2)); end % format output arguments varargout = formatMeshOutput(nargout, vertices2, faces2); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/surfToMesh.m0000644000000000000000000000013213066736044020073 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/surfToMesh.m0000644000175000017500000001012013066736044020241 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = surfToMesh(x, y, varargin) %SURFTOMESH Convert surface grids into face-vertex mesh % % [V F] = surfToMesh(X, Y) % [V F] = surfToMesh(X, Y, Z) % Converts the surface grid given by two or three coordinate arrays into % a face-vertex quad mesh. % % Example % % transform a surface into a mesh % [X,Y] = meshgrid(-2:.2:2, -2:.2:2); % Z = X .* exp(-X.^2 - Y.^2); % [V F] = surfToMesh(X, Y, Z); % figure; % drawMesh(V, F); view(3); % % % Transform surface of a cylinder as a mesh % [x y z] = cylinder(5*ones(1, 10)); % [v f] = surfToMesh(x, y, z, 'xPeriodic', true); % figure; % drawMesh(v, f); % view(3); axis equal; % % See also % meshes3d, meshgrid, drawMesh, torusMesh, sphereMesh % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. %% Parse inputs % check if z-value is present if ~isempty(varargin) && isnumeric(varargin{1}) z = varargin{1}; varargin(1) = []; end % default periodicities xPeriodic = false; yPeriodic = false; % parse input options while length(varargin) > 1 paramName = lower(varargin{1}); switch paramName case 'xperiodic' xPeriodic = varargin{2}; case 'yperiodic' yPeriodic = varargin{2}; otherwise error(['Unknown parameter name: ' paramName]); end varargin(1:2) = []; end %% Compute vertex indices % size along each direction (arrays are (y,x)-indexed) n1 = size(x, 1); n2 = size(x, 2); % in case of periodicity, the last vertex of the grid is drop (it is % assumed to be the same as the first one) if xPeriodic n2 = n2 - 1; end if yPeriodic n1 = n1 - 1; end % new size of vertex grid dim = [n1 n2]; nv = n1 * n2; %% Create vertex array % eventually remove boundary vertices x = x(1:n1, 1:n2); y = y(1:n1, 1:n2); % create vertex array if ~exist('z', 'var') vertices = [x(:) y(:)]; else z = z(1:n1, 1:n2); vertices = [x(:) y(:) z(:)]; end %% Create face array % vertex indices in grid inds = reshape(1:nv, dim); if xPeriodic inds = inds(:, [1:end 1]); end if yPeriodic inds = inds([1:end 1], :); end % vertex indices for each face v1 = inds(1:end-1, 1:end-1); v2 = inds(1:end-1, 2:end); v3 = inds(2:end, 2:end); v4 = inds(2:end, 1:end-1); % concatenate indices faces = [v1(:) v2(:) v3(:) v4(:)]; %% format output varargout = formatMeshOutput(nargout, vertices, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshEdgeFaces.m0000644000000000000000000000013213066736044020457 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshEdgeFaces.m0000644000175000017500000001151113066736044020632 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function edgeFaces = meshEdgeFaces(vertices, edges, faces) %#ok %MESHEDGEFACES Compute index of faces adjacent to each edge of a mesh % % EF = meshEdgeFaces(V, E, F) % Compute index array of faces adjacent to each edge of a mesh. % V, E and F define the mesh: V is vertex array, E contains vertex % indices of edge extremities, and F contains vertex indices of each % face, either as a numerical array or as a cell array. % The result EF has as many rows as the number of edges, and two column. % The first column contains index of faces located on the left of the % corresponding edge, whereas the second column contains index of the % face located on the right. Some indices may be 0 if the mesh is not % 'closed'. % % Note: a faster version is available for triangular meshes. % % Example % meshEdgeFaces % % See also % meshes3d, trimeshEdgeFaces, meshDihedralAngles, polyhedronMeanBreadth % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. Ne = size(edges, 1); % indices of faces adjacent to each edge edgeFaces = zeros(Ne, 2); % different method for extracting current face depending if faces are % stored as index 2D array or as cell array of 1D arrays. if isnumeric(faces) Nf = size(faces, 1); for i = 1:Nf face = faces(i, :); processFace(face, i) end elseif iscell(faces) Nf = length(faces); for i = 1:Nf face = faces{i}; processFace(face, i) end end function processFace(face, indFace) % iterate on face edges for j = 1:length(face) % build edge: array of vertices j2 = mod(j, length(face)) + 1; % do not process edges with same vertices if face(j) == face(j2) continue; end % vertex indices of current edge currentEdge = [face(j) face(j2)]; % find index of current edge, assuming face is left-located b1 = ismember(edges, currentEdge, 'rows'); indEdge = find(b1); if ~isempty(indEdge) if edgeFaces(indEdge, 1) ~= 0 error('meshes3d:IllegalTopology', ... 'Two faces were found on left side of edge %d ', indEdge); end edgeFaces(indEdge, 1) = indFace; continue; end % otherwise, assume the face is right-located b2 = ismember(edges, currentEdge([2 1]), 'rows'); indEdge = find(b2); if ~isempty(indEdge) if edgeFaces(indEdge, 2) ~= 0 error('meshes3d:IllegalTopology', ... 'Two faces were found on left side of edge %d ', indEdge); end edgeFaces(indEdge, 2) = indFace; continue; end % If face was neither left nor right, error warning('meshes3d:IllegalTopology', ... 'Edge %d of face %d was not found in edge array', ... j, indFace); continue; end end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createTetrahedron.m0000644000000000000000000000013213066736044021437 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createTetrahedron.m0000644000175000017500000000562413066736044021622 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createTetrahedron() %CREATETETRAHEDRON Create a 3D mesh representing a tetrahedron % % [V, E, F] = createTetrahedron % create a simple tetrahedron, using mesh representation. The tetrahedron % is inscribed in the unit cube. % V is a 4-by-3 array with vertex coordinates, % E is a 6-by-2 array containing indices of neighbour vertices, % F is a 4-by-3 array containing vertices array of each (triangular) face. % % [V, F] = createTetrahedron; % Returns only the vertices and the faces. % % MESH = createTetrahedron; % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % % Example % % Create and display a tetrahedron % [V, E, F] = createTetrahedron; % drawMesh(V, F); % % See also % meshes3d, drawMesh % createCube, createOctahedron, createDodecahedron, createIcosahedron % --------- % author : David Legland % e-mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 21/03/2005. % % HISTORY % 04/01/2007: remove unused variables x0 = 0; dx= 1; y0 = 0; dy= 1; z0 = 0; dz= 1; nodes = [... x0 y0 z0; ... x0+dx y0+dy z0; ... x0+dx y0 z0+dz; ... x0 y0+dy z0+dz]; edges = [1 2;1 3;1 4;2 3;3 4;4 2]; faces = [1 2 3;1 3 4;1 4 2;4 3 2]; % format output varargout = formatMeshOutput(nargout, nodes, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshFaceEdges.m0000644000000000000000000000013213066736044020457 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshFaceEdges.m0000644000175000017500000000542113066736044020635 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function FE = meshFaceEdges(vertices, edges, faces) %MESHFACEEDGES Computes edge indices of each face % % FE = meshFaceEdges(V, E, F) % Returns a 1-by-NF cell array containing for each face, the set of edge % indices corresponding to adjacent edges. % % Example % meshFaceEdges % % See also % meshes3d, meshEdgeFaces % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2013-08-22, using Matlab 7.9.0.529 (R2009b) % Copyright 2013 INRA - Cepia Software Platform. nFaces = meshFaceNumber(vertices, faces); FE = cell(nFaces, 1); % impose ordering of edge indices edges = sort(edges, 2); for iFace = 1:nFaces % extract vertex indices of current face face = meshFace(faces, iFace); nv = length(face); % for each couple of adjacent vertices, find the index of the matching % row in the edges array fei = zeros(1, nv); for iEdge = 1:nv % compute index of each edge vertex edge = sort([face(iEdge) face(mod(iEdge, nv) + 1)]); v1 = edge(1); v2 = edge(2); % find the matching row ind = find(edges(:,1) == v1 & edges(:,2) == v2); fei(iEdge) = ind; end FE{iFace} = fei; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshes3d_Contents.m0000644000000000000000000000013213066736044021364 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshes3d_Contents.m0000644000175000017500000001615213066736044021545 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} meshes3d_Contents () ## MESHES3D 3D Surface Meshes ## Version 1.0 21-Mar-2011 . ## ## Creation, vizualization, and manipulation of 3D surface meshes or ## polyhedra. ## ## Meshes and Polyhedra are represented by a couple of variables @{V, F@}: ## V: Nv-by-3 array of vertices: [x1 y1 z1; @dots{} ; xn yn zn]; ## F: is either a NF-by-3 or NF-by-4 array containing reference for ## vertices of each face, or a NF-by-1 cell array, where each cell is an ## array containing a variable number of node indices. ## For some functions, the array E of edges is needed. It consists in a ## NE-by-2 array containing indices of source and target vertices. ## ## The library provides function to create basic polyhedric meshes (the 5 ## platonic solids, plus few others), as well as functions to perform ## basic computations (surface area, normal angles, face centroids @dots{}). ## The 'MengerSponge' structure is an example of mesh that is not simply ## connected (multiple tunnels in the structure). ## ## The drawMesh function is mainly a wrapper to the Matlab 'patch' ## function, allowing passing arguments more quickly. ## ## Example ## @example ## # create a soccer ball mesh and display it ## [n e f] = createSoccerBall; ## drawMesh(n, f, 'faceColor', 'g', 'linewidth', 2); ## axis equal; ## @end example ## ## ## General functions ## meshFace - Return the vertex indices of a face in a mesh ## computeMeshEdges - Computes edges array from face array ## meshEdgeFaces - Compute index of faces adjacent to each edge of a mesh ## faceCentroids - Compute centroids of a mesh faces ## faceNormal - Compute normal vector of faces in a 3D mesh ## ## Measures on meshes ## meshSurfaceArea - Surface area of a polyhedral mesh ## trimeshSurfaceArea - Surface area of a triangular mesh ## meshEdgeLength - Lengths of edges of a polygonal or polyhedral mesh ## meshDihedralAngles - Dihedral at edges of a polyhedal mesh ## polyhedronNormalAngle - Compute normal angle at a vertex of a 3D polyhedron ## polyhedronMeanBreadth - Mean breadth of a convex polyhedron ## ## Basic processing ## triangulateFaces - Convert face array to an array of triangular faces ## meshReduce - Merge coplanar faces of a polyhedral mesh ## minConvexHull - Return the unique minimal convex hull of a set of 3D points ## polyhedronSlice - Intersect a convex polyhedron with a plane. ## checkMeshAdjacentFaces - Check if adjacent faces of a mesh have similar orientation ## clipMeshVertices - Clip vertices of a surfacic mesh and remove outer faces ## clipConvexPolyhedronHP - Clip a convex polyhedron by a plane ## ## Typical polyhedra ## polyhedra - Index of classical polyhedral meshes ## createCube - Create a 3D mesh representing the unit cube ## createOctahedron - Create a 3D mesh representing an octahedron ## createCubeOctahedron - Create a 3D mesh representing a cube-octahedron ## createIcosahedron - Create a 3D mesh representing an Icosahedron. ## createDodecahedron - Create a 3D mesh representing a dodecahedron ## createTetrahedron - Create a 3D mesh representing a tetrahedron ## createRhombododecahedron - Create a 3D mesh representing a rhombododecahedron ## createTetrakaidecahedron - Create a 3D mesh representing a tetrakaidecahedron ## ## Less typical polyhedra ## createSoccerBall - Create a 3D mesh representing a soccer ball ## createMengerSponge - Create a cube with an inside cross removed ## steinerPolytope - Create a steiner polytope from a set of vectors ## ## Drawing functions ## drawFaceNormals - Draw normal vector of each face in a mesh ## drawMesh - Draw a 3D mesh defined by vertices and faces ## @end deftypefn function meshes3d_Contents () help meshes3d_Contents endfunction geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/torusMesh.m0000644000000000000000000000013213066736044017765 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/torusMesh.m0000644000175000017500000000736013066736044020147 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = torusMesh(torus, varargin) %TORUSMESH Create a 3D mesh representing a torus % % [V, F] = torusMesh(TORUS) % Converts the torus in TORUS into a face-vertex quadrangular mesh. % TORUS is given by [XC YC ZY R1 R2 THETA PHI] % where (XC YZ ZC) is the center of the torus, R1 is the main radius, R2 % is the radius of the torus section, and (THETA PHI) is the angle of the % torus normal vector (both in degrees). % % [V, F] = torusMesh(TORUS, 'nTheta', NT, 'nPhi', NP) % Creates a mesh using NP circles, each circle being discretized with NT % vertices. Default are 60 for both parameters. % % [V, F] = torusMesh() % Creates a mesh representing a default torus. % % Example % [v, f] = torusMesh([50 50 50 30 10 30 45]); % figure; drawMesh(v, f, 'linestyle', 'none'); % view(3); axis equal; % lighting gouraud; light; % % % See also % meshes3d, drawTorus, revolutionSurface, cylinderMesh, sphereMesh % drawMesh % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. % HISTORY % 2013-04-30 add support for empty argument %% Extract data for torus if nargin == 0 torus = [0 0 0 30 10 0 0 0]; end center = torus(1:3); r1 = torus(4); r2 = torus(5); if size(torus, 2) >= 7 normal = torus(6:7); end %% Extract data for discretisation % number nTheta = 60; nPhi = 60; while length(varargin) > 1 argName = varargin{1}; switch lower(argName) case 'ntheta' nTheta = varargin{2}; case 'nphi' nPhi = varargin{2}; otherwise error('Unknown optional argument: %s', argName); end varargin(1:2) = []; end %% Discretize torus % create base torus circle = circleToPolygon([r1 0 r2], nTheta); [x, y, z] = revolutionSurface(circle, linspace(0, 2*pi, nPhi)); % transform torus trans = localToGlobal3d([center normal]); [x, y, z] = transformPoint3d(x, y, z, trans); % convert to FV mesh [vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', true, 'yPeriodic', true); % format output varargout = formatMeshOutput(nargout, vertices, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshEdges.m0000644000000000000000000000013213066736044017700 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshEdges.m0000644000175000017500000000673213066736044020064 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function edges = meshEdges(faces, varargin) %MESHEDGES Computes array of edge vertex indices from face array % % EDGES = meshEdges(FACES); % % Example % meshEdges % % See also % meshes3d, meshEdgeFaces, meshFaceEdges % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-06-28, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. % HISTORY % 2013-08-22 rename from computeMeshEdges to meshEdges, add more control % on inputs %% Process input arguments if isstruct(faces) && isfield(faces, 'faces') % if input is a mesh structure, extract the 'faces' field faces = faces.faces; elseif nargin > 1 % if two arguments are given, keep the second one faces = varargin{1}; end if ~iscell(faces) %% Process faces given as numeric array % all faces have same number of vertices, stored in nVF variable % compute total number of edges nFaces = size(faces, 1); nVF = size(faces, 2); nEdges = nFaces * nVF; % create all edges (with double ones) edges = zeros(nEdges, 2); for i = 1:nFaces f = faces(i, :); edges(((i-1)*nVF+1):i*nVF, :) = [f' f([2:end 1])']; end else %% faces are given as a cell array % faces may have different number of vertices % number of faces nFaces = length(faces); % compute the number of edges nEdges = 0; for i = nFaces nEdges = nEdges + length(faces{i}); end % allocate memory edges = zeros(nEdges, 2); ind = 0; % fillup edge array for i = 1:nFaces % get vertex indices, ensuring horizontal array f = faces{i}(:)'; nVF = length(f); edges(ind+1:ind+nVF, :) = [f' f([2:end 1])']; ind = ind + nVF; end end % keep only unique edges, and return sorted result edges = sortrows(unique(sort(edges, 2), 'rows')); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/faceCentroids.m0000644000000000000000000000013213066736044020545 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/faceCentroids.m0000644000175000017500000000643313066736044020727 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function centroids = faceCentroids(nodes, faces) %FACECENTROIDS Compute centroids of a mesh faces % % NORMALS = faceCentroids(VERTICES, FACES) % VERTICES is a set of 3D points (as a N-by-3 array), and FACES is % either a N-by-3 index array or a cell array of indices. The function % computes the centroid of each face, and returns a Nf-by-3 array % containing their coordinates. % % Example % [v e f] = createIcosahedron; % normals1 = faceNormal(v, f); % centros1 = faceCentroids(v, f); % figure; drawMesh(v, f); % hold on; axis equal; view(3); % drawVector3d(centros1, normals1); % % % See also: % meshes3d, drawMesh, faceNormal, convhull, convhulln % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2006-07-05 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). % HISTORY % 2007/09/18 fix: worked only for 2D case, now works also for 3D if isnumeric(faces) % trimesh or quadmesh nf = size(faces, 1); centroids = zeros(nf, size(nodes, 2)); if size(nodes, 2) == 2 % planar case for f = 1:nf centroids(f,:) = polygonCentroid(nodes(faces(f,:), :)); end else % 3D case for f = 1:nf centroids(f,:) = polygonCentroid3d(nodes(faces(f,:), :)); end end else % mesh with faces stored as cell array nf = length(faces); centroids = zeros(nf, size(nodes, 2)); if size(nodes, 2) == 2 % planar case for f = 1:nf centroids(f,:) = polygonCentroid(nodes(faces{f}, :)); end else % 3D case for f = 1:nf centroids(f,:) = polygonCentroid3d(nodes(faces{f}, :)); end end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/readMesh_off.m0000644000000000000000000000013213066736044020356 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/readMesh_off.m0000644000175000017500000000563313066736044020541 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [vertices, faces] = readMesh_off(fileName) %READMESH_OFF Read mesh data stord in OFF format % % [VERTICES FACES] = readMesh_off(FILNAME) % % Example % readMesh_off % % See also % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-12-20, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. % open file f = fopen(fileName, 'r'); if f == -1 error('matGeom:readMesh_off:FileNotFound', ... ['Could not find file: ' fileName]); end % check format line = fgets(f); % -1 if eof if ~strcmp(line(1:3), 'OFF') error('matGeom:readMesh_off:FileFormatError', ... 'Not a valid OFF file'); end % number of faces and vertices line = fgets(f); vals = sscanf(line, '%d %d'); nv = vals(1); nf = vals(2); % read vertex data [vertices, count] = fscanf(f, '%f ', [3 nv]); if count ~= nv*3 error('matGeom:readMesh_off:FileFormatError', ... ['Could not read all the ' num2str(nv) ' vertices']); end vertices = vertices'; % read face data (face start by index) [faces, count] = fscanf(f, '%d %d %d %d\n', [4 nf]); if count ~= nf * 4 error('matGeom:readMesh_off:FileFormatError', ... ['Could not read all the ' num2str(nf) ' faces']); end % clean up: remove index, and use 1-indexing faces = faces(2:4, :)' + 1; % close the file fclose(f); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/private0000644000000000000000000000013213066736044017213 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/private/0002755000175000017500000000000013066736044017446 5ustar00olafolaf00000000000000geometry-3.0.0/inst/meshes3d/private/PaxHeaders.28738/parseMeshData.m0000644000000000000000000000013213066736044022167 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/private/parseMeshData.m0000644000175000017500000001101013066736044022334 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{mesh} =} parseMeshData (@var{vertices},@var{edges},@var{faces}) ## @deftypefnx {Function File} {@var{mesh} =} parseMeshData (@var{vertices},@var{faces}) ## @deftypefnx {Function File} {[@var{vertices},@var{edges},@var{faces}] =} parseMeshData (@var{mesh}) ## @deftypefnx {Function File} {[@var{vertices},@var{faces}] =} parseMeshData (@var{mesh}) ## Conversion of data representation for meshes ## ## MESH = parseMeshData(VERTICES, EDGES, FACES) ## MESH = parseMeshData(VERTICES, FACES) ## [VERTICES EDGES FACES] = parseMeshData(MESH) ## [VERTICES FACES] = parseMeshData(MESH) ## ## ## @seealso{meshes3d, formatMeshOutput} ## @end deftypefn function varargout = parseMeshData(varargin) # initialize edges edges = []; # Process input arguments if nargin == 1 # input is a data structure mesh = varargin{1}; vertices = mesh.vertices; faces = mesh.faces; if isfield(mesh, 'edges') edges = mesh.edges; end elseif nargin == 2 # input are vertices and faces vertices = varargin{1}; faces = varargin{2}; elseif nargin == 3 # input are vertices, edges and faces vertices = varargin{1}; edges = varargin{2}; faces = varargin{3}; else error('Wrong number of arguments'); end varargout = formatMeshOutput(nargout, vertices, edges, faces); endfunction geometry-3.0.0/inst/meshes3d/private/PaxHeaders.28738/formatMeshOutput.m0000644000000000000000000000013213066736044022774 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/private/formatMeshOutput.m0000644000175000017500000001176313066736044023160 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{output} =} formatMeshOutput (@var{nbargs}, @var{vertices},@var{edges},@var{faces}) ## @deftypefnx {Function File} {@var{output} =} formatMeshOutput (@var{nbargs}, @var{vertices},@var{faces}) ## Format mesh output depending on nargout ## ## OUTPUT = formatMeshOutput(@var{nbargs}, VERTICES, EDGES, FACES) ## Utilitary function to convert mesh data . ## If @var{nbargs} is 0 or 1, return a matlab structure with fields vertices, ## edges and faces. ## If @var{nbargs} is 2, return a cell array with data VERTICES and FACES. ## If @var{nbargs} is 3, return a cell array with data VERTICES, EDGES and ## FACES. ## ## OUTPUT = formatMeshOutput(@var{nbargs}, VERTICES, FACES) ## Same as before, but do not intialize EDGES in output. NARGOUT can not ## be equal to 3. ## ## Example ## # Typical calling sequence (for a very basic mesh of only one face) ## v = [0 0; 0 1;1 0;1 1]; ## e = [1 2;1 3;2 4;3 4]; ## f = [1 2 3 4]; ## ## varargout = formatMeshOutput(nargout, v, e, f); ## ## @seealso{meshes3d, parseMeshData} ## @end deftypefn function res = formatMeshOutput(nbArgs, vertices, edges, faces) if nargin < 4 faces = edges; edges = []; end switch nbArgs case {0, 1} # output is a data structure with fields vertices, edges and faces mesh.vertices = vertices; mesh.edges = edges; mesh.faces = faces; res = {mesh}; case 2 # keep only vertices and faces res = cell(nbArgs, 1); res{1} = vertices; res{2} = faces; case 3 # return vertices, edges and faces as 3 separate outputs res = cell(nbArgs, 1); res{1} = vertices; res{2} = edges; res{3} = faces; otherwise error('Can not manage more than 3 outputs'); end endfunction geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/triangulateFaces.m0000644000000000000000000000013213066736044021255 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/triangulateFaces.m0000644000175000017500000001063113066736044021432 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [tri, inds] = triangulateFaces(faces) %TRIANGULATEFACES Convert face array to an array of triangular faces % % TRI = triangulateFaces(FACES) % Returns a 3-columns array of indices, based on the data stored in the % argument FACES: % - if FACES is a N-by-3 array, returns the same array % - if FACES is a N-by-4 array, returns an array with 2*N rows and 3 % columns, splitting each square into 2 triangles (uses first and % third vertex of each square as diagonal). % - if FACES is a cell array, split each face into a set of triangles, % and returns the union of all triangles. Faces are assumed to be % convex. % % [TRI INDS] = triangulateFaces(FACES) % Also returns original face index of each new triangular face. INDS has % the same number of rows as TRI, and has values between 1 and the % number of rows of the original FACES array. % % % Example % % create a basic shape % [n e f] = createCubeOctahedron; % % draw with plain faces % figure; % drawMesh(n, f); % % draw as a triangulation % tri = triangulateFaces(f); % figure; % patch('vertices', n, 'faces', tri, 'facecolor', 'r'); % % See also % meshes3d, drawMesh, mergeCoplanarFaces % % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2008-09-08, using Matlab 7.4.0.287 (R2007a) % Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. %% Tri mesh case: return original set of faces if isnumeric(faces) && size(faces, 2) == 3 tri = faces; if nargout > 1 inds = (1:size(faces, 1))'; end return; end %% Square faces: split each square into 2 triangles if isnumeric(faces) && size(faces, 2) == 4 nf = size(faces, 1); tri = zeros(nf * 2, 3); tri(1:2:end, :) = faces(:, [1 2 3]); tri(2:2:end, :) = faces(:, [1 3 4]); if nargout > 1 inds = kron(1:size(faces, 1), ones(1,2))'; end return; end %% Pentagonal faces (for dodecahedron...): split into 3 triangles if isnumeric(faces) && size(faces, 2) == 5 nf = size(faces, 1); tri = zeros(nf * 3, 3); tri(1:3:end, :) = faces(:, [1 2 3]); tri(2:3:end, :) = faces(:, [1 3 4]); tri(3:3:end, :) = faces(:, [1 4 5]); if nargout > 1 inds = kron(1:size(faces, 1), ones(1,2))'; end return; end %% Faces as cell array % number of faces nf = length(faces); % compute total number of triangles ni = zeros(nf, 1); for i = 1:nf % as many triangles as the number of vertices minus 1 ni(i) = length(faces{i}) - 2; end nt = sum(ni); % allocate memory for triangle array tri = zeros(nt, 3); inds = zeros(nt, 1); % convert faces to triangles t = 1; for i = 1:nf face = faces{i}; nv = length(face); v0 = face(1); for j = 3:nv tri(t, :) = [v0 face(j-1) face(j)]; inds(t) = i; t = t + 1; end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/trimeshEdgeFaces.m0000644000000000000000000000013213066736044021176 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/trimeshEdgeFaces.m0000644000175000017500000000747413066736044021366 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function edgeFaces = trimeshEdgeFaces(faces, varargin) %TRIMESHEDGEFACES Compute index of faces adjacent to each edge of a triangular mesh % % EF = trimeshEdgeFaces(FACES) % EF = trimeshEdgeFaces(VERTICES, FACES) % EF = trimeshEdgeFaces(VERTICES, EDGES, FACES) % Compute index array of faces adjacent to each edge of a mesh. % FACES is a NF-by-3 array containing vertex indices of each face. The % result EF is a NE-by-2 array containing the indices of the two faces % incident to each edge. If an edge belongs to only one face, the other % face index is ZERO. % % The list of edges (as array of source and target vertex indices) can be % obtained from the function 'meshEdges'. % % Note: faces are listed in increasing order for each edge, and no % information is kept about relative orientation of edge and face. % % Example % % compute incidence list of each edge of an octahedron. For example, % % first edge is incident to faces 1 and 5. Second edge is incident to % % faces 4 and 8, and so on. % [v, f] = createOctahedron; % ef = trimeshEdgeFaces(v, f) % ef = % 1 5 % 4 8 % 4 1 % 5 8 % 2 6 % 1 2 % 6 5 % 3 7 % 2 3 % 7 6 % 3 4 % 7 8 % % See also % meshes3d, meshEdgeFaces, trimeshMeanBreadth, meshEdges % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2015-08-19, using Matlab 8.5.0.197613 (R2015a) % Copyright 2015 INRA - Cepia Software Platform. if nargin == 2 faces = varargin{1}; elseif nargin == 3 faces = varargin{2}; end % compute vertex indices of each edge (in increasing index order) edges = sort([faces(:,[1 2]) ; faces(:,[2 3]) ; faces(:,[3 1])], 2); % create an array to keep indices of faces "creating" each edge nFaces = size(faces, 1); edgeFaceInds = repmat( (1:nFaces)', 3, 1); % sort edges, keeping indices [edges, ia, ib] = unique(edges, 'rows'); %#ok nEdges = size(edges, 1); % allocate memory for result edgeFaces = zeros(nEdges, 2); % iterate over edges, to identify incident faces for iEdge = 1:nEdges inds = find(ib == iEdge); edgeFaces(iEdge, 1:length(inds)) = edgeFaceInds(inds); end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createOctahedron.m0000644000000000000000000000013213066736044021246 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createOctahedron.m0000644000175000017500000000615413066736044021430 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createOctahedron() %CREATEOCTAHEDRON Create a 3D mesh representing an octahedron % % [V, E, F] = createOctahedron; % Create a 3D mesh representing an octahedron % V is a 6-by-3 array with vertices coordinate, E is a 12-by-2 array % containing indices of neighbour vertices, and F is a 8-by-3 array % containing array of vertex index for each face. % % [V, F] = createOctahedron; % Returns only the vertices and the face vertex indices. % % MESH = createOctahedron; % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % Vertices are located on grid vertices: % ( ±1, 0, 0 ) % ( 0, ±1, 0 ) % ( 0, 0, ±1 ) % % Edge length of returned octahedron is sqrt(2). % Surface area of octahedron is 2*sqrt(3)*a^2, approximately 6.9282 in % this case. % Volume of octahedron is sqrt(2)/3*a^3, approximately 1.3333 in this % case. % % Example % [v, e, f] = createOctahedron; % drawMesh(v, f); % % See also % meshes3d, drawMesh % createCube, createIcosahedron, createDodecahedron, createTetrahedron % createCubeOctahedron % % --------- % author : David Legland % e-mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 10/02/2005. % % HISTORY % 04/01/2007: remove unused variables nodes = [1 0 0;0 1 0;-1 0 0;0 -1 0;0 0 1;0 0 -1]; edges = [1 2;1 4;1 5; 1 6;2 3;2 5;2 6;3 4;3 5;3 6;4 5;4 6]; faces = [1 2 5;2 3 5;3 4 5;4 1 5;1 6 2;2 6 3;3 6 4;1 4 6]; % format output varargout = formatMeshOutput(nargout, nodes, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/vertexNormal.m0000644000000000000000000000013213066736044020462 xustar0030 mtime=1490795556.672870949 30 atime=1490795556.672870949 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/vertexNormal.m0000644000175000017500000000605613066736044020645 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function normals = vertexNormal(vertices, faces) %VERTEXNORMAL Compute normals to a mesh vertices % % N = vertexNormal(V, F) % Computes vertex normals of the mesh given by vertices V and F. % V is a vertex array with 3 columns, F is either a NF-by-3 or NF-by-4 % index array, or a cell array with NF elements. % % Example % % Draw the vertex normals of a sphere % s = [10 20 30 40]; % [v f] = sphereMesh(s); % drawMesh(v, f); % view(3);axis equal; light; lighting gouraud; % normals = vertexNormal(v, f); % drawVector3d(v, normals); % % See also % meshes3d, faceNormal, triangulateFaces % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-12-19, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. nv = size(vertices, 1); nf = size(faces, 1); % unit normals to the faces faceNormals = normalizeVector3d(faceNormal(vertices, faces)); % compute normal of each vertex: sum of normals to each face normals = zeros(nv, 3); if isnumeric(faces) for i = 1:nf face = faces(i, :); for j = 1:length(face) v = face(j); normals(v, :) = normals(v,:) + faceNormals(i,:); end end else for i = 1:nf face = faces{i}; for j = 1:length(face) v = face(j); normals(v, :) = normals(v,:) + faceNormals(i,:); end end end % normalize vertex normals to unit vectors normals = normalizeVector3d(normals); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createRhombododecahedron.m0000644000000000000000000000013213066736044022746 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createRhombododecahedron.m0000644000175000017500000000603113066736044023122 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createRhombododecahedron() %CREATERHOMBODODECAHEDRON Create a 3D mesh representing a rhombododecahedron % % [V, E, F] = createRhombododecahedron % V is a 14-by-3 array with vertex coordinate, % E is a 12-by-2 array containing indices of neighbour vertices, % F is a 8-by-3 array containing vertices array of each face. % % [V, F] = createRhombododecahedron; % Returns only the vertices and the face vertex indices. % % MESH = createRhombododecahedron; % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % Example % [v, e, f] = createRhombododecahedron; % drawMesh(v, f); % % % See also % meshes3d, drawMesh % --------- % author : David Legland % e-mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 10/02/2005. % % HISTORY % 04/01/2007: remove unused variables nodes = [0 0 2;... 1 -1 1;1 1 1;-1 1 1;-1 -1 1;... 2 0 0;0 2 0;-2 0 0;0 -2 0;... 1 -1 -1;1 1 -1;-1 1 -1;-1 -1 -1;... 0 0 -2]; edges = [... 1 2;1 3;1 4;1 5;... 2 6;2 9;3 6;3 7;4 7;4 8;5 8;5 9;... 6 10;6 11;7 11;7 12;8 12;8 13;9 10;9 13; ... 10 14;11 14;12 14;13 14]; faces = [... 1 2 6 3;... 1 3 7 4;... 1 4 8 5;... 1 5 9 2;... 2 9 10 6;... 3 6 11 7;... 4 7 12 8;... 5 8 13 9;... 6 10 14 11;... 7 11 14 12;... 8 12 14 13;... 9 13 14 10]; % format output varargout = formatMeshOutput(nargout, nodes, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/checkMeshAdjacentFaces.m0000644000000000000000000000013213066736044022262 xustar0030 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/checkMeshAdjacentFaces.m0000644000175000017500000000717313066736044022446 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function checkMeshAdjacentFaces(vertices, edges, faces) %CHECKMESHADJACENTFACES Check if adjacent faces of a mesh have similar orientation % % checkMeshAdjacentFaces(VERTICES, EDGES, FACES) % The functions returns no output, but if two faces share a common edge % with the same direction (meaning that adjacent faces have normals in % opposite direction), a warning is displayed. % % Example % [v e f] = createCube(); % checkMeshAdjacentFaces(v, e, f); % % no output -> all faces have normal outwards of the cube % % v = [0 0 0; 10 0 0; 0 10 0; 10 10 0]; % e = [1 2;1 3;2 3;2 4;3 4]; % f = [1 2 3; 2 3 4]; % checkMeshAdjacentFaces(v, e, f); % Warning: Faces 1 and 2 run through the edge 3 (2-3) in the same direction % % See also % meshes3d % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-06, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. pattern = 'Faces %d and %d run through the edge %d (%d-%d) in the same direction'; edgeFaces = meshEdgeFaces(vertices, edges, faces); Ne = size(edgeFaces, 1); for i = 1:Ne % indices of extreimty vertices v1 = edges(i, 1); v2 = edges(i, 2); % index of adjacent faces indF1 = edgeFaces(i, 1); indF2 = edgeFaces(i, 2); % if one of the faces has index 0, then the edge is at the boundary if indF1 == 0 || indF2 == 0 continue; end % vertices of adjacent faces face1 = meshFace(faces, indF1); face2 = meshFace(faces, indF2); % position of vertices in face vertex array ind11 = find(face1 == v1); ind12 = find(face1 == v2); ind21 = find(face2 == v1); ind22 = find(face2 == v2); % check if edge is traveled forward or backard direct1 = (ind12 == ind11+1) | (ind12 == 1 & ind11 == length(face1)); direct2 = (ind22 == ind21+1) | (ind22 == 1 & ind21 == length(face2)); % adjacent faces should travel the edge in opposite direction if direct1 == direct2 warning(pattern, indF1, indF2, i, v1, v2); %#ok end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createCubeOctahedron.m0000644000000000000000000000013213066736044022045 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createCubeOctahedron.m0000644000175000017500000001131513066736044022222 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{v}, @var{e}, @var{f}] =} createCubeOctahedron () ## @deftypefnx {Function File} {@var{mesh} =} createCubeOctahedron () ## Create a 3D mesh representing a cube-octahedron ## ## [V E F] = createCubeOctahedron; ## Cubeoctahedron can be seen either as a truncated cube, or as a ## truncated octahedron. ## V is the 12-by-3 array of vertex coordinates ## E is the 27-by-2 array of edge vertex indices ## F is the 1-by-14 cell array of face vertex indices ## ## [V F] = createCubeOctahedron; ## Returns only the vertices and the face vertex indices. ## ## MESH = createCubeOctahedron; ## Returns the data as a mesh structure, with fields 'vertices', 'edges' ## and 'faces'. ## ## @seealso{meshes3d, drawMesh, createCube, createOctahedron} ## @end deftypefn function varargout = createCubeOctahedron() nodes = [... 0 -1 1;1 0 1;0 1 1;-1 0 1; ... 1 -1 0;1 1 0;-1 1 0;-1 -1 0;... 0 -1 -1;1 0 -1;0 1 -1;-1 0 -1]; edges = [... 1 2; 1 4; 1 5; 1 8; ... 2 3; 2 5; 2 6; ... 3 4; 3 6; 3 7; ... 4 7; 4 8; ... 5 9; 5 10; ... 6 10; 6 11; ... 7 11; 7 12; ... 8 9; 8 12; ... 9 10; 9 12; ... 10 11; 11 12]; faces = {... [1 2 3 4], [1 5 2], [2 6 3], [3 7 4], [4 8 1], ... [5 10 6 2], [3 6 11 7], [4 7 12 8], [1 8 9 5], ... [5 9 10], [6 10 11], [7 11 12], [8 12 9], [9 12 11 10]}; # format output varargout = formatMeshOutput(nargout, nodes, edges, faces); endfunction %!demo %! [n e f] = createCubeOctahedron; %! drawMesh (n, f); %! view (3); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/intersectPlaneMesh.m0000644000000000000000000000013213066736044021571 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/intersectPlaneMesh.m0000644000175000017500000001434113066736044021750 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function polys = intersectPlaneMesh(plane, v, f) %INTERSECTPLANEMESH Compute the polygons resulting from plane-mesh intersection % % POLYS = intersectPlaneMesh(P, V, F) % Computes the interection between a plane and a mesh given by vertex and % face lists. The result is a cell array of polygons. % % The function currently returns at most one polygon in the cell array % POLYS. % % % Example % % Intersect a cube by a plane % [v f] = createCube; v = v * 10; % plane = createPlane([5 5 5], [3 4 5]); % % draw the primitives % figure; hold on; set(gcf, 'renderer', 'opengl'); % axis([-10 20 -10 20 -10 20]); view(3); % drawMesh(v, f); drawPlane3d(plane); % % compute intersection polygon % polys = intersectPlaneMesh(plane, v, f); % drawPolygon3d(polys, 'LineWidth', 2); % % % Intersect a torus by a set of planes, and draw the results % % first creates a torus slightly shifted and rotated % torus = [.5 .6 .7 30 10 3 4]; % figure; drawTorus(torus, 'nTheta', 180, 'nPhi', 180); % hold on; view (3); axis equal; light; % % convert to mesh representation % [v, f] = torusMesh(torus, 'nTheta', 64, 'nPhi', 64); % % compute intersections with collection of planes % xList = -50:5:50; % polySet = cell(length(xList), 1); % for i = 1:length(xList) % x0 = xList(i); % plane = createPlane([x0 .5 .5], [1 .2 .3]); % polySet{i} = intersectPlaneMesh2(plane, v, f); % end % % draw the resulting 3D polygons % drawPolygon3d(polySet, 'lineWidth', 2, 'color', 'k') % % % See also % meshes3d, intersectPlanes, intersectEdgePlane % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-07-31, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. %% Computation of crossing edges % compute the edge list e = meshEdges(f); edges = [ v(e(:,1), :) v(e(:,2), :) ]; % identify which edges cross the mesh inds = isBelowPlane(v, plane); edgeCrossInds = find(sum(inds(e), 2) == 1); % compute one intersection point for each edge intersectionPoints = intersectEdgePlane(edges(edgeCrossInds, :), plane); %% mapping edges <-> faces % identify for each face the indices of edges that intersect the plane, as % well as for each edge, the indices of the two faces around it. % We expect each face to contain either 0 or 2 intersecting edges. % nFaces = length(f); faceEdges = cell(1, nFaces); nCrossEdges = length(edgeCrossInds); crossEdgeFaces = zeros(nCrossEdges, 2); for iEdge = 1:length(edgeCrossInds) edge = e(edgeCrossInds(iEdge), :); indFaces = find(sum(ismember(f, edge), 2) == 2); if length(indFaces) ~= 2 error('crossing edge %d (%d,%d) is associated to %d faces', ... iEdge, edge(1), edge(2), length(indFaces)); end crossEdgeFaces(iEdge, :) = indFaces; for iFace = 1:length(indFaces) indEdges = faceEdges{indFaces(iFace)}; indEdges = [indEdges iEdge]; %#ok faceEdges{indFaces(iFace)} = indEdges; end end %% Iterate on edges and faces to form polygons % initialize an array indicating which indices need to be processed nCrossEdges = length(edgeCrossInds); remainingCrossEdges = true(nCrossEdges, 1); % create empty cell array of polygons polys = {}; % iterate while there are some crossing edges to process while any(remainingCrossEdges) % start at any edge, mark it as current startEdgeIndex = find(remainingCrossEdges, 1, 'first'); currentEdgeIndex = startEdgeIndex; % mark current edge as processed remainingCrossEdges(currentEdgeIndex) = false; % initialize new set of edge indices polyEdgeInds = currentEdgeIndex; % choose one of the two faces around the edge currentFace = crossEdgeFaces(currentEdgeIndex, 1); % iterate along current face-edge couples until back to first edge while true % find the index of next crossing edge inds = faceEdges{currentFace}; currentEdgeIndex = inds(inds ~= currentEdgeIndex); % mark current edge as processed remainingCrossEdges(currentEdgeIndex) = false; % find the index of the other face containing current edge inds = crossEdgeFaces(currentEdgeIndex, :); currentFace = inds(inds ~= currentFace); % check end of current loop if currentEdgeIndex == startEdgeIndex break; end % add index of current edge polyEdgeInds = [polyEdgeInds currentEdgeIndex]; %#ok end % create polygon, and add it to list of polygons poly = intersectionPoints(polyEdgeInds, :); polys = [polys, {poly}]; %#ok end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createCube.m0000644000000000000000000000013213066736044020036 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createCube.m0000644000175000017500000001131413066736044020212 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. ## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{v},@var{e},@var{f}] =} createCube () ## @deftypefnx {Function File} {[@var{v},@var{f}] =} createCube () ## @deftypefnx {Function File} {@var{mesh} =} createCube () ## Create a 3D mesh representing the unit cube ## ## [V E F] = createCube ## Create a unit cube, as a polyhedra representation. ## c has the form [V E F], where V is a 8-by-3 array with vertices ## coordinates, E is a 12-by-2 array containing indices of neighbour ## vertices, and F is a 6-by-4 array containing vertices array of each ## face. ## ## [V F] = createCube; ## Returns only the vertices and the face vertex indices. ## ## MESH = createCube; ## Returns the data as a mesh structure, with fields 'vertices', 'edges' ## and 'faces'. ## ## Example ## @example ## [n e f] = createCube; ## drawMesh(n, f); ## @end example ## ## @seealso{meshes3d, drawMesh, createOctahedron, createTetrahedron, ## createDodecahedron, createIcosahedron, createCubeOctahedron} ## @end deftypefn function varargout = createCube() x0 = 0; dx= 1; y0 = 0; dy= 1; z0 = 0; dz= 1; nodes = [... x0 y0 z0; ... x0+dx y0 z0; ... x0 y0+dy z0; ... x0+dx y0+dy z0; ... x0 y0 z0+dz; ... x0+dx y0 z0+dz; ... x0 y0+dy z0+dz; ... x0+dx y0+dy z0+dz]; edges = [1 2;1 3;1 5;2 4;2 6;3 4;3 7;4 8;5 6;5 7;6 8;7 8]; # faces are oriented such that normals point outwards faces = [1 3 4 2;5 6 8 7;2 4 8 6;1 5 7 3;1 2 6 5;3 7 8 4]; # format output varargout = formatMeshOutput(nargout, nodes, edges, faces); endfunction %!demo %! [n e f] = createCube; %! drawMesh (n, f); %! view (3); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/tetrahedronVolume.m0000644000000000000000000000013213066736044021503 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/tetrahedronVolume.m0000644000175000017500000000551713066736044021667 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function vol = tetrahedronVolume(vertices, varargin) %TETRAHEDRONVOLUME Signed volume of a tetrahedron % % VOL = tetrahedronVolume(TETRA) % Comptues the siged volume of the tetrahedron TETRA defined by a 4-by-4 % array representing the polyhedron vertices. % % Example % vi = [0 0 0;1 0 0;0 1 0;0 0 1]; % tetrahedronVolume(vi) % ans = % 0.1667 % % [V F] = createTetrahedron; % tetrahedronVolume(V) % ans = % -.3333 % % See also % meshes3d, createTetrahedron, meshVolume % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-04-05, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. if nargin == 2 tetras = varargin{1}; nTetras = size(tetras, 1); vol = zeros(nTetras, 1); for i = 1:nTetras tetra = tetras(i,:); vol(i) = det(bsxfun(@minus, vertices(tetra(2:4),:), vertices(tetra(1),:))) / 6; end return; end % control on inputs if nargin == 4 vertices = [vertices ; varargin{1} ; varargin{2} ; varargin{3}]; end if size(vertices, 1) < 4 error('Input vertex array requires at least 4 vertices'); end % compute volume of tetrahedron, using first vertex as origin vol = det(vertices(2:4,:) - vertices([1 1 1],:)) / 6; geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshFacePolygons.m0000644000000000000000000000013213066736044021242 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshFacePolygons.m0000644000175000017500000000507113066736044021421 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function polys = meshFacePolygons(varargin) %MESHFACEPOLYGONS Returns the set of polygons that constitutes a mesh % % POLYGONS = meshFacePolygons(V, F) % POLYGONS = meshFacePolygons(MESH) % % Example % [v f] = createCubeOctahedron; % polygons = meshFacePolygons(v, f); % areas = polygonArea3d(polygons); % sum(areas) % ans = % 18.9282 % % See also % meshes3d, meshFace, polygonArea3d % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2013-08-20, using Matlab 7.9.0.529 (R2009b) % Copyright 2013 INRA - Cepia Software Platform. % extract vertices and faces [v, f] = parseMeshData(varargin{:}); % number of faces if iscell(f) nFaces = length(f); else nFaces = size(f, 1); end % allocate cell array for result polys = cell(nFaces, 1); % compute polygon corresponding to each face if iscell(f) for i = 1:nFaces polys{i} = v(f{i}, :); end else for i = 1:nFaces polys{i} = v(f(i,:), :); end end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/polyhedra.m0000644000000000000000000000013213066736044017763 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/polyhedra.m0000644000175000017500000000510713066736044020142 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function polyhedra(varargin) %POLYHEDRA Index of classical polyhedral meshes % % Polyhedra are specific meshes, with additional assumptions: % * the set of faces is assumed to enclose a single 3D domain % * each face has a neighbor face for each edge % * some functions also assume that normals of all faces point ouwards % % Example % % create a soccer ball mesh and display it % [n e f] = createSoccerBall; % drawMesh(n, f, 'faceColor', 'g', 'linewidth', 2); % axis equal; % % See also % meshes3d % createCube, createCubeOctahedron, createIcosahedron, createOctahedron % createRhombododecahedron, createTetrahedron, createTetrakaidecahedron % createDodecahedron, createSoccerBall, createMengerSponge % steinerPolytope, minConvexHull % polyhedronNormalAngle, polyhedronMeanBreadth % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2008-10-13, using Matlab 7.4.0.287 (R2007a) % Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. % HISTORY geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshSurfaceArea.m0000644000000000000000000000013213066736044021032 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshSurfaceArea.m0000644000175000017500000000664113066736044021215 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function area = meshSurfaceArea(vertices, edges, faces) %MESHSURFACEAREA Surface area of a polyhedral mesh % % S = meshSurfaceArea(V, F) % S = meshSurfaceArea(V, E, F) % Computes the surface area of the mesh specified by vertex array V and % face array F. Vertex array is a NV-by-3 array of coordinates. % Face array can be a NF-by-3 or NF-by-4 numeric array, or a Nf-by-1 cell % array, containing vertex indices of each face. % % This functions iterates on faces, extract vertices of the current face, % and computes the sum of face areas. % % This function assumes faces are coplanar and convex. If faces are all % triangular, the function "trimeshSurfaceArea" should be more efficient. % % % Example % % compute the surface of a unit cube (should be equal to 6) % [v f] = createCube; % meshSurfaceArea(v, f) % ans = % 6 % % See also % meshes3d, trimeshSurfaceArea, meshVolume, meshFacePolygons, % polygonArea3d % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-13, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % check input number if nargin == 2 faces = edges; end % pre-compute normals normals = normalizeVector3d(faceNormal(vertices, faces)); % init accumulator area = 0; if isnumeric(faces) % iterate on faces in a numeric array for i = 1:size(faces, 1) poly = vertices(faces(i, :), :); area = area + polyArea3d(poly, normals(i,:)); end else % iterate on faces in a cell array for i = 1:length(faces) poly = vertices(faces{i}, :); area = area + polyArea3d(poly, normals(i,:)); end end function a = polyArea3d(v, normal) nv = size(v, 1); v0 = repmat(v(1,:), nv, 1); products = sum(cross(v-v0, v([2:end 1], :)-v0, 2), 1); a = abs(dot(products, normal, 2))/2; geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/polyhedronMeanBreadth.m0000644000000000000000000000013213066736044022252 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/polyhedronMeanBreadth.m0000644000175000017500000000705313066736044022433 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function breadth = polyhedronMeanBreadth(vertices, edges, faces) %POLYHEDRONMEANBREADTH Mean breadth of a convex polyhedron % % BREADTH = polyhedronMeanBreadth(V, E, F) % Return the mean breadth (average of polyhedron caliper diameter over % all direction) of a convex polyhedron. % % The mean breadth is computed using the sum, over the edges of the % polyhedron, of the edge dihedral angles multiplied by the edge length, % the final sum being divided by (4*PI). % % Note: the function assumes that the faces are correctly oriented. The % face vertices should be indexed counter-clockwise when considering the % supporting plane of the plane, with the outer normal oriented outwards % of the polyhedron. % % Typical values for classical polyhedra are: % cube side a breadth = (3/2)*a % cuboid sides a, b, c breadth = (a+b+c)/2 % tetrahedron side a breadth = 0.9123*a % octaedron side a beradth = 1.175*a % dodecahedron, side a breadth = 15*arctan(2)*a/(2*pi) % icosaehdron, side a breadth = 15*arcsin(2/3)*a/(2*pi) % % Example % [v e f] = createCube; % polyhedronMeanBreadth(v, e, f) % ans = % 1.5 % % See also % meshes3d, meshEdgeFaces, meshDihedralAngles, checkMeshAdjacentFaces % trimeshMeanBreadth % % References % Stoyan D., Kendall W.S., Mecke J. (1995) "Stochastic Geometry and its % Applications", John Wiley and Sons, p. 26 % Ohser, J., Muescklich, F. (2000) "Statistical Analysis of % Microstructures in Materials Sciences", John Wiley and Sons, p.352 % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % compute dihedral angle of each edge alpha = meshDihedralAngles(vertices, edges, faces); % compute length of each edge lengths = meshEdgeLength(vertices, edges); % compute product of length by angles breadth = sum(alpha.*lengths)/(4*pi); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/meshFace.m0000644000000000000000000000013213066736044017507 xustar0030 mtime=1490795556.660870728 30 atime=1490795556.660870728 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/meshFace.m0000644000175000017500000000477413066736044017677 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function face = meshFace(faces, index) %MESHFACE Return the vertex indices of a face in a mesh % % FACE = meshFace(FACES, INDEX) % Return the vertex indices of the i-th face in the face array. This is % mainly an utilitary function that manages faces stored either as int % array (when all faces have same number of sides) or cell array (when % faces may have different number of edges). % % Example % meshFace % % See also % % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2010-10-06, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % process mesh given as structure if isstruct(faces) if isfield(faces, 'faces') faces = faces.faces; else error('Mesh structure should contains a field ''faces'''); end end % switch between numeric or cell array if isnumeric(faces) face = faces(index, :); else face = faces{index}; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/createIcosahedron.m0000644000000000000000000000013213066736044021416 xustar0030 mtime=1490795556.652870579 30 atime=1490795556.652870579 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/createIcosahedron.m0000644000175000017500000000663213066736044021601 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = createIcosahedron() %CREATEICOSAHEDRON Create a 3D mesh representing an Icosahedron. % % MESH = createIcosahedron; % [V, E, F] = createIcosahedron; % Create a solid with 12 vertices, and 20 triangular faces. Faces are % oriented outwards of the mesh. % % [V, F] = createIcosahedron; % Returns only the vertices and the face vertex indices. % % MESH = createIcosahedron; % Returns the data as a mesh structure, with fields 'vertices', 'edges' % and 'faces'. % % Example % [n, e, f] = createIcosahedron; % drawMesh(n, f); % % See also % meshes3d, drawMesh % createCube, createOctahedron, createDodecahedron, createTetrahedron % % --------- % author: David Legland % mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 21/03/2005. % % HISTORY % 2007-01-04 remove unused variables % 2010-12-06 format output, orient normals outwards %% Initialisations theta = 2*pi/5; l = 1/sin(theta/2)/2; z1 = sqrt(1-l*l); t1 = (0:2*pi/5:2*pi*(1-1/5))'; x1 = l*cos(t1); y1 = l*sin(t1); t2 = t1 + 2*pi/10; x2 = l*cos(t2); y2 = l*sin(t2); h = sqrt(l*l-.5*.5); z2 = sqrt(3/4 - (l-h)*(l-h)); %% Create mesh data nodes = [0 0 0;... [x1 y1 repmat(z1, [5 1])]; ... [x2 y2 repmat(z1+z2, [5 1])]; ... 0 0 2*z1+z2]; edges = [... 1 2;1 3;1 4;1 5;1 6; ... 2 3;3 4;4 5;5 6;6 2; ... 2 7;7 3;3 8;8 4;4 9;9 5;5 10;10 6;6 11;11 2; ... 7 8;8 9;9 10;10 11;11 7; ... 7 12;8 12;9 12;10 12;11 12]; % faces are ordered to have normals pointing outside of the mesh faces = [... 1 3 2 ; 1 4 3 ; 1 5 4 ; 1 6 5 ; 1 2 6;... 2 3 7 ; 3 4 8 ; 4 5 9 ; 5 6 10 ; 6 2 11;... 7 3 8 ; 8 4 9 ; 9 5 10 ; 10 6 11 ; 11 2 7;... 7 8 12 ; 8 9 12 ; 9 10 12 ; 10 11 12 ; 11 7 12]; % format output varargout = formatMeshOutput(nargout, nodes, edges, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/sphereMesh.m0000644000000000000000000000013213066736044020077 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/sphereMesh.m0000644000175000017500000000654313066736044020263 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = sphereMesh(sphere, varargin) %SPHEREMESH Create a 3D mesh representing a sphere % % [V, F] = sphereMesh(S) % Creates a 3D mesh representing the sphere S given by [xc yc zy r]. % % [V, F] = sphereMesh(); % Assumes sphere is the unit sphere centered at the origin. % % [V, F] = sphereMesh(S, 'nTheta', NT, 'nPhi', NP); % Specifies the number of discretisation steps for the meridians and the % parallels. % % % Example % s = [10 20 30 40]; % [v f] = sphereMesh(s); % drawMesh(v, f); % view(3);axis equal; light; lighting gouraud; % % See also % meshes3d, drawSphere, ellipsoidMesh, cylinderMesh, surfToMesh % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. if nargin == 0 sphere = [0 0 0 1]; end % number of meridians nPhi = 32; % number of parallels nTheta = 16; % process input arguments while length(varargin) > 1 paramName = varargin{1}; switch lower(paramName) case 'ntheta', nTheta = varargin{2}; case 'nphi', nPhi = varargin{2}; otherwise error(['Could not recognise parameter: ' paramName]); end varargin(1:2) = []; end % extract sphere data xc = sphere(:,1); yc = sphere(:,2); zc = sphere(:,3); r = sphere(:,4); % compute spherical coordinates theta = linspace(0, pi, nTheta+1); phi = linspace(0, 2*pi, nPhi+1); % convert to cartesian coordinates sintheta = sin(theta); x = xc + cos(phi') * sintheta * r; y = yc + sin(phi') * sintheta * r; z = zc + ones(length(phi),1) * cos(theta) * r; % convert to FV mesh [vertices, faces] = surfToMesh(x, y, z, 'yperiodic', true); % format output varargout = formatMeshOutput(nargout, vertices, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/minConvexHull.m0000644000000000000000000000013213066736044020567 xustar0030 mtime=1490795556.664870801 30 atime=1490795556.664870801 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/minConvexHull.m0000644000175000017500000001027713066736044020752 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function faces = minConvexHull(nodes, varargin) %MINCONVEXHULL Return the unique minimal convex hull of a set of 3D points % % FACES = minConvexHull(NODES) % NODES is a set of 3D points (as a Nx3 array). The function computes % the convex hull, and merge contiguous coplanar faces. The result is a % set of polygonal faces, such that there are no coplanar faces. % FACES is a cell array, each cell containing the vector of indices of % nodes given in NODES for the corresponding face. % % FACES = minConvexHull(NODES, PRECISION) % Adjust the threshold for deciding if two faces are coplanar or % parallel. Default value is 1e-14. % % Example % [n e f] = createCube; % f2 = minConvexHull(n); % drawMesh(n, f); % % See also % meshes3d, drawMesh, convhull, convhulln % % % ------ % Author: David Legland % e-mail: david.legland@jouy.inra.fr % Created: 2006-07-05 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). % HISTORY % 20/07/2006 add tolerance for coplanarity test % 21/08/2006 fix small bug due to difference of methods to test % coplanarity, sometimes resulting in 3 points of a face being not % coplanar ! Also add control on precision % 18/09/2007 ensure faces are given as horizontal vectors % set up precision acc = 1e-14; if ~isempty(varargin) acc = varargin{1}; end % triangulated convex hull. It is not uniquely defined. hull = convhulln(nodes); % number of base triangular faces N = size(hull, 1); % compute normals of given faces normals = planeNormal(createPlane(... nodes(hull(:,1),:), nodes(hull(:,2),:), nodes(hull(:,3),:))); % initialize empty faces faces = {}; % Processing flag for each triangle % 1 : triangle to process, 0 : already processed % in the beginning, every triangle face need to be processed flag = ones(N, 1); % iterate on each triangle face for i = 1:N % check if face was already performed if ~flag(i) continue; end % indices of faces with same normal ind = find(abs(vectorNorm3d(cross(repmat(normals(i, :), [N 1]), normals))) end end % compute order of the vertices in current face vertices = unique(hull(ind2, :)); [tmp, I] = angleSort3d(nodes(vertices, :)); %#ok % add a new face to the list face = vertices(I); faces = [faces {face(:)'}]; %#ok % mark processed faces flag(ind2) = 0; end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/intersectLineMesh3d.m0000644000000000000000000000013213066736044021650 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/intersectLineMesh3d.m0000644000175000017500000001056713066736044022035 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [points, pos, faceInds] = intersectLineMesh3d(line, vertices, faces, varargin) %INTERSECTLINEMESH3D Intersection points of a 3D line with a mesh % % INTERS = intersectLineMesh3d(LINE, VERTICES, FACES) % Compute the intersection points between a 3D line and a 3D mesh defined % by vertices and faces. % % [INTERS, POS, INDS] = intersectLineMesh3d(LINE, VERTICES, FACES) % Also returns the position of each intersection point on the input line, % and the index of the intersected faces. % If POS > 0, the point is also on the ray corresponding to the line. % % Example % [V, F] = createCube; % line = [.2 .3 .4 1 0 0]; % pts = intersectLineMesh3d(line, V, F) % pts = % 1.0000 0.3000 0.4000 % 0 0.3000 0.4000 % % See also % meshes3d, triangulateFaces, intersectLineTriangle3d % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2011-12-20, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. % tolerance for detecting if a point is tol = 1e-12; if ~isempty(varargin) tol = varargin{1}; end % ensure the mesh has triangular faces tri2Face = []; if iscell(faces) || size(faces, 2) ~= 3 [faces, tri2Face] = triangulateFaces(faces); end % find triangle edge vectors t0 = vertices(faces(:,1), :); u = vertices(faces(:,2), :) - t0; v = vertices(faces(:,3), :) - t0; % triangle normal n = normalizeVector3d(vectorCross3d(u, v)); % direction vector of line dir = line(4:6); % vector between triangle origin and line origin w0 = bsxfun(@minus, line(1:3), t0); a = -dot(n, w0, 2); b = dot(n, repmat(dir, size(n, 1), 1), 2); valid = abs(b) > tol & vectorNorm3d(n) > tol; % compute intersection point of line with supporting plane % If pos < 0: point before ray % IF pos > |dir|: point after edge pos = a ./ b; % coordinates of intersection point points = bsxfun(@plus, line(1:3), bsxfun(@times, pos, dir)); %% test if intersection point is inside triangle % normalize direction vectors of triangle edges uu = dot(u, u, 2); uv = dot(u, v, 2); vv = dot(v, v, 2); % coordinates of vector v in triangle basis w = points - t0; wu = dot(w, u, 2); wv = dot(w, v, 2); % normalization constant D = uv.^2 - uu .* vv; % test first coordinate s = (uv .* wv - vv .* wu) ./ D; % ind1 = s < 0.0 | s > 1.0; ind1 = s < -tol | s > (1.0 + tol); points(ind1, :) = NaN; pos(ind1) = NaN; % test second coordinate, and third triangle edge t = (uv .* wu - uu .* wv) ./ D; % ind2 = t < 0.0 | (s + t) > 1.0; ind2 = t < -tol | (s + t) > (1.0 + tol); points(ind2, :) = NaN; pos(ind2) = NaN; % keep only interesting points inds = ~ind1 & ~ind2 & valid; points = points(inds, :); pos = pos(inds); faceInds = find(inds); % convert to face indices of original mesh if ~isempty(tri2Face) faceInds = tri2Face(faceInds); end geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/cylinderMesh.m0000644000000000000000000000013213066736044020422 xustar0030 mtime=1490795556.656870653 30 atime=1490795556.656870653 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/cylinderMesh.m0000644000175000017500000000663413066736044020607 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = cylinderMesh(cyl, varargin) %CYLINDERMESH Create a 3D mesh representing a cylinder % % [V F] = cylinderMesh(CYL) % Computes vertex coordinates and face vertex indices of a mesh % representing a 3D cylinder given as [X1 Y1 Z1 X2 Y2 Z2 R]. % % Example % % Draw a rotated cylinder % cyl = [0 0 0 10 20 30 5]; % [v f] = cylinderMesh(cyl); % figure;drawMesh(v, f, 'FaceColor', 'r'); % view(3); axis equal; % % % Draw three mutually intersecting cylinders % p0 = [30 30 30]; % p1 = [90 30 30]; % p2 = [30 90 30]; % p3 = [30 30 90]; % [v1 f1] = cylinderMesh([p0 p1 25]); % [v2 f2] = cylinderMesh([p0 p2 25]); % [v3 f3] = cylinderMesh([p0 p3 25]); % figure; hold on; % drawMesh(v1, f1, 'FaceColor', 'r'); % drawMesh(v2, f2, 'FaceColor', 'g'); % drawMesh(v3, f3, 'FaceColor', 'b'); % view(3); axis equal % set(gcf, 'renderer', 'opengl') % % See also % drawCylinder, torusMesh, sphereMesh % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. % extract cylinder data p1 = cyl(:, 1:3); p2 = cyl(:, 4:6); r = cyl(:, 7); % compute length and orientation [theta, phi, rho] = cart2sph2d(p2 - p1); % parametrisation on x t = linspace(0, 2*pi, 20); lx = r * cos(t); ly = r * sin(t); % parametrisation on z lz = linspace(0, rho, 10); % generate surface grids x = repmat(lx, [length(lz) 1]); y = repmat(ly, [length(lz) 1]); z = repmat(lz', [1 length(t)]); % transform points trans = localToGlobal3d(p1, theta, phi, 0); [x, y, z] = transformPoint3d(x, y, z, trans); % convert to FV mesh [vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', true); % format output varargout = formatMeshOutput(nargout, vertices, faces); geometry-3.0.0/inst/meshes3d/PaxHeaders.28738/steinerPolytope.m0000644000000000000000000000013213066736044021201 xustar0030 mtime=1490795556.668870876 30 atime=1490795556.668870876 30 ctime=1490795556.716871764 geometry-3.0.0/inst/meshes3d/steinerPolytope.m0000644000175000017500000000646313066736044021366 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [vertices, faces] = steinerPolytope(vectors) %STEINERPOLYTOPE Create a steiner polytope from a set of vectors % % [VERTICES FACES] = steinerPolygon(VECTORS) % Creates the Steiner polytope defined by the set of vectors VECTORS. % % Example % % Creates and display a planar Steiner polytope (ie, a polygon) % [v f] = steinerPolytope([1 0;0 1;1 1]); % fillPolygon(v); % % % Creates and display a 3D Steiner polytope % [v f] = steinerPolytope([1 0 0;0 1 0;0 0 1;1 1 1]); % drawMesh(v, f); % view(3); axis vis3d % % See also % meshes3d, drawMesh, steinerPolygon, mergeCoplanarFaces % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2006-04-28 % Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). % History % 2013-02-22 merge coplanar faces, add management of 2D case, update doc % compute vectors dimension nd = size(vectors, 2); % create candidate vertices vertices = zeros(1, size(vectors, 2)); for i = 1:length(vectors) nv = size(vertices, 1); vertices = [vertices; vertices+repmat(vectors(i,:), [nv 1])]; %#ok end if nd == 2 % for planar case, use specific function convhull K = convhull(vertices(:,1), vertices(:,2)); vertices = vertices(K, :); faces = 1:length(K); else % Process the general case (tested only for nd==3) % compute convex hull K = convhulln(vertices); % keep only relevant points, and update faces indices ind = unique(K); for i = 1:length(ind) K(K==ind(i)) = i; end % return results vertices = vertices(ind, :); faces = K; % in case of 3D meshes, merge coplanar faces if nd == 3 faces = mergeCoplanarFaces(vertices, faces); end end geometry-3.0.0/inst/PaxHeaders.28738/utils0000644000000000000000000000013113066736044015165 xustar0029 mtime=1490795556.69287132 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/utils/0002755000175000017500000000000013066736044015421 5ustar00olafolaf00000000000000geometry-3.0.0/inst/utils/PaxHeaders.28738/isAxisHandle.m0000644000000000000000000000013013066736044017773 xustar0029 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 geometry-3.0.0/inst/utils/isAxisHandle.m0000644000175000017500000000451313066736044020154 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function b = isAxisHandle(arg) %ISAXISHANDLE Check if the input corresponds to a valid axis hanfle % % B = isAxisHandle(VAR) % If the value of VAR is scalar, corresponds to a valid matlab handle, % and has type equal to 'axis', then returns TRUE. Otherwise, returns % false. % This function is used to check if first argument of drawing functions % corresponds to data or to axis handle to draw in. % % Example % isAxisHandle(gca) % ans = % 1 % % See also % drawPoint, drawLine, drawEdge % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-09-21, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. b = isscalar(arg) && ishandle(arg) && strcmp(get(arg, 'type'), 'axes'); geometry-3.0.0/inst/PaxHeaders.28738/__geometry_package_register__.m0000644000000000000000000000013213066736044022267 xustar0030 mtime=1490795556.560868878 30 atime=1490795556.560868878 30 ctime=1490795556.716871764 geometry-3.0.0/inst/__geometry_package_register__.m0000644000175000017500000000272013066736044022444 0ustar00olafolaf00000000000000## Copyright (C) 2016 Carnë Draug ## ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 3 of the ## License, or (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, see ## . ## -*- texinfo -*- ## @deftypefn {} {} __geometry_package_register__ () ## Undocumented internal function of geometry package. ## @end deftypefn ## PKG_ADD: __geometry_package_register__ (1); ## PKG_DEL: __geometry_package_register__ (-1); function subdir_paths = __geometry_package_register__ (loading = 0) subdirlist = {"utils", "geom2d","io","polygons2d","shape2d", "graphs",... "geom3d","meshes3d","polynomialCurves2d"}; ## Get full path, with luck we can retreive the package name from here base_pkg_path = fileparts (make_absolute_filename (mfilename ("fullpath"))); subdir_paths = fullfile (base_pkg_path, subdirlist); if (loading > 0) addpath (subdir_paths{:}); elseif (loading < 0) rmpath (subdir_paths{:}); endif endfunction geometry-3.0.0/inst/PaxHeaders.28738/geom3d0000644000000000000000000000013113066736044015203 xustar0029 mtime=1490795556.63287021 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/0002755000175000017500000000000013066736044015437 5ustar00olafolaf00000000000000geometry-3.0.0/inst/geom3d/PaxHeaders.28738/lines3d.m0000644000000000000000000000013213066736044017000 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/lines3d.m0000644000175000017500000000375313066736044017164 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} lines3d () ##LINES3D Description of functions operating on 3D lines ## ## A 3D Line is represented by a 3D point (its origin) and a 3D vector ## (its direction): ## LINE = [X0 Y0 Z0 DX DY DZ]; ## ## @seealso{createLine3d, transformLine3d, distancePointLine3d, linePosition3d ## intersectLinePlane, distanceLines3d, clipLine3d, drawLine3d} ## @end deftypefn function lines3d() help lines3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createTranslation3d.m0000644000000000000000000000013213066736044021350 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createTranslation3d.m0000644000175000017500000000543613066736044021534 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{} =} createTranslation3d (@var{dx}, @var{dy}, @var{dz}) ## @deftypefnx {Function File} {@var{} =} createTranslation3d (@var{vect}) ## Create the 4x4 matrix of a 3D translation ## ## usage: ## TRANS = createTranslation3d(DX, DY, DZ); ## return the translation corresponding to DX and DY. ## The returned matrix has the form : ## [1 0 0 DX] ## [0 1 0 DY] ## [0 0 1 DZ] ## [0 0 0 1] ## ## TRANS = createTranslation3d(VECT); ## return the translation corresponding to the given vector [x y z]. ## ## @seealso{transforms3d, transformPoint3d, transformVector3d, ## createRotationOx, createRotationOy, createRotationOz, createScaling3d} ## @end deftypefn function trans = createTranslation3d(varargin) if isempty(varargin) # assert translation with null vector dx = 0; dy = 0; dz = 0; elseif length(varargin)==1 # translation vector given in a single argument var = varargin{1}; dx = var(1); dy = var(2); dz = var(3); else # translation vector given in 3 arguments dx = varargin{1}; dy = varargin{2}; dz = varargin{3}; end # create the translation matrix trans = [1 0 0 dx ; 0 1 0 dy ; 0 0 1 dz; 0 0 0 1]; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/boundingBox3d.m0000644000000000000000000000013013066736044020142 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/boundingBox3d.m0000644000175000017500000000545313066736044020327 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{box} =} boundingBox3d (@var{points}) ## Bounding box of a set of 3D points ## ## Returns the bounding box of the set of points POINTS. POINTS is a ## N-by-3 array containing points coordinates. The result BOX is a 1-by-6 ## array, containing: ## [XMIN XMAX YMIN YMAX ZMIN ZMAX] ## ## Example ## @group ## # Draw bounding box of a cubeoctehedron ## [v e f] = createCubeOctahedron; ## box3d = boundingBox3d(v); ## figure; hold on; ## drawMesh(v, f); ## drawBox3d(box3d); ## axis([-2 2 -2 2 -2 2]); ## view(3) ## @end group ## ## @seealso{boxes3d, drawBox3d} ## @end deftypefn function box = boundingBox3d(points) # compute extreme x and y values xmin = min(points(:,1)); xmax = max(points(:,1)); ymin = min(points(:,2)); ymax = max(points(:,2)); box = [xmin xmax ymin ymax]; # process case of 3D points if size(points, 2) > 2 zmin = min(points(:,3)); zmax = max(points(:,3)); box = [xmin xmax ymin ymax zmin zmax]; end endfunction %!demo %! # Draw bounding box of a cubeoctehedron %! [v e f] = createCubeOctahedron; %! box3d = boundingBox3d(v); %! figure; hold on; %! drawMesh(v, f); %! drawBox3d(box3d); %! axis([-2 2 -2 2 -2 2]); %! view(3) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/clipLine3d.m0000644000000000000000000000013013066736044017423 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/clipLine3d.m0000644000175000017500000001011513066736044017577 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %CLIPLINE3D Clip a line with a box and return an edge % % EDGE = clipLine3d(LINE, BOX); % Clips the line LINE with the bounds given in BOX, and returns the % corresponding edge. % % If the line lies totally outside of the box, returns a 1-by-6 row array % containing only NaN's. % % If LINE is a N-by-6 array, with one line by row, returns the clipped % edge coresponding to each line in a N-by-6 array. % % See also: % lines3d, edges3d, createLine3d function edge = clipLine3d(line, box) % get box limits xmin = box(1); xmax = box(2); ymin = box(3); ymax = box(4); zmin = box(5); zmax = box(6); % extreme corners of the box p000 = [xmin ymin zmin]; p111 = [xmax ymax zmax]; % main vectors ex = [1 0 0]; ey = [0 1 0]; ez = [0 0 1]; % box faces parallel to Oxy planeZ0 = [p000 ex ey]; planeZ1 = [p111 ex ey]; % box faces parallel to Oxz planeY0 = [p000 ex ez]; planeY1 = [p111 ex ez]; % box faces parallel to Oyz planeX0 = [p000 ey ez]; planeX1 = [p111 ey ez]; % number of lines Nl = size(line, 1); % allocate memory for result edge = zeros(Nl, 6); % process each line for i=1:Nl % compute intersection point with each plane ipZ0 = intersectLinePlane(line(i,:), planeZ0); ipZ1 = intersectLinePlane(line(i,:), planeZ1); ipY0 = intersectLinePlane(line(i,:), planeY0); ipY1 = intersectLinePlane(line(i,:), planeY1); ipX1 = intersectLinePlane(line(i,:), planeX1); ipX0 = intersectLinePlane(line(i,:), planeX0); % concatenate resulting points points = [ipX0;ipX1;ipY0;ipY1;ipZ0;ipZ1]; % compute position of each point on the line pos = linePosition3d(points, line(i,:)); % keep only defined points ind = find(~isnan(pos)); pos = pos(ind); points = points(ind,:); % sort points with respect to their position [pos, ind] = sort(pos); %#ok points = points(ind, :); % keep median points wrt to position. These points define the limit of % the clipped edge. nv = length(ind)/2; % create resulting edge. edge(i,:) = [points(nv, :) points(nv+1, :)]; end % check that middle point of the edge is contained in the box midX = mean(edge(:, [1 4]), 2); xOk = xmin <= midX & midX <= xmax; midY = mean(edge(:, [2 5]), 2); yOk = ymin <= midY & midY <= ymax; midZ = mean(edge(:, [3 6]), 2); zOk = zmin <= midZ & midZ <= zmax; % if one of the bounding condition is not met, set edge to NaN edge (~(xOk & yOk & zOk), :) = NaN; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createRotationOx.m0000644000000000000000000000013213066736044020731 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createRotationOx.m0000644000175000017500000000672613066736044021120 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{trans} =} createRotationOx (@var{theta}) ## @deftypefnx {Function File} {@var{trans} =} createRotationOx (@var{origin},@var{theta}) ## @deftypefnx {Function File} {@var{trans} =} createRotationOx (@var{x0},@var{y0},@var{z0},@var{theta}) ## Create the 4x4 matrix of a 3D rotation around x-axis ## ## TRANS = createRotationOx(THETA); ## Returns the transform matrix corresponding to a rotation by the angle ## THETA (in radians) around the Ox axis. A rotation by an angle of PI/2 ## would transform the vector [0 1 0] into the vector [0 0 1]. ## ## The returned matrix has the form: ## [1 0 0 0] ## [0 cos(THETA) -sin(THETA) 0] ## [0 sin(THETA) cos(THETA) 0] ## [0 0 0 1] ## ## TRANS = createRotationOx(ORIGIN, THETA); ## TRANS = createRotationOx(X0, Y0, Z0, THETA); ## Also specifies origin of rotation. The result is similar as performing ## translation(-X0, -Y0, -Z0), rotation, and translation(X0, Y0, Z0). ## ## @seealso{transforms3d, transformPoint3d, createRotationOy, createRotationOz} ## @end deftypefn function trans = createRotationOx(varargin) # default values dx = 0; dy = 0; dz = 0; theta = 0; # get input values if length(varargin)==1 # only angle theta = varargin{1}; elseif length(varargin)==2 # origin point (as array) and angle var = varargin{1}; dx = var(1); dy = var(2); dz = var(3); theta = varargin{2}; elseif length(varargin)==3 # origin (x and y) and angle dx = varargin{1}; dy = varargin{2}; dz = varargin{3}; theta = varargin{3}; end # compute coefs cot = cos(theta); sit = sin(theta); # create transformation trans = [... 1 0 0 0;... 0 cot -sit 0;... 0 sit cot 0;... 0 0 0 1]; # add the translation part t = [1 0 0 dx;0 1 0 dy;0 0 1 dz;0 0 0 1]; trans = t*trans/t; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/distancePoints.m0000644000000000000000000000013213066736044020426 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/distancePoints.m0000644000175000017500000001365113066736044020610 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{d} =} distancePoints(@var{p1}, @var{p2}) ## @deftypefnx {Function File} {@var{d} =} distancePoints(@var{p1}, @var{p2},@var{norm}) ## @deftypefnx {Function File} {@var{d} = } distancePoints (@dots{}, @asis{'diag'}) ## Compute euclidean distance between pairs of points in any dimension ## ## Return distance @var{d} between points @var{p1} and ## @var{p2}, given as [X Y Z @dots{} Wdim]. ## ## If @var{p1} and @var{p2} are two arrays of points, result is a N1-by-N2 array ## containing distance between each point of @var{p1} and each point of @var{p2}. ## ## ## @var{d} = distancePoints(@var{p1}, @var{p2}, @var{norm}) ## with @var{norm} being 1, 2, or Inf, corresponfing to the norm used. Default is ## 2 (euclidean norm). 1 correspond to manhattan (or taxi driver) distance ## and Inf to maximum difference in each coordinate. ## ## When 'diag' is given, computes only distances between @code{@var{p1}(i,:)} and @code{@var{p2}(i,:)}. ## In this case the numer of points in each array must be the same. ## ## @seealso{points3d, minDistancePoints} ## @end deftypefn function dist = distancePoints(p1, p2, varargin) norm = 2; diagonal = false; switch numel(varargin) case 0 1; case 1 if isnumeric (varargin{1}) norm = varargin{1}; else diagonal = true; end case 2 norm = varargin{1}; diagonal = true; otherwise print_usage; end # compute difference of coordinate for each all points [n1 dim] = size(p1); [n2 dim] = size(p2); if diagonal if n1 ~= n2 error ("geometry:InvalidArgument",... "When option diag is given the number of points must be equal.\n"); end ptsDiff = p2 - p1; else ptsDiff = zeros (n1,n2,dim); for i =1:dim ptsDiff(:,:,i) = p2(:,i)' - p1(:,i); end end # Return dist based on the type of measurement requested along_dim = length(size(ptsDiff)); switch(norm) case 1 dist = sum(abs(ptsDiff), along_dim); case 2 if ~diagonal dist = reshape(vectorNorm (reshape(ptsDiff,n1*n2,dim)),n1,n2); else dist = vectorNorm (ptsDiff); end case Inf dist = max(abs(ptsDiff), [], along_dim); otherwise dist = sum(ptsDiff.^norm, along_dim).^(1/norm); end endfunction %!shared pt1,pt2,pt3,pt4 %! pt1 = [10 10]; %! pt2 = [10 20]; %! pt3 = [20 20]; %! pt4 = [20 10]; %!assert (distancePoints(pt1, pt2), 10, 1e-6); %!assert (distancePoints(pt2, pt3), 10, 1e-6); %!assert (distancePoints(pt1, pt3), 10*sqrt(2), 1e-6); %!assert (distancePoints(pt1, pt2, 1), 10, 1e-6); %!assert (distancePoints(pt2, pt3, 1), 10, 1e-6); %!assert (distancePoints(pt1, pt3, 1), 20, 1e-6); %!assert (distancePoints(pt1, pt2, inf), 10, 1e-6); %!assert (distancePoints(pt2, pt3, inf), 10, 1e-6); %!assert (distancePoints(pt1, pt3, inf), 10, 1e-6); %!assert (distancePoints(pt1, [pt1; pt2; pt3]), [0 10 10*sqrt(2)], 1e-6); %!test %! array1 = [pt1;pt2;pt3]; %! array2 = [pt1;pt2;pt3;pt4]; %! res = [0 10 10*sqrt(2) 10; 10 0 10 10*sqrt(2); 10*sqrt(2) 10 0 10]; %! assert (distancePoints(array1, array2), res, 1e-6); %! assert (distancePoints(array2, array2, 'diag'), [0;0;0;0], 1e-6); %!test %! array1 = [pt1;pt2;pt3]; %! array2 = [pt2;pt3;pt1]; %! assert (distancePoints(array1, array2, inf, 'diag'), [10;10;10], 1e-6); %!shared pt1,pt2,pt3,pt4 %! pt1 = [10 10 10]; %! pt2 = [10 20 10]; %! pt3 = [20 20 10]; %! pt4 = [20 20 20]; %!assert (distancePoints(pt1, pt2), 10, 1e-6); %!assert (distancePoints(pt2, pt3), 10, 1e-6); %!assert (distancePoints(pt1, pt3), 10*sqrt(2), 1e-6); %!assert (distancePoints(pt1, pt4), 10*sqrt(3), 1e-6); %!assert (distancePoints(pt1, pt2, inf), 10, 1e-6); %!assert (distancePoints(pt2, pt3, inf), 10, 1e-6); %!assert (distancePoints(pt1, pt3, inf), 10, 1e-6); %!assert (distancePoints(pt1, pt4, inf), 10, 1e-6); %!shared pt1,pt2,pt3,pt4 %! pt1 = [10 10 30]; %! pt2 = [10 20 30]; %! pt3 = [20 20 30]; %! pt4 = [20 20 40]; %!assert (distancePoints(pt1, pt2, 1), 10, 1e-6); %!assert (distancePoints(pt2, pt3, 1), 10, 1e-6); %!assert (distancePoints(pt1, pt3, 1), 20, 1e-6); %!assert (distancePoints(pt1, pt4, 1), 30, 1e-6); %!test %! array1 = [pt1;pt2;pt3]; %! array2 = [pt2;pt3;pt1]; %! assert (distancePoints(array1, array2, 'diag'), [10;10;10*sqrt(2)], 1e-6); %! assert (distancePoints(array1, array2, 1, 'diag'), [10;10;20], 1e-6); geometry-3.0.0/inst/geom3d/PaxHeaders.28738/vectorAngle3d.m0000644000000000000000000000013013066736044020135 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/vectorAngle3d.m0000644000175000017500000000501013066736044020307 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{theta} =} vectorAngle3d (@var{v1}, @var{v2}) ## Angle between two 3D vectors ## ## THETA = vectorAngle3d(V1, V2) ## Computes the angle between the 2 3D vectors V1 and V2. The result THETA ## is given in radians, between 0 and PI. ## ## ## Example ## # angle between 2 orthogonal vectors ## vectorAngle3d([1 0 0], [0 1 0]) ## ans = ## 1.5708 ## ## # angle between 2 parallel vectors ## v0 = [3 4 5]; ## vectorAngle3d(3*v0, 5*v0) ## ans = ## 0 ## ## @seealso{vectors3d, vectorNorm} ## @end deftypefn function theta = vectorAngle3d(v1, v2) # compute angle using arc-tangent to get better precision for angles near # zero, see the discussion in: # http://www.mathworks.com/matlabcentral/newsreader/view_thread/151925#381952 # equivalent to: # v1 = normalizeVector(v1); # v2 = normalizeVector(v2); # theta = acos(dot(v1, v2, 2)); theta = atan2(vectorNorm(cross (v1, v2)), sum(v1.*v2,2)); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/sph2cart2d.m0000644000000000000000000000013013066736044017411 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/sph2cart2d.m0000644000175000017500000000651613066736044017577 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{c} =} sph2cart2d(@var{theta}, @var{phi}, @var{rho}) ## @deftypefnx {Function File} {@var{c} =} sph2cart2d(@var{theta}, @var{phi}) ## @deftypefnx {Function File} {@var{c} =} sph2cart2d(@var{s}) ## @deftypefnx {Function File} {[@var{x},@var{y},@var{z}] =} sph2cart2d(@var{theta}, @var{phi}, @var{rho}) ## Convert spherical coordinates to cartesian coordinates in degrees ## ## ## @var{c} = SPH2CART2(@var{theta}, @var{phi}) assumes @var{rho} = 1. ## ## @var{s} = [@var{theta}, @var{phi}, @var{rho}] (spherical coordinate). ## @var{c} = [@var{x},@var{y},@var{z}] (cartesian coordinate) ## ## The following convention is used: ## @var{theta} is the colatitude, in degrees, 0 for north pole, +180 degrees for ## south pole, +90 degrees for points with z=0. ## @var{phi} is the azimuth, in degrees, defined as matlab cart2sph: angle from ## Ox axis, counted counter-clockwise. ## @var{rho} is the distance of the point to the origin. ## Discussion on choice for convention can be found at: ## @url{http://www.physics.oregonstate.edu/bridge/papers/spherical.pdf} ## ## @seealso{angles3d, cart2sph2d, sph2cart2} ## @end deftypefn function varargout = sph2cart2d(theta, phi, rho) # Process input arguments if nargin == 1 phi = theta(:, 2); if size(theta, 2) > 2 rho = theta(:, 3); else rho = ones(size(phi)); end theta = theta(:, 1); elseif nargin == 2 rho = ones(size(theta)); end # conversion rz = rho .* sind(theta); x = rz .* cosd(phi); y = rz .* sind(phi); z = rho .* cosd(theta); # Process output arguments if nargout == 1 || nargout == 0 varargout{1} = [x, y, z]; else varargout{1} = x; varargout{2} = y; varargout{3} = z; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/sph2cart2.m0000644000000000000000000000013013066736044017245 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/sph2cart2.m0000644000175000017500000000633213066736044017427 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{c} =} sph2cart2 (@var{s}) ## @deftypefnx {Function File} {@var{c} =} sph2cart2 (@var{theta}, @var{phi}) ## @deftypefnx {Function File} {@var{c} =} sph2cart2 (@var{theta}, @var{phi}, @var{rho}) ## @deftypefnx {Function File} {[@var{x} @var{y} @var{z}]=} sph2cart2 (@dots{}) ## Convert spherical coordinates to cartesian coordinates ## ## C = SPH2CART2(S) ## C = SPH2CART2(THETA, PHI) (assume rho = 1) ## C = SPH2CART2(THETA, PHI, RHO) ## [X, Y, Z] = SPH2CART2(THETA, PHI, RHO); ## ## S = [phi theta rho] (spherical coordinate). ## C = [X Y Z] (cartesian coordinate) ## ## The following convention is used: ## THETA is the colatitude, in radians, 0 for north pole, +pi for south ## pole, pi/2 for points with z=0. ## PHI is the azimuth, in radians, defined as matlab cart2sph: angle from ## Ox axis, counted counter-clockwise. ## RHO is the distance of the point to the origin. ## Discussion on choice for convention can be found at: ## http://www.physics.oregonstate.edu/bridge/papers/spherical.pdf ## ## @seealso{angles3d, cart2sph2, sph2cart, sph2cart2d} ## @end deftypefn function varargout = sph2cart2(theta, phi, rho) # Process input arguments if nargin == 1 phi = theta(:, 2); if size (theta, 2) > 2 rho = theta(:, 3); else rho = ones (size (phi)); end theta = theta(:, 1); elseif nargin == 2 rho = ones (size (theta)); end # conversion rz = rho .* sin(theta); x = rz .* cos(phi); y = rz .* sin(phi); z = rho .* cos(theta); if nargout <= 1 varargout{1} = [x, y, z]; else varargout{1} = x; varargout{2} = y; varargout{3} = z; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawVector3d.m0000644000000000000000000000013213066736044020006 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawVector3d.m0000644000175000017500000000445413066736044020171 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} function_name (@var{pos}, @var{vect}) ## Draw vector at a given position ## ## Example ## @example ## figure; hold on; ## drawVector3d([2 3 4], [1 0 0]); ## drawVector3d([2 3 4], [0 1 0]); ## drawVector3d([2 3 4], [0 0 1]); ## view(3); ## @end example ## ## @seealso{quiver3} ## @end deftypefn function varargout = drawVector3d(pos, vect, varargin) h = quiver3 (pos(:, 1), pos(:, 2), pos(:, 3), ... vect(:, 1), vect(:, 2), vect(:, 3), varargin{:}); # format output if nargout > 0 varargout{1} = h; end endfunction %!demo %! figure; hold on; %! drawVector3d([2 3 4], [1 0 0]); %! drawVector3d([2 3 4], [0 1 0]); %! drawVector3d([2 3 4], [0 0 1]); %! view(3); geometry-3.0.0/inst/geom3d/PaxHeaders.28738/recenterTransform3d.m0000644000000000000000000000013213066736044021371 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/recenterTransform3d.m0000644000175000017500000000512013066736044021543 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %RECENTERTRANSFORM3D Change the fixed point of an affine 3D transform % % TRANSFO2 = recenterTransform3d(TRANSFO, CENTER) % where TRANSFO is a 4x4 transformation matrix, and CENTER is a 1x3 row % vector, computes the new transformations that uses the same linear part % (defined by the upper-left 3x3 corner of the transformation matrix) as % the initial transform, and that will leave the point CENTER unchanged. % % % % Example % % creating a re-centered rotation using: % rot1 = createRotationOx(pi/3); % rot2 = recenterTransform3d(rot1, [3 4 5]); % % will give the same result as: % rot3 = createRotationOx([3 4 5], pi/3); % % % See also % transforms3d, createRotationOx, createRotationOy, createRotationOz % createTranslation3d function res = recenterTransform3d(transfo, center) % remove former translation part res = eye(4); res(1:3, 1:3) = transfo(1:3, 1:3); % create translations t1 = createTranslation3d(-center); t2 = createTranslation3d(center); % compute translated transform res = t2*res*t1; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawCube.m0000644000000000000000000000013213066736044017173 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawCube.m0000644000175000017500000001065313066736044017354 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawCube (@var{cube}) ## @deftypefnx {Function File} {[@var{x},@var{y},@var{z}] =} drawCube (@var{cube}) ## Draw a 3D centered cube, eventually rotated ## ## drawCube(CUBE) ## Displays a 3D cube on current axis. CUBE is given by: ## [XC YC ZC SIDE THETA PHI PSI] ## where (XC, YC, ZC) is the CUBE center, SIDE is the length of the cube ## main sides, and THETA PHI PSI are angles representing the cube ## orientation, in degrees. THETA is the colatitude of the cube, between 0 ## and 90 degrees, PHI is the longitude, and PSI is the rotation angle ## around the axis of the normal. ## ## CUBE can be axis aligned, in this case it should only contain center ## and side information: ## CUBE = [XC YC ZC SIDE] ## ## The function drawCuboid is closely related, but uses a different angle ## convention, and allows for different sizes along directions. ## ## Example ## @example ## # Draw a cube with small rotations ## figure; hold on; ## drawCube([10 20 30 50 10 20 30], 'FaceColor', 'g'); ## axis equal; ## view(3); ## @end example ## ## WARNING: This function doesn't work in gnuplot (as of version 4.2). ## ## @seealso{meshes3d, polyhedra, createCube, drawCuboid} ## @end deftypefn function varargout = drawCube(cube, varargin) # default values theta = 0; phi = 0; psi = 0; ## Parses the input if nargin == 0 # no input: assumes cube with default shape xc = 0; yc = 0; zc = 0; a = 1; else # one argument: parses elements xc = cube(:,1); yc = cube(:,2); zc = cube(:,3); a = cube(:,4); # parses orientation if present k = pi / 180; if size(cube, 2) >= 6 theta = cube(:,5) * k; phi = cube(:,6) * k; end if size(cube, 2) >= 7 psi = cube(:,7) * k; end end ## Compute cube coordinates # create unit centered cube [v f] = createCube; v = bsxfun(@minus, v, mean(v, 1)); # convert unit basis to cube basis sca = createScaling3d (a); rot1 = createRotationOz (psi); rot2 = createRotationOy (theta); rot3 = createRotationOz (phi); tra = createTranslation3d ([xc yc zc]); # concatenate transforms trans = tra * rot3 * rot2 * rot1 * sca; # transform mesh vertices [x y z] = transformPoint3d (v, trans); ## Process output if nargout == 0 # no output: draw the cube drawMesh ([x y z], f, varargin{:}); elseif nargout == 1 # one output: draw the cube and return handle varargout{1} = drawMesh ([x y z], f, varargin{:}); elseif nargout == 3 # 3 outputs: return computed coordinates varargout{1} = x; varargout{2} = y; varargout{3} = z; end endfunction %!demo %! # Draw a cube with small rotations %! figure; hold on; %! drawCube([10 20 30 50 10 20 30], 'FaceColor', 'g'); %! axis equal; %! view(3); geometry-3.0.0/inst/geom3d/PaxHeaders.28738/spheres.m0000644000000000000000000000013013066736044017106 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/spheres.m0000644000175000017500000000446213066736044017272 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} spheres () ## Description of functions operating on 3D spheres ## ## Spheres are represented by their center and their radius: ## S = [xc yc zc r]; ## ## An ellipsoid is defined by: ## ELL = [XC YC ZC A B C PHI THETA PSI] ## where [XC YC ZY] is the center, [A B C] are length of semi-axes (in ## decreasing order), and [PHI THETA PSI] are euler angles representing ## the ellipsoid orientation. ## @seealso{createSphere, inertiaEllipsoid, intersectLineSphere, ## intersectPlaneSphere, sphericalVoronoiDomain, drawSphere, drawEllipsoid, ## drawSphericalEdge, drawSphericalTriangle, drawSphericalPolygon, ## fillSphericalTriangle, fillSphericalPolygon} ## @end deftypefn function spheres(varargin) help spheres endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawPlane3d.m0000644000000000000000000000013213066736044017603 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawPlane3d.m0000644000175000017500000001170413066736044017762 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function varargout = drawPlane3d(plane, varargin) %DRAWPLANE3D Draw a plane clipped in the current window % % drawPlane3d(plane) % plane = [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2]; % % See also % planes3d, createPlane % % Example % p0 = [1 2 3]; % v1 = [1 0 1]; % v2 = [0 -1 1]; % plane = [p0 v1 v2]; % axis([-10 10 -10 10 -10 10]); % drawPlane3d(plane) % drawLine3d([p0 v1]) % drawLine3d([p0 v2]) % set(gcf, 'renderer', 'zbuffer'); % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % INRA - TPV URPOI - BIA IMASTE % created the 17/02/2005. % % HISTORY % 2008-10-30 replace intersectPlaneLine by intersectLinePlane, add doc % 2010-10-04 fix a bug for planes touching box by one corner % 2011-07-19 fix a bug for param by Xin KANG (Ben) % % default display options = {'FaceColor', 'm'}; % parse input arguments if any if ~isempty(varargin) options = varargin; % if options are specified as struct, need to convert to parameter % name-value pairs if isstruct(options{1}) s = options{1}; options = [fieldnames(s) struct2cell(s)]'; options = options(:)'; end end % extract axis bounds to crop plane lim = get(gca, 'xlim'); xmin = lim(1); xmax = lim(2); lim = get(gca, 'ylim'); ymin = lim(1); ymax = lim(2); lim = get(gca, 'zlim'); zmin = lim(1); zmax = lim(2); % create lines corresponding to cube edges lineX00 = [xmin ymin zmin 1 0 0]; lineX01 = [xmin ymin zmax 1 0 0]; lineX10 = [xmin ymax zmin 1 0 0]; lineX11 = [xmin ymax zmax 1 0 0]; lineY00 = [xmin ymin zmin 0 1 0]; lineY01 = [xmin ymin zmax 0 1 0]; lineY10 = [xmax ymin zmin 0 1 0]; lineY11 = [xmax ymin zmax 0 1 0]; lineZ00 = [xmin ymin zmin 0 0 1]; lineZ01 = [xmin ymax zmin 0 0 1]; lineZ10 = [xmax ymin zmin 0 0 1]; lineZ11 = [xmax ymax zmin 0 0 1]; % compute intersection points with each plane piX00 = intersectLinePlane(lineX00, plane); piX01 = intersectLinePlane(lineX01, plane); piX10 = intersectLinePlane(lineX10, plane); piX11 = intersectLinePlane(lineX11, plane); piY00 = intersectLinePlane(lineY00, plane); piY01 = intersectLinePlane(lineY01, plane); piY10 = intersectLinePlane(lineY10, plane); piY11 = intersectLinePlane(lineY11, plane); piZ00 = intersectLinePlane(lineZ00, plane); piZ01 = intersectLinePlane(lineZ01, plane); piZ10 = intersectLinePlane(lineZ10, plane); piZ11 = intersectLinePlane(lineZ11, plane); % concatenate points into one array points = [... piX00;piX01;piX10;piX11; ... piY00;piY01;piY10;piY11; ... piZ00;piZ01;piZ10;piZ11;]; % check validity: keep only points inside window (with tolerance) ac = 1e-14; ivx = points(:,1) >= xmin-ac & points(:,1) <= xmax+ac; ivy = points(:,2) >= ymin-ac & points(:,2) <= ymax+ac; ivz = points(:,3) >= zmin-ac & points(:,3) <= zmax+ac; valid = ivx & ivy & ivz; pts = unique(points(valid, :), 'rows'); % If there is no intersection point, escape. if size(pts, 1) < 3 disp('plane is outside the drawing window'); return; end % the two spanning lines of the plane d1 = plane(:, [1:3 4:6]); d2 = plane(:, [1:3 7:9]); % position of intersection points in plane coordinates u1 = linePosition3d(pts, d1); u2 = linePosition3d(pts, d2); % reorder vertices in the correct order ind = convhull(u1, u2); ind = ind(1:end-1); % draw the patch h = patch('XData', pts(ind, 1), 'YData', pts(ind, 2), 'ZData', pts(ind, 3)); set(h, options{:}); % return handle to plane if needed if nargout > 0 varargout = {h}; end geometry-3.0.0/inst/geom3d/PaxHeaders.28738/angles3d.m0000644000000000000000000000013213066736044017137 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/angles3d.m0000644000175000017500000000614013066736044017314 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} angles3d () ##ANGLES3D Conventions for manipulating angles in 3D ## ## Contrary to the plane, there are no oriented angles in 3D. Angles ## between lines or between planes are comprised between 0 and PI. ## ## Spherical angles ## Spherical angles are defined by 2 angles: ## * THETA, the colatitude, representing angle with Oz axis (between 0 and ## PI) ## * PHI, the azimut, representing angle with Ox axis of horizontal ## projection of the direction (between 0 and 2*PI) ## ## Spherical coordinates can be represented by THETA, PHI, and the ## distance RHO to the origin. ## ## Euler angles ## Some functions for creating rotations use Euler angles. They follow the ## ZYX convention in the global reference system, that is eqivalent to the ## XYZ convention ine a local reference system. ## Euler angles are given by a triplet of angles [PHI THETA PSI] that ## represents the succession of 3 rotations: ## * rotation around X by angle PSI ("roll") ## * rotation around Y by angle THETA ("pitch") ## * rotation around Z by angle PHI ("yaw") ## ## In this library, euler angles are given in degrees. The functions that ## use euler angles use the keyword 'Euler' in their name. ## ## ## @seealso{cart2sph2, sph2cart2, cart2sph2d, sph2cart2d ## anglePoints3d, angleSort3d, sphericalAngle, randomAngle3d ## dihedralAngle, polygon3dNormalAngle, eulerAnglesToRotation3d ## rotation3dAxisAndAngle, rotation3dToEulerAngles} ## @end deftypefn function angles3d() help angles3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawLine3d.m0000644000000000000000000000013213066736044017433 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawLine3d.m0000644000175000017500000000541613066736044017615 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %DRAWLINE3D Draw a 3D line on the current axis % % drawline3d(LINE); % Draws the line LINE on the current axis, by clipping with the current % axis. If line is not clipepd by the axis, function return -1. % % drawLine3d(LINE, PARAM, VALUE) % Accepts parameter/value pairs, like for plot function. % Color of the line can also be given as a single parameter. % % H = drawLine3d(...) % Returns a handle to the created graphic line object. % % % See also: % lines3d, createLine3d, clipLine3d function varargout = drawLine3d(lin, varargin) % ensure color is given as name-value pair if length(varargin)==1 varargin = {'color', varargin{1}}; end % extract limits of the bounding box lim = get(gca, 'xlim'); xmin = lim(1); xmax = lim(2); lim = get(gca, 'ylim'); ymin = lim(1); ymax = lim(2); lim = get(gca, 'zlim'); zmin = lim(1); zmax = lim(2); % clip the ine with the limits of the current axis edge = clipLine3d (lin, [xmin xmax ymin ymax zmin zmax]); % draw the clipped line if sum(isnan(edge))==0 h = drawEdge3d(edge); if ~isempty(varargin) set(h, varargin{:}); end else h = -1; end % process output if nargout>0 varargout{1}=h; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/projPointOnPlane.m0000644000000000000000000000013213066736044020700 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/projPointOnPlane.m0000644000175000017500000000523113066736044021055 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pt2} =} projPointOnPlane (@var{pt1}, @var{plane}) ## Return the orthogonal projection of a point on a plane ## ## PT2 = projPointOnPlane(PT1, PLANE); ## Compute the (orthogonal) projection of point PT1 onto the line PLANE. ## ## Function works also for multiple points and planes. In this case, it ## returns multiple points. ## Point PT1 is a [N*3] array, and PLANE is a [N*9] array (see createPlane ## for details). Result PT2 is a [N*3] array, containing coordinates of ## orthogonal projections of PT1 onto planes PLANE. ## ## @seealso{planes3d, points3d, planePosition, intersectLinePlane} ## @end deftypefn function point = projPointOnPlane (point, plane) if size (point, 1) == 1 point = repmat (point, [size(plane, 1) 1]); elseif size (plane, 1) == 1 plane = repmat (plane, [size(point, 1) 1]); elseif size (plane, 1) ~= size (point, 1) error ('Octave:invalid-input-arg', ... 'projPointOnPlane: size of inputs differ'); end n = planeNormal (plane); line = [point n]; point = intersectLinePlane (line, plane); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawSphericalEdge.m0000644000000000000000000000013213066736044021014 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawSphericalEdge.m0000644000175000017500000000555613066736044021203 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawSphericalEdge (@var{sphere}, @var{edge}) ## Draw an edge on the surface of a sphere ## ## @var{edge} is given as a couple of 3D corodinates corresponding to edge ## extremities. The shortest spherical edge joining the two extremities is ## drawn on the current axes. ## ## @seealso{drawSphericalPolygon} ## @end deftypefn function varargout = drawSphericalEdge(sphere, edge, varargin) # extract data of the sphere origin = sphere(:, 1:3); # extremities of current edge point1 = edge(1:3); point2 = edge(4:6); # compute plane containing current edge plane = createPlane(origin, point1, point2); # intersection of the plane with unit sphere circle = intersectPlaneSphere(plane, sphere); # find the position (in degrees) of the 2 vertices on the circle angle1 = circle3dPosition(point1, circle); angle2 = circle3dPosition(point2, circle); # ensure angles are in right direction if mod(angle2 - angle1 + 360, 360) > 180 tmp = angle1; angle1 = angle2; angle2 = tmp; end # compute angle extent of the circle arc angleExtent = mod(angle2 - angle1 + 360, 360); # create circle arc arc = [circle angle1 angleExtent]; # draw the arc h = drawCircleArc3d(arc, varargin{:}); if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/transformLine3d.m0000644000000000000000000000013013066736044020507 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/transformLine3d.m0000644000175000017500000000433213066736044020667 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %TRANSFORMLINE3D Transform a 3D line with a 3D affine transform % % LINE2 = transformLine3d(LINE1, TRANS) % % Example % P1 = [10 20 30]; % P2 = [30 40 50]; % L = createLine3d(P1, P2); % T = createRotationOx(P1, pi/6); % L2 = transformLine3d(L, T); % figure; hold on; % axis([0 100 0 100 0 100]); view(3); % drawPoint3d([P1;P2]); % drawLine3d(L, 'b'); % drawLine3d(L2, 'm'); % % See also: % lines3d, transforms3d, transformPoint3d, transformVector3d function res = transformLine3d(line, trans) res = [... transformPoint3d(line(:, 1:3), trans) ... % transform origin point transformVector3d(line(:,4:6), trans)]; % transform direction vect. endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/polygons3d.m0000644000000000000000000000013213066736044017540 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/polygons3d.m0000644000175000017500000000427413066736044017723 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} polygons3d () ## POLYGONS3D Description of functions operating on 3D polygons ## ## A 3D polygon is simply a set of 3D points (called vertices) which are ## assumed to be located in the same plane. ## Several functions are provided for computing basic geometrical ## parameters (centroid, angles), or intersections with lines or planes. ## ## @seealso{polygon3dNormalAngle, polygonCentroid3d, clipConvexPolygon3dHP ## intersectLinePolygon3d, intersectLineTriangle3d, intersectRayPolygon3d ## drawPolygon3d, drawPolyline3d, fillPolygon3d} ## @end deftypefn function polygons3d() help polygons3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/cart2cyl.m0000644000000000000000000000013013066736044017160 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/cart2cyl.m0000644000175000017500000000620113066736044017335 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{cyl} =} cart2cyl (@var{point}) ## @deftypefnx {Function File} {@var{cyl} =} cart2cyl (@var{x}, @var{y}, @var{z}) ## Convert cartesian to cylindrical coordinates ## ## CYL = cart2cyl(POINT) ## convert the 3D cartesian coordinates of points POINT (given by [X Y Z] ## where X, Y, Z have the same size) into cylindrical coordinates CYL, ## given by [THETA R Z]. ## THETA is the arctangent of the ratio Y/X (between 0 and 2*PI) ## R can be computed using sqrt(X^2+Y^2) ## Z keeps the same value. ## The size of THETA, and R is the same as the size of X, Y and Z. ## ## CYL = cart2cyl(X, Y, Z) ## provides coordinates as 3 different parameters ## ## Example ## @example ## cart2cyl([-1 0 2]) ## gives : 4.7124 1.0000 2.0000 ## @end example ## ## @seealso{agles3d, cart2pol, cart2sph2} ## @end deftypefn function varargout = cart2cyl(varargin) # process input parameters if length(varargin)==1 var = varargin{1}; x = var(:,1); y = var(:,2); z = var(:,3); elseif length(varargin)==3 x = varargin{1}; y = varargin{2}; z = varargin{3}; end # convert coordinates dim = size(x); theta = reshape(mod(atan2(y(:), x(:))+2*pi, 2*pi), dim); r = reshape(sqrt(x(:).*x(:) + y(:).*y(:)), dim); # process output parameters if nargout==0 ||nargout==1 if length(dim)>2 || dim(2)>1 varargout{1} = {theta r z}; else varargout{1} = [theta r z]; end elseif nargout==3 varargout{1} = theta; varargout{2} = r; varargout{3} = z; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/polygonArea3d.m0000644000000000000000000000013213066736044020146 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/polygonArea3d.m0000644000175000017500000000606113066736044020325 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{area} =} polygonArea3d(@var{poly}) ## Area of a 3D polygon ## ## @var{poly} is given as a N-by-3 array of vertex coordinates. The resulting ## area is positive. ## ## Example ## @example ## poly = [10 30 20;20 30 20;20 40 20;10 40 20]; ## polygonArea3d(poly) ## ans = ## 100 ## @end example ## ## @seealso{polygons3d, triangleArea3d, polygonArea, polygonCentroid3d} ## @end deftypefn function area = polygonArea3d(poly) # put the first vertex at origin (reducing computation errors for polygons # far from origin) v0 = poly (1, :); poly -= v0; # indices of next vertices N = size (poly, 1); iNext = [2:N 1]; # compute area (vectorized version) # need to compute the sign explicitely, as the norm of the cross product # does not keep orientation within supporting plane. cp = cross (poly, poly(iNext,:), 2); sign_i = sign (cp*cp(2,:)'); area_i = vectorNorm(cp) .* sign_i; # sum up individual triangles area area = sum(area_i) / 2; endfunction %!demo %! poly = [10 30 20;20 30 20;20 40 20;10 40 20]; %! polygonArea3d(poly) %!demo %! l=0.25; %! # Corner Triangle with a wedge %! poly = [1 0 0; ... %! ([1 0 0]+l*[-1 1 0]); ... %! mean(eye(3)); ... %! ([1 0 0]+(1-l)*[-1 1 0]); ... %! 0 1 0; ... %! 0 0 1]; %! %! polygonArea3d(poly) %! %! # Is the same as %! p1 = [1 0 0; 0 1 0; 0 0 1]; # Corner %! p2 = [([1 0 0]+l*[-1 1 0]); ([1 0 0]+(1-l)*[-1 1 0]); mean(eye(3))]; # Wedge %! %! polygonArea3d(p1)-polygonArea3d(p2) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/intersectLineSphere.m0000644000000000000000000000013213066736044021416 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/intersectLineSphere.m0000644000175000017500000001302213066736044021570 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %INTERSECTLINESPHERE Return intersection points between a line and a sphere % % PTS = intersectLineSphere(LINE, SPHERE); % Returns the two points which are the intersection of the given line and % sphere. % LINE : [x0 y0 z0 dx dy dz] % SPHERE : [xc yc zc R] % PTS : [x1 y1 z1 ; x2 y2 z2] % If there is no intersection between the line and the sphere, return a % 2-by-3 array containing only NaN. % % Example %! % draw the intersection between a sphere and a collection of parallel %! % lines %! sphere = [50.12 50.23 50.34 40]; %! [x, y] = meshgrid(10:10:90, 10:10:90); %! n = numel(x); %! lines = [x(:) y(:) zeros(n,1) zeros(n,2) ones(n,1)]; %! figure; hold on; axis equal; %! axis([0 100 0 100 0 100]); view(3); %! drawSphere(sphere); %! drawLine3d(lines); %! pts = intersectLineSphere(lines, sphere); %! drawPoint3d(pts, 'rx'); % %! % apply rotation on set of lines to check with non vertical lines %! rot = eulerAnglesToRotation3d(20, 30, 10); %! rot2 = recenterTransform3d(rot, [50 50 50]); %! lines2 = transformLine3d(lines, rot2); %! figure; hold on; axis equal; %! axis([0 100 0 100 0 100]); view(3); %! drawSphere(sphere); %! drawLine3d(lines2); %! pts2 = intersectLineSphere(lines2, sphere); %! drawPoint3d(pts, 'rx'); % % See also % spheres, circles3d, intersectPlaneSphere function points = intersectLineSphere (line, sphere, tol = sqrt(eps)) % difference between centers dc = bsxfun (@minus, line(:, 1:3), sphere(:, 1:3)); % equation coefficients a = sum (line(:, 4:6) .* line(:, 4:6), 2); b = 2 * sum (bsxfun (@times, dc, line(:, 4:6)), 2); c = sum (dc.*dc, 2) - sphere(:,4) .* sphere(:,4); % solve equation delta = b.*b - 4*a.*c; % initialize empty results points = NaN * ones (2 * size (delta, 1), 3); %% process couples with two intersection points % process couples with two intersection points inds = find (delta > tol); if ~isempty (inds) % delta positive: find two roots of second order equation u1 = (-b(inds) - sqrt (delta(inds))) / 2 ./ a(inds); u2 = (-b(inds) + sqrt (delta(inds))) / 2 ./ a(inds); % convert into 3D coordinate points(inds, :) = line(inds, 1:3) + ... bsxfun (@times, u1, line(inds, 4:6)); points(inds+length(delta),:) = line(inds, 1:3) + ... bsxfun (@times, u2, line(inds, 4:6)); end %% process couples with one intersection point % proces couples with two intersection points inds = find (abs (delta) < tol); if ~isempty (inds) % delta around zero: find unique root, and convert to 3D coord. u = -b(inds) / 2 ./ a(inds); % convert into 3D coordinate pts = line(inds, 1:3) + ... bsxfun (@times, u, line(inds, 4:6)); points(inds, :) = pts; points(inds+length(delta),:) = pts; end endfunction %!demo %! sphere = [50.12 50.23 50.34 40]; %! [x, y] = meshgrid (10:10:90, 10:10:90); %! n = numel (x); %! lines = [x(:) y(:) zeros(n,1) zeros(n,2) ones(n,1)]; %! pts = intersectLineSphere (lines, sphere); %! figure; hold on; axis equal; %! axis ([0 100 0 100 0 100]); view (3); %! drawSphere (sphere); %! drawLine3d (lines); %! drawPoint3d (pts, 'rx'); %! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %! % draw the intersection between a sphere and a collection of parallel %! % lines %!demo %! sphere = [50.12 50.23 50.34 40]; %! [x, y] = meshgrid (10:10:90, 10:10:90); %! n = numel (x); %! lines = [x(:) y(:) zeros(n,1) zeros(n,2) ones(n,1)]; %! rot = eulerAnglesToRotation3d (20, 30, 10); %! rot = recenterTransform3d (rot, [50 50 50]); %! lines = transformLine3d (lines, rot); %! pts = intersectLineSphere (lines, sphere); %! figure; hold on; axis equal; %! axis ([0 100 0 100 0 100]); view (3); %! drawSphere (sphere); %! drawLine3d (lines); %! drawPoint3d (pts, 'rx'); %! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 %! % apply rotation on set of lines to check with non vertical lines geometry-3.0.0/inst/geom3d/PaxHeaders.28738/anglePoints3d.m0000644000000000000000000000013213066736044020151 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/anglePoints3d.m0000644000175000017500000000652713066736044020337 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{alpha} =} anglePoints3d (@var{p1}, @var{p2}) ## @deftypefnx {Function File} {@var{alpha} =} anglePoints3d (@var{p1}, @var{p2},@var{p3}) ## @deftypefnx {Function File} {@var{alpha} =} anglePoints3d (@var{pts}) ## Compute angle between three 3D points ## ## @var{alpha} = anglePoints3d(P1, P2) ## Computes angle (P1, O, P2), in radians, between 0 and PI. ## ## @var{alpha} = anglePoints3d(P1, P2, P3) ## Computes angle (P1, P2, P3), in radians, between 0 and PI. ## ## @var{alpha} = anglePoints3d(PTS) ## PTS is a 3x3 or 2x3 array containing coordinate of points. ## ## @seealso{points3d, angles3d} ## @end deftypefn function alpha = anglePoints3d(varargin) p2 = [0 0 0]; if length(varargin)==1 pts = varargin{1}; if size(pts, 1)==2 p1 = pts(1,:); p0 = [0 0 0]; p2 = pts(2,:); else p1 = pts(1,:); p0 = pts(2,:); p2 = pts(3,:); end elseif length(varargin)==2 p1 = varargin{1}; p0 = [0 0 0]; p2 = varargin{2}; elseif length(varargin)==3 p1 = varargin{1}; p0 = varargin{2}; p2 = varargin{3}; end # ensure all data have same size n1 = size(p1, 1); n2 = size(p2, 1); n0 = size(p0, 1); if n1~=n2 if n1==1 p1 = repmat(p1, [n2 1]); elseif n2==1 p2 = repmat(p2, [n1 1]); else error('Arguments P1 and P2 must have the same size'); end end if n1~=n0 if n1==1 p1 = repmat(p1, [n0 1]); elseif n0==1 p0 = repmat(p0, [n1 1]); else error('Arguments P1 and P0 must have the same size'); end end # normalized vectors p1 = normalizeVector(p1-p0); p2 = normalizeVector(p2-p0); # compute angle alpha = acos(dot(p1, p2, 2)); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/points3d.m0000644000000000000000000000013213066736044017202 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/points3d.m0000644000175000017500000000403213066736044017355 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} points3d () ##POINTS3D Description of functions operating on 3D points ## ## Points are represented by their 3 Cartesian coordinates: ## P = [X Y Z]; ## ## Arrays of points consist in N*3 arrays, each row being a point. ## ## @seealso{isCoplanar, distancePoints, anglePoints3d, angleSort3d, sphericalAngle, ## sph2cart2, cart2sph2, cart2cyl, cyl2cart, transformPoint3d, clipPoints3d} ## @end deftypefn function points3d() help points3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawPolyline3d.m0000644000000000000000000000013213066736044020337 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawPolyline3d.m0000644000175000017500000001067613066736044020525 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawPolyline3d (@var{poly}) ## @deftypefnx {Function File} {@var{h} =} drawPolyline3d (@var{px},@var{py},@var{pz}) ## @deftypefnx {Function File} {@var{h} =} drawPolyline3d (@dots{},@var{closed}) ## @deftypefnx {Function File} {@var{h} =} drawPolyline3d (@dots{},@var{param},@var{value}) ## Draw a 3D polyline specified by a list of vertices ## ## drawPolyline3d(POLY); ## packs coordinates in a single N-by-3 array. ## ## drawPolyline3d(PX, PY, PZ); ## specify coordinates in separate arrays. ## ## drawPolyline3d(..., CLOSED); ## Specifies if the polyline is closed or open. CLOSED can be one of: ## - 'closed' ## - 'open' (the default) ## - a boolean variable with value TRUE for closed polylines. ## ## drawPolyline3d(..., PARAM, VALUE); ## Specifies style options to draw the polyline, see plot for details. ## ## H = drawPolyline3d(...); ## also return a handle to the list of line objects. ## ## @seealso{polygons3d, drawPolygon3d, fillPolygon3d} ## @end deftypefn function varargout = drawPolyline3d(varargin) ## Process input arguments # check case we want to draw several curves, stored in a cell array var = varargin{1}; if iscell(var) holded = false; if ~ishold(gca) hold on; holded = true; end h = []; for i = 1:length(var(:)) h = [h; drawPolyline3d(var{i}, varargin{2:end})]; ##ok end if holded hold off end if nargout > 0 varargout = {h}; end return; end # extract curve coordinates if size(var, 2) == 1 # first argument contains x coord, second argument contains y coord # and third one the z coord px = var; if length(varargin) < 3 error('Wrong number of arguments in drawPolyline3d'); end py = varargin{2}; pz = varargin{3}; varargin = varargin(4:end); else # all coordinates are grouped in the first argument px = var(:, 1); py = var(:, 2); pz = var(:, 3); varargin = varargin(2:end); end # check if curve is closed or open (default is open) closed = false; if ~isempty(varargin) var = varargin{1}; if islogical(var) # check boolean flag closed = var; varargin = varargin(2:end); elseif ischar(var) # check string indicating close or open if strncmpi(var, 'close', 5) closed = true; varargin = varargin(2:end); elseif strncmpi(var, 'open', 4) closed = false; varargin = varargin(2:end); end end end ## draw the curve # for closed curve, add the first point at the end to close curve if closed px = [px; px(1)]; py = [py; py(1)]; pz = [pz; pz(1)]; end h = plot3(px, py, pz, varargin{:}); if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/distancePointLine3d.m0000644000000000000000000000013213066736044021302 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/distancePointLine3d.m0000644000175000017500000000765113066736044021467 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{d} =} distancePointLine3d (@var{point}, @var{line}) ## Euclidean distance between 3D point and line ## ## Returns the distance between point POINT and the line LINE, given as: ## POINT : [x0 y0 z0] ## LINE : [x0 y0 z0 dx dy dz] ## D : (positive) scalar ## ## Run @command{demo distancePointLine3d} to see examples. ## ## References ## http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html ## ## @seealso{lines3d, distancePointLine, distancePointEdge3d, projPointOnLine3d} ## @end deftypefn function d = distancePointLine3d(point, lin) [np nd] = size (point); [nl ndl] = size (lin); if ndl < 4 error("geometry:InvalidInput","second argument must be a line. See lines3d."); end # Compare everything to everything if np != nl # Order the lines such that all points are compared against 1st line, then # secoind and so on. --JPi idx = reshape (1:np*nl,nl,np)'(:); lin = repmat (lin, np, 1)(idx,:); point = repmat (point, nl, 1); end d = vectorNorm ( cross ( lin(:,4:6), lin(:,1:3)-point, 2)) ./ ... vectorNorm (lin(:,4:6)); endfunction %!demo %! point = [0 0 1]; %! lin = [0 0 0 1 1 1]; %! d = distancePointLine3d (point,lin); %! %! # Orthogonal and Parallel projectors %! dl = normalizeVector (lin(4:end))'; %! V = dl*dl'; %! P = eye(3) - dl*dl'; %! pv = P*point'; %! vv = V*point'; %! %! # Compare %! disp([d vectorNorm(pv)]) %! %! figure(1); %! clf %! plot3 (point(1),point(2),point(3),'.k'); %! line ([0 point(1)],[0 point(2)],[0 point(3)],'color','k'); %! line (dl(1)*[-2 2],dl(2)*[-2 2],dl(3)*[-2 2],'color','r'); %! line ([0 vv(1)],[0 vv(2)],[0 vv(3)],'color','g'); %! line (vv(1)+[0 pv(1)],vv(2)+[0 pv(2)],vv(3)+[0 pv(3)],'color','b'); %! axis square equal %! %! # ------------------------------------------------------------------------- %! # Distance between a line and a point, the distance is verified against the %! # vector form the point to the line, orthogonal to the line. %!demo %! point = 2*rand(4,3)-1; %! lin = [0 0 0 1 1 1; 0 0 0 1 1 0]; %! d = distancePointLine3d (point,lin) %! %! # Organize as matrix point vs lines %! reshape (d,4,2) %! %! # ------------------------------------------------------------------------- %! # Distance between 4 points and two lines. The result can be arrange as a %! # distance matrix. geometry-3.0.0/inst/geom3d/PaxHeaders.28738/angleSort3d.m0000644000000000000000000000013213066736044017624 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/angleSort3d.m0000644000175000017500000000742713066736044020012 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pts2} =} angleSort3d (@var{pts}) ## @deftypefnx {Function File} {@var{pts2} =} angleSort3d (@var{pts},@var{pts0}) ## @deftypefnx {Function File} {@var{pts2} =} angleSort3d (@var{pts},@var{pts0},@var{pts1}) ## @deftypefnx {Function File} {[@var{pts2} @var{i}]=} angleSort3d (@dots{}) ## Sort 3D coplanar points according to their angles in plane ## ## @var{pts2} = angleSort3d(@var{pts}); ## Considers all points are located on the same plane, and sort them ## according to the angle on plane. @var{pts} is a [Nx2] array. Note that the ## result depend on plane orientation: points can be in reverse order ## compared to expected. The reference plane is computed besed on the 3 ## first points. ## ## @var{pts2} = angleSort3d(@var{pts}, @var{pts0}); ## Computes angles between each point of @var{pts} and PT0. By default, uses ## centroid of points. ## ## @var{pts2} = angleSort3d(@var{pts}, @var{pts0}, @var{pts1}); ## Specifies the point which will be used as a start. ## ## [@var{pts2}, @var{i}] = angleSort3d(...); ## Also return in @var{i} the indices of @var{pts}, such that @var{pts2} = @var{pts}(I, :); ## ## @seealso{points3d, angles3d, angleSort} ## @end deftypefn function varargout = angleSort3d(pts, varargin) # default values pt0 = mean (pts, 1); pt1 = pts(1,:); if length (varargin)==1 pt0 = varargin{1}; elseif length (varargin)==2 pt0 = varargin{1}; pt1 = varargin{2}; end # create support plane plane = createPlane (pts(1:3, :)); # project points onto the plane pts2d = planePosition (pts, plane); pt0 = planePosition (pt0, plane); pt1 = planePosition (pt1, plane); # compute origin angle theta0 = atan2 (pt1(2)-pt0(2), pt1(1)-pt0(1)); theta0 = mod (theta0 + 2*pi, 2*pi); # translate to reference point n = size (pts, 1); pts2d = pts2d - repmat (pt0, [n 1]); # compute angles angle = atan2 (pts2d(:,2), pts2d(:,1)); angle = mod (angle - theta0 + 4*pi, 2*pi); # sort points according to angles [angle, I] = sort (angle); ##ok # format output if nargout<2 varargout{1} = pts(I, :); elseif nargout==2 varargout{1} = pts(I, :); varargout{2} = I; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/revolutionSurface.m0000644000000000000000000000013213066736044021156 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/revolutionSurface.m0000644000175000017500000001331213066736044021332 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{x}, @var{y}, @var{z}] =} revolutionSurface (@var{c1}, @var{c2}, @var{n}) ## @deftypefnx {Function File} {[@var{x}, @var{y}, @var{z}] =} revolutionSurface (@var{curve}, @var{n}) ## @deftypefnx {Function File} {[@var{x}, @var{y}, @var{z}] =} revolutionSurface (@dots{}, @var{theta}) ## @deftypefnx {Function File} {[@var{x}, @var{y}, @var{z}] =} revolutionSurface (@dots{}, @var{line}) ## Create a surface of revolution from a planar curve ## ## usage ## [X Y Z] = revolutionSurface(C1, C2, N); ## create the surface of revolution of parametrized function (xt, yt), ## with N+1 equally spaced slices, around the Oz axis. ## It assumed that C1 corresponds to the x coordinate, and that C2 ## corresponds to the Oz coordinate. ## ## [X Y Z] = revolutionSurface(CURVE, N); ## is the same, but generating curve is given in a single parameter CURVE, ## which is a [Nx2] array of 2D points. ## ## [X Y Z] = revolutionSurface(..., THETA) ## where THETA is a vector, uses values of THETA for computing revolution ## angles. ## ## [X Y Z] = revolutionSurface(..., LINE); ## where LINE is a 1x4 array, specifes the revolution axis in the ## coordinate system of the curve. LINE is a row vector of 4 parameters, ## containing [x0 y0 dx dy], where (x0,y0) is the origin of the line and ## (dx,dy) is a direction vector of the line. ## The resulting revolution surface still has Oz axis as symmetry axis. It ## can be transformed using transformPoint3d function. ## Surface can be displayed using : ## @code{H = surf(X, Y, Z);} ## H is a handle to the created patch. ## ## revolutionSurface(...); ## by itself, directly shows the created patch. ## ## Example ## @example ## # draws a piece of torus ## circle = circleAsPolygon([10 0 3], 50); ## [x y z] = revolutionSurface(circle, linspace(0, 4*pi/3, 50)); ## surf(x, y, z); ## axis square equal; ## @end example ## ## @seealso{surf, transformPoint3d, drawSphere, drawTorus, drawEllipsoid} ## @end deftypefn function varargout = revolutionSurface(varargin) ## Initialisations # default values # use revolution using the full unit circle, decomposed into 24 angular # segments (thus, some vertices correspond to particular angles 30°, # 45°...) theta = linspace(0, 2*pi, 25); # use planar vertical axis as default revolution axis revol = [0 0 0 1]; # extract the generating curve var = varargin{1}; if size(var, 2)==1 xt = var; yt = varargin{2}; varargin(1:2) = []; else xt = var(:,1); yt = var(:,2); varargin(1) = []; end # extract optional parameters: angles, axis of revolution # parameters are identified from their length while ~isempty(varargin) var = varargin{1}; if length(var) == 4 # axis of rotation in the base plane revol = var; elseif length(var) == 1 # number of points -> create row vector of angles theta = linspace(0, 2*pi, var); else # use all specified angle values theta = var(:)'; end varargin(1) = []; end ## Create revolution surface # ensure length is enough m = length(xt); if m==1 xt = [xt xt]; end # ensure x and y are vertical vectors xt = xt(:); yt = yt(:); # transform xt and yt to replace in the reference of the revolution axis tra = createTranslation(-revol(1:2)); rot = createRotation(pi/2 - lineAngle(revol)); [xt yt] = transformPoint(xt, yt, tra*rot); # compute surface vertices x = xt * cos(theta); y = xt * sin(theta); z = yt * ones(size(theta)); ## Process output arguments # format output depending on how many output parameters are required if nargout == 0 # draw the revolution surface surf(x, y, z); elseif nargout == 1 # draw the surface and return a handle to the shown structure h = surf(x, y, z); varargout{1} = h; elseif nargout == 3 # return computed mesh varargout = {x, y, z}; end endfunction %!demo %! # draws a piece of torus %! circle = circleAsPolygon ([10 0 3], 50); %! [x y z] = revolutionSurface (circle, linspace(0, 4*pi/3, 50)); %! surf (x, y, z); %! axis square equal; geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createPlane.m0000644000000000000000000000013013066736044017660 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createPlane.m0000644000175000017500000001155413066736044020044 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{PLANE} =} createPlane (@var{pts}) ## @deftypefnx {Function File} {@var{PLANE} =} createPlane (@var{p0}, @var{n}) ## @deftypefnx {Function File} {@var{PLANE} =} createPlane (@var{p1}, @var{p2}, @var{p3}) ## Create a plane in parametrized form ## ## PLANE = createPlane(PTS) ## The 3 points are packed into a single 3x3 array. ## ## PLANE = createPlane(P0, N); ## Creates a plane from a point and from a normal to the plane. The ## parameter N is given either as a 3D vector (1-by-3 row vector), or as ## [THETA PHI], where THETA is the colatitute (angle with the vertical ## axis) and PHI is angle with Ox axis, counted counter-clockwise (both ## given in radians). ## ## PLANE = createPlane(P1, P2, P3) ## creates a plane containing the 3 points ## ## The created plane data has the following format: ## PLANE = [X0 Y0 Z0 DX1 DY1 DZ1 DX2 DY2 DZ2], with ## - (X0, Y0, Z0) is a point belonging to the plane ## - (DX1, DY1, DZ1) is a first direction vector ## - (DX2, DY2, DZ2) is a second direction vector ## The 2 direction vectors are normalized and orthogonal. ## ## @seealso{planes3d, medianPlane} ## @end deftypefn ## TODO: return closet plane when dim(PTS,1) > 3 function plane = createPlane(varargin) if length (varargin) == 1 var = varargin{1}; if iscell (var) plane = zeros ([length (var) 9]); for i=1:length (var) plane(i,:) = createPlane (var{i}); end elseif size (var, 1) >= 3 # 3 points in a single array p1 = var(1,:); p2 = var(2,:); p3 = var(3,:); # create direction vectors v1 = p2 - p1; v2 = p3 - p1; # create plane plane = normalizePlane ([p1 v1 v2]); return; end elseif length (varargin) == 2 # plane origin p0 = varargin{1}; # second parameter is either a 3D vector or a 3D angle (2 params) var = varargin{2}; if size (var, 2) == 2 # normal is given in spherical coordinates n = sph2cart2 ([var ones(size(var, 1))]); elseif size (var, 2)==3 # normal is given by a 3D vector n = normalizeVector (var); else error ('wrong number of parameters in createPlane'); end # ensure same dimension for parameters if size (p0, 1)==1 p0 = repmat (p0, [size(n, 1) 1]); end if size(n, 1)==1 n = repmat (n, [size(p0, 1) 1]); end # find a vector not colinear to the normal v0 = repmat ([1 0 0], [size(p0, 1) 1]); inds = vectorNorm (cross (n, v0, 2)) < 1e-14; v0(inds, :) = repmat ([0 1 0], [sum(inds) 1]); # if abs(cross(n, v0, 2))<1e-14 # v0 = repmat([0 1 0], [size(p0, 1) 1]); # end # create direction vectors v1 = normalizeVector (cross (n, v0, 2)); v2 = -normalizeVector (cross (v1, n, 2)); # concatenate result in the array representing the plane plane = [p0 v1 v2]; return; elseif length (varargin)==3 p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; # create direction vectors v1 = p2 - p1; v2 = p3 - p1; plane = normalizePlane ([p1 v1 v2]); return; else error ('Wrong number of arguments in "createPlane".'); end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createRotationOz.m0000644000000000000000000000013213066736044020733 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createRotationOz.m0000644000175000017500000000672613066736044021122 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{trans} =} createRotationOz (@var{theta}) ## @deftypefnx {Function File} {@var{trans} =} createRotationOz (@var{origin},@var{theta}) ## @deftypefnx {Function File} {@var{trans} =} createRotationOz (@var{x0},@var{y0},@var{z0},@var{theta}) ## Create the 4x4 matrix of a 3D rotation around x-axis ## ## TRANS = createRotationOz(THETA); ## Returns the transform matrix corresponding to a rotation by the angle ## THETA (in radians) around the Oz axis. A rotation by an angle of PI/2 ## would transform the vector [0 1 0] into the vector [0 0 1]. ## ## The returned matrix has the form: ## [1 0 0 0] ## [0 cos(THETA) -sin(THETA) 0] ## [0 sin(THETA) cos(THETA) 0] ## [0 0 0 1] ## ## TRANS = createRotationOz(ORIGIN, THETA); ## TRANS = createRotationOz(X0, Y0, Z0, THETA); ## Also specifies origin of rotation. The result is similar as performing ## translation(-X0, -Y0, -Z0), rotation, and translation(X0, Y0, Z0). ## ## @seealso{transforms3d, transformPoint3d, createRotationOx, createRotationOy} ## @end deftypefn function trans = createRotationOz(varargin) # default values dx = 0; dy = 0; dz = 0; theta = 0; # get input values if length(varargin)==1 # only angle theta = varargin{1}; elseif length(varargin)==2 # origin point (as array) and angle var = varargin{1}; dx = var(1); dy = var(2); dz = var(3); theta = varargin{2}; elseif length(varargin)==3 # origin (x and y) and angle dx = varargin{1}; dy = varargin{2}; dz = varargin{3}; theta = varargin{3}; end # compute coefs cot = cos(theta); sit = sin(theta); # create transformation trans = [... cot -sit 0 0;... sit cot 0 0;... 0 0 1 0;... 0 0 0 1]; # add the translation part t = [1 0 0 dx;0 1 0 dy;0 0 1 dz;0 0 0 1]; trans = t*trans/t; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawBox3d.m0000644000000000000000000000013213066736044017274 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawBox3d.m0000644000175000017500000000755213066736044017461 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawBox3d (@var{box}) ## @deftypefnx {Function File} drawBox3d (@dots{},@var{opt}) ## Draw a 3D box defined by coordinate extents ## ## Draw a box defined by its coordinate extents: ## BOX = [XMIN XMAX YMIN YMAX ZMIN ZMAX]. ## The function draws only the outline edges of the box. ## Extra options @var{opt} are passed to the function @code{drawEdges3d}. ## ## Example ## @example ## # Draw bounding box of a cubeoctehedron ## [v e f] = createCubeOctahedron; ## box3d = boundingBox3d(v); ## figure; hold on; ## drawMesh(v, f); ## drawBox3d(box3d); ## axis([-2 2 -2 2 -2 2]); ## view(3) ## @end example ## ## @seealso{boxes3d, boundingBox3d} ## @end deftypefn function drawBox3d(box, varargin) # default values xmin = box(:,1); xmax = box(:,2); ymin = box(:,3); ymax = box(:,4); zmin = box(:,5); zmax = box(:,6); nBoxes = size(box, 1); for i=1:length(nBoxes) # lower face (z=zmin) drawEdge3d([xmin(i) ymin(i) zmin(i) xmax(i) ymin(i) zmin(i)], varargin{:}); drawEdge3d([xmin(i) ymin(i) zmin(i) xmin(i) ymax(i) zmin(i)], varargin{:}); drawEdge3d([xmax(i) ymin(i) zmin(i) xmax(i) ymax(i) zmin(i)], varargin{:}); drawEdge3d([xmin(i) ymax(i) zmin(i) xmax(i) ymax(i) zmin(i)], varargin{:}); # front face (y=ymin) drawEdge3d([xmin(i) ymin(i) zmin(i) xmin(i) ymin(i) zmax(i)], varargin{:}); drawEdge3d([xmax(i) ymin(i) zmin(i) xmax(i) ymin(i) zmax(i)], varargin{:}); drawEdge3d([xmin(i) ymin(i) zmax(i) xmax(i) ymin(i) zmax(i)], varargin{:}); # left face (x=xmin) drawEdge3d([xmin(i) ymax(i) zmin(i) xmin(i) ymax(i) zmax(i)], varargin{:}); drawEdge3d([xmin(i) ymin(i) zmax(i) xmin(i) ymax(i) zmax(i)], varargin{:}); # the last 3 remaining edges drawEdge3d([xmin(i) ymax(i) zmax(i) xmax(i) ymax(i) zmax(i)], varargin{:}); drawEdge3d([xmax(i) ymax(i) zmin(i) xmax(i) ymax(i) zmax(i)], varargin{:}); drawEdge3d([xmax(i) ymin(i) zmax(i) xmax(i) ymax(i) zmax(i)], varargin{:}); end endfunction %!demo %! close all %! # Draw bounding box of a cubeoctehedron %! [v e f] = createCubeOctahedron; %! box3d = boundingBox3d(v); %! figure; %! hold on; %! drawMesh(v, f); %! drawBox3d(box3d); %! axis([-2 2 -2 2 -2 2]); %! view(3) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/cyl2cart.m0000644000000000000000000000013213066736044017162 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/cyl2cart.m0000644000175000017500000000602413066736044017340 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{cart} =} cyl2cart (@var{cyl}) ## @deftypefnx {Function File} {@var{cart} =} cyl2cart (@var{theta},@var{r},@var{z}) ## Convert cylindrical to cartesian coordinates ## ## CART = cyl2cart(CYL) ## convert the 3D cylindrical coordinates of points CYL (given by ## [THETA R Z] where THETA, R, and Z have the same size) into cartesian ## coordinates CART, given by [X Y Z]. ## The transforms is the following : ## X = R*cos(THETA); ## Y = R*sin(THETA); ## Z remains inchanged. ## ## CART = cyl2cart(THETA, R, Z) ## provides coordinates as 3 different parameters ## ## Example ## @example ## cyl2cart([-1 0 2]) ## gives : 4.7124 1.0000 2.0000 ## @end example ## ## @seealso{angles3d, cart2pol, cart2sph2, cart2cyl} ## @end deftypefn function varargout = cyl2cart(varargin) # process input parameters if length(varargin)==1 var = varargin{1}; theta = var(:,1); r = var(:,2); z = var(:,3); elseif length(varargin)==3 theta = varargin{1}; r = varargin{2}; z = varargin{3}; end # convert coordinates dim = size(theta); x = reshape(r(:).*cos(theta(:)), dim); y = reshape(r(:).*sin(theta(:)), dim); # process output parameters if nargout==0 ||nargout==1 if length(dim)>2 || dim(2)>1 varargout{1} = {x y z}; else varargout{1} = [x y z]; end elseif nargout==3 varargout{1} = x; varargout{2} = y; varargout{3} = z; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawAxis3d.m0000644000000000000000000000013213066736044017450 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawAxis3d.m0000644000175000017500000000540613066736044017631 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawAxis3d () ## @deftypefnx {Function File} drawAxis3d (@var{l},@var{r}) ## Draw a coordinate system and an origin ## ## Adds 3 cylinders to the current axis, corresponding to the directions ## of the 3 basis vectors Ox, Oy and Oz. ## Ox vector is red, Oy vector is green, and Oz vector is blue. ## ## @var{l} specifies the length and @var{r} the radius of the cylinders ## representing the different axes. ## ## WARNING: This function doesn't work in gnuplot (as of version 4.2). ## ## @seealso{drawAxisCube} ## @end deftypefn function drawAxis3d(L=1,r=1/10) # geometrical data origin = [0 0 0]; v1 = [1 0 0]; v2 = [0 1 0]; v3 = [0 0 1]; # draw 3 cylinders and a ball holded = false; if ~ishold(gca) hold on; holded = true; endif drawCylinder([origin origin+v1*L r], 16, 'facecolor', 'r', 'edgecolor', 'none'); drawCylinder([origin origin+v2*L r], 16, 'facecolor', 'g', 'edgecolor', 'none'); drawCylinder([origin origin+v3*L r], 16, 'facecolor', 'b', 'edgecolor', 'none'); drawSphere([origin 2*r], 'faceColor', 'black'); if holded hold off endif endfunction %!demo %! scatter3(5*randn(100,1),5*randn(100,1),5*randn(100,1)); %! drawAxis3d() %! axis tight geometry-3.0.0/inst/geom3d/PaxHeaders.28738/circle3dOrigin.m0000644000000000000000000000013013066736044020275 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/circle3dOrigin.m0000644000175000017500000000511413066736044020454 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{p} =} circle3dOrigin([@var{xc} @var{yc} @var{zc} @var{r} @var{theta} @var{phi}]) ## @deftypefnx {Function File} {@var{p} =} circle3dOrigin([@var{xc} @var{yc} @var{zc} @var{r} @var{theta} @var{phi} @var{psi}]) ## Return the first point of a 3D circle ## ## Returns the origin point of the circle, i.e. the first point used for ## drawing circle. ## ## @seealso{circles3d, points3d, circle3dPosition} ## @end deftypefn function ori = circle3dOrigin(varargin) # get center and radius circle = varargin{1}; xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); r = circle(:,4); # get angle of normal theta = circle(:,5); phi = circle(:,6); # get roll if size(circle, 2)==7 psi = circle(:,7); else psi = zeros(size(circle, 1), 1); end # create origin point pt0 = [r 0 0]; # compute transformation from local basis to world basis trans = localToGlobal3d(xc, yc, zc, theta, phi, psi); # transform the point ori = transformPoint3d(pt0, trans); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createScaling3d.m0000644000000000000000000000013213066736044020432 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createScaling3d.m0000644000175000017500000000657513066736044020623 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{trans} =} createScaling3d (@var{s}) ## @deftypefnx {Function File} {@var{trans} =} createScaling3d (@var{sx}, @var{sy}, @var{sz}) ## Create the 4x4 matrix of a 3D scaling ## ## TRANS = createScaling3d(S); ## returns the scaling transform corresponding to a scaling factor S in ## each direction. S can be a scalar, or a 1x3 vector containing the ## scaling factor in each direction. ## ## TRANS = createScaling3d(SX, SY, SZ); ## returns the scaling transform corresponding to a different scaling ## factor in each direction. ## ## The returned matrix has the form : ## @group ## [SX 0 0 0] ## [ 0 SY 0 0] ## [ 0 0 SZ 0] ## [ 0 0 0 0] ## @end group ## ## @seealso{transforms3d, transformPoint3d, transformVector3d, createTranslation3d, ## createRotationOx, createRotationOy, createRotationOz} ## @end deftypefn function trans = createScaling3d(varargin) # process input parameters if isempty(varargin) # assert uniform scaling in each direction sx = 1; sy = 1; sz = 1; elseif length(varargin)==1 # only one argument var = varargin{1}; if length(var)==1 # same scaling factor in each direction sx = var; sy = var; sz = var; elseif length(var)==3 # scaling is a vector, giving different scaling in each direction sx = var(1); sy = var(2); sz = var(3); else error('wrong size for first parameter of "createScaling3d"'); end elseif length(varargin)==3 # 3 arguments, giving scaling in each direction sx = varargin{1}; sy = varargin{2}; sz = varargin{3}; else error('wrong number of arguments for "createScaling3d"'); end # create the scaling matrix trans = [sx 0 0 0;0 sy 0 0;0 0 sz 0;0 0 0 1]; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawCylinder.m0000644000000000000000000000013213066736044020066 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawCylinder.m0000644000175000017500000001375113066736044020251 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawCylinder (@var{cyl}) ## @deftypefnx {Function File} {@var{h} =} drawCylinder (@var{cyl},@var{n}) ## @deftypefnx {Function File} {@var{h} =} drawCylinder (@dots{}, @var{opt}) ## @deftypefnx {Function File} {@var{h} =} drawCylinder (@dots{}, @asis{"Facecolor"},@var{color}) ## @deftypefnx {Function File} {@var{h} =} drawCylinder (@dots{}) ## Draw a cylinder ## ## drawCylinder(@var{cyl}) ## where @var{cyl} is a cylinder defined by [x1 y1 z1 x2 y2 z2 r]: ## [x1 y2 z1] are coordinates of starting point, [x2 y2 z2] are ## coordinates of ending point, and R is the radius of the cylinder, ## draws the corresponding cylinder on the current axis. ## ## drawCylinder(@var{cyl}, @var{N}) ## uses @var{N} points for discretisation of angle. Default value is 32. ## ## drawCylinder(..., @var{opt}) ## with @var{opt} = 'open' (default) or 'closed', specify if bases of the ## cylinder should be drawn. ## ## drawCylinder(..., @asis{"FaceColor"}, @var{color}) ## Specifies the color of the cylinder. Any couple of parameters name and ## value can be given as argument, and will be transfered to the 'surf' ## matlab function ## ## @var{h} = drawCylinder(...) ## returns a handle to the patch representing the cylinder. ## ## Run @code{demo drawCylinder} to see several examples. ## ## WARNING: This function doesn't work in gnuplot (as of version 4.2). ## ## @seealso{drawSphere, drawLine3d, surf} ## @end deftypefn function varargout = drawCylinder(cyl, varargin) ## Input argument processing if iscell(cyl) res = zeros(length(cyl), 1); for i=1:length(cyl) res(i) = drawCylinder(cyl{i}, varargin{:}); end if nargout>0 varargout{1} = res; end return; end # default values N = 32; closed = true; # check number of discretization steps if ~isempty(varargin) var = varargin{1}; if isnumeric(var) N = var; varargin = varargin(2:end); end end # check if cylinder must be closed or open if ~isempty(varargin) var = varargin{1}; if ischar(var) if strncmpi(var, 'open', 4) closed = false; varargin = varargin(2:end); elseif strncmpi(var, 'closed', 5) closed = true; varargin = varargin(2:end); end end end ## Computation of mesh coordinates # extreme points of cylinder p1 = cyl(1:3); p2 = cyl(4:6); # radius of cylinder r = cyl(7); # compute orientation angle of cylinder [theta phi rho] = cart2sph2d(p2 - p1); dphi = linspace(0, 2*pi, N+1); # generate a cylinder oriented upwards x = repmat(cos(dphi) * r, [2 1]); y = repmat(sin(dphi) * r, [2 1]); z = repmat([0 ; rho], [1 length(dphi)]); # transform points trans = localToGlobal3d(p1, theta, phi, 0); pts = transformPoint3d([x(:) y(:) z(:)], trans); # reshape transformed points x2 = reshape(pts(:,1), size(x)); y2 = reshape(pts(:,2), size(x)); z2 = reshape(pts(:,3), size(x)); ## Display cylinder mesh # add default drawing options varargin = [{'FaceColor', 'g', 'edgeColor', 'none'} varargin]; # plot the cylinder as a surface hSurf = surf(x2, y2, z2, varargin{:}); # eventually plot the ends of the cylinder if closed ind = find(strcmpi(varargin, 'facecolor'), 1, 'last'); if isempty(ind) color = 'k'; else color = varargin{ind+1}; end patch(x2(1,:)', y2(1,:)', z2(1,:)', color, 'edgeColor', 'none'); patch(x2(2,:)', y2(2,:)', z2(2,:)', color, 'edgeColor', 'none'); end # format ouptut if nargout == 1 varargout{1} = hSurf; end endfunction %!demo %! figure; %! h = drawCylinder([0 0 0 10 20 30 5],'FaceColor', 'r'); %! set(h, 'facecolor', 'g'); %! axis equal %! view([60 30]) %! %! figure; %! drawCylinder([0 0 0 10 20 30 5], 'open'); %! axis equal %! view([60 30]) %! %! figure; %! drawCylinder([0 0 0 10 20 30 5], 'FaceColor', 'r'); %! axis equal %! view([60 30]) %! %! figure; %! h = drawCylinder([0 0 0 10 20 30 5]); %! set(h, 'facecolor', 'b'); %! axis equal %! view([60 30]) %!demo %! # Draw three mutually intersecting cylinders %! p0 = [30 30 30]; %! p1 = [90 30 30]; %! p2 = [30 90 30]; %! p3 = [30 30 90]; %! %! figure; %! drawCylinder([p0 p1 25], 'FaceColor', 'r'); %! hold on %! drawCylinder([p0 p2 25], 'FaceColor', 'g'); %! drawCylinder([p0 p3 25], 'FaceColor', 'b'); %! axis equal %! view([60 30]) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createRotation3dLineAngle.m0000644000000000000000000000013213066736044022430 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createRotation3dLineAngle.m0000644000175000017500000000545013066736044022610 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function mat = createRotation3dLineAngle(line, theta) %CREATEROTATION3DLINEANGLE Create rotation around a line by an angle theta % % MAT = createRotation3dLineAngle(LINE, ANGLE) % % Example % origin = [1 2 3]; % direction = [4 5 6]; % line = [origin direction]; % angle = pi/3; % rot = createRotation3dLineAngle(line, angle); % [axis angle2] = rotation3dAxisAndAngle(rot); % angle2 % angle2 = % 1.0472 % % See also % transforms3d, rotation3dAxisAndAngle, rotation3dToEulerAngles, % eulerAnglesToRotation3d % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2010-08-11, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % determine rotation center and direction center = [0 0 0]; if size(line, 2)==6 center = line(1:3); vector = line(4:6); else vector = line; end % normalize vector v = normalizeVector3d(vector); % compute projection matrix P and anti-projection matrix P = v'*v; Q = [0 -v(3) v(2) ; v(3) 0 -v(1) ; -v(2) v(1) 0]; I = eye(3); % compute vectorial part of the transform mat = eye(4); mat(1:3, 1:3) = P + (I - P)*cos(theta) + Q*sin(theta); % add translation coefficient mat = recenterTransform3d(mat, center); geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawCircleArc3d.m0000644000000000000000000000013213066736044020373 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawCircleArc3d.m0000644000175000017500000000707513066736044020560 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawCircleArc3d([@var{xc} @var{yc} @var{zc} @var{r} @var{theta} @var{phi} @var{psi} @var{start} @var{extent}]) ## Draw a 3D circle arc ## ## [@var{xc} @var{yc} @var{zc}] : coordinate of arc center ## @var{r} : arc radius ## [@var{theta} @var{phi}] : orientation of arc normal, in degrees (theta: 0->180). ## @var{psi} : roll of arc (rotation of circle origin) ## @var{start} : starting angle of arc, from arc origin, in degrees ## @var{extent} : extent of circle arc, in degrees (can be negative) ## ## Drawing options can be specified, as for the plot command. ## ## @seealso{angles3, circles3d, drawCircle3d, drawCircleArc} ## @end deftypefn function varargout = drawCircleArc3d(arc, varargin) if iscell(arc) h = []; for i = 1:length(arc) h = [h drawCircleArc3d(arc{i}, varargin{:})]; ##ok end if nargout > 0 varargout = {h}; end return; end if size(arc, 1) > 1 h = []; for i = 1:size(arc, 1) h = [h drawCircleArc3d(arc(i,:), varargin{:})]; ##ok end if nargout > 0 varargout = {h}; end return; end # get center and radius xc = arc(:,1); yc = arc(:,2); zc = arc(:,3); r = arc(:,4); # get angle of normal theta = arc(:,5); phi = arc(:,6); psi = arc(:,7); # get starting angle and angle extent of arc start = arc(:,8); extent = arc(:,9); # positions on circle arc N = 60; t = linspace(start, start+extent, N+1) * pi / 180; # compute coordinate of points x = r*cos(t)'; y = r*sin(t)'; z = zeros(length(t), 1); curve = [x y z]; # compute transformation from local basis to world basis trans = localToGlobal3d(xc, yc, zc, theta, phi, psi); # transform circle arc curve = transformPoint3d(curve, trans); # draw the curve with specified options h = drawPolyline3d(curve, varargin{:}); if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/intersectLinePlane.m0000644000000000000000000000013213066736044021227 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/intersectLinePlane.m0000644000175000017500000000761113066736044021410 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pt} =} intersectLinePlane (@var{line}, @var{plane}) ## @deftypefnx {Function File} {@var{pt} =} intersectLinePlane (@dots{}, @var{tol}) ## Intersection point between a 3D line and a plane ## ## PT = intersectLinePlane(LINE, PLANE) ## Returns the intersection point of the given line and the given plane. ## LINE: [x0 y0 z0 dx dy dz] ## PLANE: [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2] ## PT: [xi yi zi] ## If LINE and PLANE are parallel, return [NaN NaN NaN]. ## If LINE (or PLANE) is a matrix with 6 (or 9) columns and N rows, result ## is an array of points with N rows and 3 columns. ## ## PT = intersectLinePlane(LINE, PLANE, TOL) ## Specifies the tolerance factor to test if a line is parallel to a ## plane. Default is 1e-14. ## ## Example ## @example ## # define horizontal plane through origin ## plane = [0 0 0 1 0 0 0 1 0]; ## # intersection with a vertical line ## line = [2 3 4 0 0 1]; ## intersectLinePlane(line, plane) ## ans = ## 2 3 0 ## # intersection with a line "parallel" to plane ## line = [2 3 4 1 2 0]; ## intersectLinePlane(line, plane) ## ans = ## NaN NaN NaN ## @end example ## ## @seealso{lines3d, planes3d, points3d, clipLine3d} ## @end deftypefn function point = intersectLinePlane (line, plane, tol = sqrt(eps)) # unify sizes of data nLines = size (line, 1); nPlanes = size (plane, 1); # N planes and M lines not allowed if nLines ~= nPlanes && min (nLines, nPlanes) > 1 error ('Octave:invalid-input-arg', ... 'Input must have same number of rows, or one must be 1'); end # plane normal n = cross (plane(:,4:6), plane(:,7:9), 2); # difference between origins of plane and line dp = bsxfun (@minus, plane(:, 1:3), line(:, 1:3)); # dot product of line direction with plane normal denom = sum (bsxfun (@times, n, line(:,4:6)), 2); # relative position of intersection point on line (can be inf in case of a # line parallel to the plane) t = zeros (size (denom)); tf = denom != 0; t(tf) = sum (bsxfun (@times, n, dp),2)(tf) ./ denom(tf); # compute coord of intersection point point = bsxfun (@plus, line(:,1:3), bsxfun (@times, [t t t], line(:,4:6))); # set indices of line and plane which are parallel to NaN par = abs (denom) < tol; point(par,:) = NaN; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/eulerAnglesToRotation3d.m0000644000000000000000000000013213066736044022157 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/eulerAnglesToRotation3d.m0000644000175000017500000000744413066736044022344 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %EULERANGLESTOROTATION3D Convert 3D Euler angles to 3D rotation matrix % % MAT = eulerAnglesToRotation3d(PHI, THETA, PSI) % Creates a rotation matrix from the 3 euler angles PHI THETA and PSI, % given in degrees, using the 'XYZ' convention (local basis), or the % 'ZYX' convention (global basis). The result MAT is a 4-by-4 rotation % matrix in homogeneous coordinates. % % PHI: rotation angle around Z-axis, in degrees, corresponding to the %! 'Yaw'. PHI is between -180 and +180. % THETA: rotation angle around Y-axis, in degrees, corresponding to the %! 'Pitch'. THETA is between -90 and +90. % PSI: rotation angle around X-axis, in degrees, corresponding to the %! 'Roll'. PSI is between -180 and +180. % These angles correspond to the "Yaw-Pitch-Roll" convention, also known % as "Tait–Bryan angles". % % The resulting rotation is equivalent to a rotation around X-axis by an % angle PSI, followed by a rotation around the Y-axis by an angle THETA, % followed by a rotation around the Z-axis by an angle PHI. % That is: %! ROT = Rz * Ry * Rx; % % MAT = eulerAnglesToRotation3d(ANGLES) % Concatenates all angles in a single 1-by-3 array. % % Example % [n e f] = createCube; % phi = 20; % theta = 30; % psi = 10; % rot = eulerAnglesToRotation3d(phi, theta, psi); % n2 = transformPoint3d(n, rot); % drawPolyhedron(n2, f); % % See also % transforms3d, createRotationOx, createRotationOy, createRotationOz % rotation3dAxisAndAngle function mat = eulerAnglesToRotation3d(phi, theta, psi, varargin) % Process input arguments if size(phi, 2) == 3 % manages arguments given as one array theta = phi(:, 2); psi = phi(:, 3); phi = phi(:, 1); end % create individual rotation matrices k = pi / 180; rotX = createRotationOx(psi * k); rotY = createRotationOy(theta * k); rotZ = createRotationOz(phi * k); % concatenate matrices mat = rotZ * rotY * rotX; endfunction %!demo %! [n e f] = createCube; %! phi = 20; %! theta = 30; %! psi = 10; %! rot = eulerAnglesToRotation3d (phi, theta, psi); %! n2 = transformPoint3d (n, rot); %! drawPolyhedron (transformPoint3d(n,createTranslation3d([-1 0 0])), f, 'g'); %! drawPolyhedron (n2, f); %! view (3) %! axis equal geometry-3.0.0/inst/geom3d/PaxHeaders.28738/geom3d_Contents.m0000644000000000000000000000013213066736044020472 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/geom3d_Contents.m0000644000175000017500000003165713066736044020662 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} geom3d_Contents () ## GEOM3D Geometry 3D Toolbox ## Version 1.0 21-Mar-2011 . ## ## Creation, transformations, algorithms and visualization of geometrical ## 3D primitives, such as points, lines, planes, polyhedra, circles and ## spheres. ## ## Euler Angles are defined as follow: ## PHI is the azimut, i.e. the angle of the projection on horizontal plane ## with the Ox axis, with value beween 0 and 180 degrees. ## THETA is the latitude, i.e. the angle with the Oz axis, with value ## between -90 and +90 degrees. ## PSI is the 'roll', i.e. the rotation around the (PHI, THETA) direction, ## with value in degrees ## See also the 'angles3d' page. ## ## Base format for primitives: ## Point: [x0 y0 z0] ## Vector: [dx dy dz] ## Line: [x0 y0 z0 dx dy dz] ## Edge: [x1 y1 z1 x2 y2 z2] ## Plane: [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2] ## Sphere: [x0 y0 z0 R] ## Circle: [x0 y0 z0 R PHI THETA PSI] (origin+center+normal+'roll'). ## Cylinder: [X1 Y1 Z1 X2 Y2 Z2 R] ## Box: [xmin xmax ymin ymax zmin zmax]. Used for clipping shapes. ## ## Polygons are represented by N-by-3 array of points, the last point is ## not necessarily the same as the first one. Points must be coplanar. ## ## Meshes and Polyhedra are represented by a couple of variables @{V, F@}: ## V: N-by-3 array of vetrtices: [x1 y1 z1; ... ;xn yn zn]; ## F: is either a [Nf*3] or [Nf*4] array containing reference for vertices ## of each face, or a [Nf*1] cell array, where each cell is an array ## containing a variable number of node indices. ## For some functions, the array E of edges is needed. It consists in a ## Ne-by-2 array containing indices of source and target vertices. ## ## ## 3D Points ## points3d - Description of functions operating on 3D points ## midPoint3d - Middle point of two 3D points or of a 3D edge ## isCoplanar - Tests input points for coplanarity in 3-space. ## transformPoint3d - Transform a point with a 3D affine transform ## distancePoints - Compute euclidean distance between pairs of 3D Points ## clipPoints3d - Clip a set of points by a box ## drawPoint3d - Draw 3D point on the current axis. ## ## 3D Vectors ## vectors3d - Description of functions operating on 3D vectors ## transformVector3d - Transform a vector with a 3D affine transform ## normalizeVector3d - Normalize a 3D vector to have norm equal to 1 ## vectorNorm3d - Norm of a 3D vector or of set of 3D vectors ## vectorAngle3d - Angle between two 3D vectors ## isParallel3d - Check parallelism of two 3D vectors ## isPerpendicular3d - Check orthogonality of two 3D vectors ## ## Angles ## angles3d - Conventions for manipulating angles in 3D ## anglePoints3d - Compute angle between three 3D points ## sphericalAngle - Compute angle between points on the sphere ## angleSort3d - Sort 3D coplanar points according to their angles in plane ## randomAngle3d - Return a 3D angle uniformly distributed on unit sphere ## ## Coordinate transforms ## sph2cart2 - Convert spherical coordinates to cartesian coordinates ## cart2sph2 - Convert cartesian coordinates to spherical coordinates ## cart2sph2d - Convert cartesian coordinates to spherical coordinates in degrees ## sph2cart2d - Convert spherical coordinates to cartesian coordinates in degrees ## cart2cyl - Convert cartesian to cylindrical coordinates ## cyl2cart - Convert cylindrical to cartesian coordinates ## ## 3D Lines and Edges ## lines3d - Description of functions operating on 3D lines ## createLine3d - Create a line with various inputs. ## transformLine3d - Transform a 3D line with a 3D affine transform ## clipLine3d - Clip a line with a box and return an edge ## midPoint3d - Middle point of two 3D points or of a 3D edge ## distancePointLine3d - Euclidean distance between 3D point and line ## distanceLines3d - Minimal distance between two 3D lines ## linePosition3d - Return the position of a 3D point on a 3D line ## drawEdge3d - Draw 3D edge in the current Window ## drawLine3d - Draw a 3D line on the current axis ## ## Planes ## planes3d - Description of functions operating on 3D planes ## createPlane - Create a plane in parametrized form ## normalizePlane - Normalize parametric representation of a plane ## intersectPlanes - Return intersection line between 2 planes in space ## intersectLinePlane - Return intersection point between a plane and a line ## intersectEdgePlane - Return intersection point between a plane and a edge ## distancePointPlane - Signed distance betwen 3D point and plane ## projPointOnPlane - Return the orthogonal projection of a point on a plane ## isBelowPlane - Test whether a point is below or above a plane ## medianPlane - Create a plane in the middle of 2 points ## planeNormal - Compute the normal to a plane ## planePosition - Compute position of a point on a plane ## planePoint - Compute 3D position of a point in a plane ## dihedralAngle - Compute dihedral angle between 2 planes ## drawPlane3d - Draw a plane clipped in the current window ## ## 3D Polygons and curves ## polygons3d - Description of functions operating on 3D polygons ## polygonCentroid3d - Centroid (or center of mass) of a polygon ## triangleArea3d - Area of a 3D triangle ## polygon3dNormalAngle - Normal angle at a vertex of the 3D polygon ## intersectLinePolygon3d - Intersection point of a 3D line and a 3D polygon ## intersectLineTriangle3d - Intersection point of a 3D line and a 3D triangle ## intersectRayPolygon3d - Intersection point of a 3D ray and a 3D polygon ## clipConvexPolygon3dHP - Clip a convex 3D polygon with Half-space ## drawPolygon3d - Draw a 3D polygon specified by a list of vertices ## drawPolyline3d - Draw a 3D polyline specified by a list of vertices ## fillPolygon3d - Fill a 3D polygon specified by a list of points ## ## 3D circles and ellipses ## circles3d - Description of functions operating on 3D circles ## circle3dPosition - Return the angular position of a point on a 3D circle ## circle3dPoint - Coordinates of a point on a 3D circle from its position ## circle3dOrigin - Return the first point of a 3D circle ## drawCircle3d - Draw a 3D circle ## drawCircleArc3d - Draw a 3D circle arc ## drawEllipse3d - Draw a 3D ellipse ## ## Spheres ## spheres - Description of functions operating on 3D spheres ## createSphere - Create a sphere containing 4 points ## intersectLineSphere - Return intersection points between a line and a sphere ## intersectPlaneSphere - Return intersection circle between a plane and a sphere ## drawSphere - Draw a sphere as a mesh ## drawSphericalTriangle - Draw a triangle on a sphere ## ## Smooth surfaces ## inertiaEllipsoid - Inertia ellipsoid of a set of 3D points ## intersectLineCylinder - Compute intersection points between a line and a cylinder ## revolutionSurface - Create a surface of revolution from a planar curve ## surfaceCurvature - Curvature on a surface from angle and principal curvatures ## drawEllipsoid - Draw a 3D ellipsoid ## drawTorus - Draw a torus (3D ring) ## drawCylinder - Draw a cylinder ## drawSurfPatch - Draw a 3D surface patch, with 2 parametrized surfaces ## ## Bounding boxes management ## boxes3d - Description of functions operating on 3D boxes ## boundingBox3d - Bounding box of a set of 3D points ## orientedBox3d - Object-oriented bounding box of a set of 3D points ## intersectBoxes3d - Intersection of two 3D bounding boxes ## mergeBoxes3d - Merge 3D boxes, by computing their greatest extent ## box3dVolume - Volume of a 3-dimensional box ## randomPointInBox3d - Generate random point(s) within a 3D box ## drawBox3d - Draw a 3D box defined by coordinate extents ## ## Geometric transforms ## transforms3d - Conventions for manipulating 3D affine transforms ## createTranslation3d - Create the 4x4 matrix of a 3D translation ## createScaling3d - Create the 4x4 matrix of a 3D scaling ## createRotationOx - Create the 4x4 matrix of a 3D rotation around x-axis ## createRotationOy - Create the 4x4 matrix of a 3D rotation around y-axis ## createRotationOz - Create the 4x4 matrix of a 3D rotation around z-axis ## createBasisTransform3d - Compute matrix for transforming a basis into another basis ## eulerAnglesToRotation3d - Convert 3D Euler angles to 3D rotation matrix ## rotation3dToEulerAngles - Extract Euler angles from a rotation matrix ## createRotation3dLineAngle - Create rotation around a line by an angle theta ## rotation3dAxisAndAngle - Determine axis and angle of a 3D rotation matrix ## recenterTransform3d - Change the fixed point of an affine 3D transform ## composeTransforms3d - Concatenate several space transformations ## ## Various drawing Functions ## drawGrid3d - Draw a 3D grid on the current axis ## drawAxis3d - Draw a coordinate system and an origin ## drawAxisCube - Draw a colored cube representing axis orientation ## drawCube - Draw a 3D centered cube, eventually rotated ## drawCuboid - Draw a 3D cuboid, eventually rotated ## ## ## Credits: ## * function isCoplanar was originally written by Brett Shoelson. ## * Songbai Ji enhanced file intersectPlaneLine (6/23/2006). ## ## @end deftypefn function geom3d_Contents () help('geom3d_Contents'); ## In development: ## clipPolygon3dHP - clip a 3D polygon with Half-space ## drawPartialPatch - draw surface patch, with 2 parametrized surfaces ## Deprecated: ## intersectPlaneLine - return intersection between a plane and a line ## translation3d - return 4x4 matrix of a 3D translation ## scale3d - return 4x4 matrix of a 3D scaling ## rotationOx - return 4x4 matrix of a rotation around x-axis ## rotationOy - return 4x4 matrix of a rotation around y-axis ## rotationOz - return 4x4 matrix of a rotation around z-axis ## scaling3d - return 4x4 matrix of a 3D scaling ## vecnorm3d - compute norm of vector or of set of 3D vectors ## normalize3d - normalize a 3D vector ## drawCurve3d - draw a 3D curve specified by a list of points ## createEulerAnglesRotation - Create a rotation matrix from 3 euler angles endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/transformVector3d.m0000644000000000000000000000013013066736044021062 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/transformVector3d.m0000644000175000017500000000564613066736044021253 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %TRANSFORMVECTOR3D Transform a vector with a 3D affine transform % % V2 = transformVector3d(V1, TRANS); % Computes the vector obtained by transforming vector V1 with affine % transform TRANS. % V1 has the form [x1 y1 z1], and TRANS is a [3x3], [3x4], or [4x4] % matrix, with one of the forms: % [a b c] , [a b c j] , or [a b c j] % [d e f] [d e f k] [d e f k] % [g h i] [g h i l] [g h i l] % [0 0 0 1] % % V2 = transformVector3d(V1, TRANS) also works when V1 is a [Nx3xMxEtc] % array of double. In this case, V2 has the same size as V1. % % V2 = transformVector3d(X1, Y1, Z1, TRANS); % Specifies vectors coordinates in three arrays with same size. % % [X2 Y2 Z2] = transformVector3d(...); % Returns the coordinates of the transformed vector separately. % % % See also: % vectors3d, transforms3d, transformPoint3d function varargout = transformVector3d(varargin) if length(varargin)==2 % func(PTS_XYZ, PLANE) syntax vIds = 1:2; elseif length(varargin)==4 % func(X, Y, Z, PLANE) syntax vIds = 1:3; end % Extract only the linear part of the affine transform trans = varargin{vIds(end)}; trans(1:4, 4) = [0; 0; 0; 1]; % Call transformPoint3d using equivalent output arguments varargout = cell(1, max(1,nargout)); [varargout{:}] = transformPoint3d(varargin{vIds(1:end-1)}, trans); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/planeNormal.m0000644000000000000000000000013213066736044017707 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/planeNormal.m0000644000175000017500000000366513066736044020075 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{n} =} planeNormal (@var{plane}) # Compute the normal to a plane # # N = planeNormal(PLANE) # compute the normal of the given plane # PLANE : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2] # N : [dx dy dz] # ## @seealso{planes3d, createPlane} ## @end deftypefn function n = planeNormal(plane) n = cross (plane(:,4:6), plane(:, 7:9), 2); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/planePoint.m0000644000000000000000000000013213066736044017550 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/planePoint.m0000644000175000017500000000463213066736044017731 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} =} planePoint (@var{plane}, @var{pos}) ## PLANEPOINT Compute 3D position of a point in a plane ## ## POINT = planePoint(PLANE, POS) ## PLANE is a 9 element row vector [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2] ## POS is the coordinate of a point in the plane basis, ## POINT is the 3D coordinate in global basis. ## ## @seealso{planes3d, planePosition} ## @end deftypefn function coord = planePoint (plane, point) # check size of input arguments npl = size (plane, 1); npt = size (point, 1); if npl ~= npt && (npl ~= 1 && npt ~= 1) error ("geometry:InvalidArgument", ... "plane and point should have same size or one of them must have a single row.\n"); end # compute 3D coordinate coord = plane(:,1:3) + ... plane(:,4:6) .* point(:,1) + ... plane(:,7:9) .* point(:,2) endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/circle3dPoint.m0000644000000000000000000000013013066736044020137 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/circle3dPoint.m0000644000175000017500000000632613066736044020324 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} =} circle3dPoint (@var{circle},@var{pos}) ## Coordinates of a point on a 3D circle from its position ## ## ## Example ## @example ## circle = [0 0 0 1 45 45 0]; ## # Draw some points on a 3D circle ## figure; hold on; ## # origin point ## pos1 = 0; ## drawPoint3d(circle3dPoint(circle, pos1), 'ro') ## # few points regularly spaced ## for i = 10:10:40 ## drawPoint3d(circle3dPoint(circle, i)) ## end ## # Draw point opposite to origin ## drawPoint3d(circle3dPoint(circle, 180), 'k*') ## @end example ## ## @seealso{circles3d, circle3dPosition} ## @end deftypefn function point = circle3dPoint(circle, pos) # extract circle coordinates xc = circle(1); yc = circle(2); zc = circle(3); r = circle(4); theta = circle(5); phi = circle(6); psi = circle(7); # convert position to angle t = pos * pi / 180; # compute position on base circle x = r * cos(t); y = r * sin(t); z = 0; pt0 = [x y z]; # compute transformation from local basis to world basis trans = localToGlobal3d (xc, yc, zc, theta, phi, psi); # compute points of transformed circle point = transformPoint3d (pt0, trans); endfunction %!demo %! # Draw some points on a 3D circle %! circle = [0 0 0 1 45 45 0]; %! figure; %! %! drawCircle3d(circle); %! hold on; %! %! # origin point %! pos1 = 0; %! drawPoint3d(circle3dPoint(circle, pos1), 'go') %! # few points regularly spaced %! for i = 10:10:90 %! drawPoint3d(circle3dPoint(circle, i)) %! end %! # Draw point opposite to origin %! drawPoint3d(circle3dPoint(circle, 180), 'k*') %! axis square equal; %! view(70,30) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/private0000644000000000000000000000013213066736044016656 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/private/0002755000175000017500000000000013066736044017111 5ustar00olafolaf00000000000000geometry-3.0.0/inst/geom3d/private/PaxHeaders.28738/localToGlobal3d.m0000644000000000000000000000013213066736044022056 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/private/localToGlobal3d.m0000644000175000017500000001027313066736044022235 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{} =} localToGlobal3d (@var{center}, @var{theta},@var{phi},@var{psi}) ## Transformation matrix from local to global coordinate system ## ## TRANS = localToGlobal3d(CENTER, THETA, PHI, PSI) ## Compute the transformation matrix from a local (or modelling) ## coordinate system to the global (or world) coordinate system. ## This is a low-level function, used by several drawing functions. ## ## The transform is defined by: ## - CENTER: the position of the local origin into the World coordinate ## system ## - THETA: colatitude, defined as the angle with the Oz axis (between 0 ## and 180 degrees), positive in the direction of the of Oy axis. ## - PHI: azimut, defined as the angle of the normal with the Ox axis, ## between 0 and 360 degrees ## - PSI: intrinsic rotation, corresponding to the rotation of the object ## around the direction vector, between 0 and 360 degrees ## ## The resulting transform is obtained by applying (in that order): ## - Rotation by PSI around he Z-axis ## - Rotation by THETA around the Y-axis ## - Rotation by PHI around the Z-axis ## - Translation by vector CENTER ## This corresponds to Euler ZYZ rotation, using angles PHI, THETA and ## PSI. ## ## The 'createEulerAnglesRotation' function may better suit your needs as ## it is more 'natural'. ## ## @seealso{transforms3d, createEulerAnglesRotation} ## @end deftypefn function trans = localToGlobal3d(varargin) ## extract the components of the transform if nargin == 1 ## all components are bundled in the first argument var = varargin{1}; center = var(1:3); theta = var(4); phi = var(5); psi = 0; if length(var) > 5 psi = var(6); end elseif nargin == 4 ## arguments = center, then the 3 angles center = varargin{1}; theta = varargin{2}; phi = varargin{3}; psi = varargin{4}; elseif nargin > 4 ## center is given in 3 arguments, then 3 angles center = [varargin{1} varargin{2} varargin{3}]; theta = varargin{4}; phi = varargin{5}; psi = 0; if nargin > 5 psi = varargin{6}; end end ## conversion from degrees to radians k = pi / 180; ## rotation around normal vector axis rot1 = createRotationOz(psi * k); ## colatitude rot2 = createRotationOy(theta * k); ## longitude rot3 = createRotationOz(phi * k); ## shift center tr = createTranslation3d(center); ## create final transform by concatenating transforms trans = tr * rot3 * rot2 * rot1; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/boxes3d.m0000644000000000000000000000013013066736044017004 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/boxes3d.m0000644000175000017500000000413313066736044017163 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} boxes3d () ## BOXES3D Description of functions operating on 3D boxes ## ## A box defined by its coordinate extents: ## BOX = [XMIN XMAX YMIN YMAX ZMIN ZMAX]. ## ## Example ## # Draw a polyhedron together with its bounding box ## [n e f]= createIcosahedron; ## drawPolyhedron(n, f); ## hold on; ## drawBox3d(point3dBounds(n)) ## ## ## @seealso{point3dBounds, box3dVolume, drawBox3d ## intersectBoxes3d, mergeBoxes3d, randomPointInBox3d} ## @end deftypefn function boxes3d() help boxes3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/normalizePlane.m0000644000000000000000000000013213066736044020417 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/normalizePlane.m0000644000175000017500000000531713066736044020601 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{plane2} =} normalizePlane (@var{plane1}) ## Normalize parametric representation of a plane ## ## PLANE2 = normalizePlane(PLANE1); ## Transforms the plane PLANE1 in the following format: ## [X0 Y0 Z0 DX1 DY1 DZ1 DX2 DY2 DZ2], where: ## - (X0, Y0, Z0) is a point belonging to the plane ## - (DX1, DY1, DZ1) is a first direction vector ## - (DX2, DY2, DZ2) is a second direction vector ## into another plane, with the same format, but with: ## - (x0 y0 z0) is the closest point of plane to the origin ## - (DX1 DY1 DZ1) has norm equal to 1 ## - (DX2 DY2 DZ2) has norm equal to 1 and is orthogonal to (DX1 DY1 DZ1) ## ## @seealso{planes3d, createPlane} ## @end deftypefn function plane2 = normalizePlane (plane1) # compute first direction vector d1 = normalizeVector (plane1(:,4:6)); # compute second direction vector n = normalizeVector (planeNormal (plane1)); d2 = -normalizeVector (cross (d1, n, 2)); # compute origin point of the plane origins = zeros (size (plane1, 1), 3); p0 = projPointOnPlane (origins, [plane1(:,1:3) d1 d2]); # create the resulting plane plane2 = [p0 d1 d2]; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawSphere.m0000644000000000000000000000013213066736044017543 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawSphere.m0000644000175000017500000001323213066736044017720 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{} =} function_name (@var{}, @var{}) ## Draw a sphere as a mesh ## ## drawSphere(SPHERE) ## Where SPHERE = [XC YC ZC R], draw the sphere centered on the point with ## coordinates [XC YC ZC] and with radius R, using a quad mesh. ## ## drawSphere(CENTER, R) ## Where CENTER = [XC YC ZC], specifies the center and the radius with two ## arguments. ## ## drawSphere(XC, YC, ZC, R) ## Specifiy sphere center and radius as four arguments. ## ## drawSphere(..., NAME, VALUE); ## Specifies one or several options using parameter name-value pairs. ## Available options are usual drawing options, as well as: ## 'nPhi' the number of arcs used for drawing the meridians ## 'nTheta' the number of circles used for drawing the parallels ## ## H = drawSphere(...) ## Return a handle to the graphical object created by the function. ## ## [X Y Z] = drawSphere(...) ## Return the coordinates of the vertices used by the sphere. In this ## case, the sphere is not drawn. ## ## Run @code{demo drawSphere} to see several examples. ## ## @seealso{spheres, circles3d, sphere, drawEllipsoid} ## @end deftypefn function varargout = drawSphere(varargin) # process input options: when a string is found, assumes this is the # beginning of options options = {'FaceColor', 'g', 'linestyle', 'none'}; for i=1:length(varargin) if ischar(varargin{i}) options = [options(1:end) varargin(i:end)]; varargin = varargin(1:i-1); break; end end # Parse the input (try to extract center coordinates and radius) if isempty(varargin) # no input: assumes unit sphere xc = 0; yc = 0; zc = 0; r = 1; elseif length(varargin) == 1 # one argument: concatenates center and radius sphere = varargin{1}; xc = sphere(:,1); yc = sphere(:,2); zc = sphere(:,3); r = sphere(:,4); elseif length(varargin) == 2 # two arguments, corresponding to center and radius center = varargin{1}; xc = center(1); yc = center(2); zc = center(3); r = varargin{2}; elseif length(varargin) == 4 # four arguments, corresponding to XC, YX, ZC and R xc = varargin{1}; yc = varargin{2}; zc = varargin{3}; r = varargin{4}; else error('drawSphere: please specify center and radius'); end # number of meridians nPhi = 32; ind = strmatch('nphi', lower(options(1:2:end))); if ~isempty(ind) ind = ind(1); nPhi = options{2*ind}; options(2*ind-1:2*ind) = []; end # number of parallels nTheta = 16; ind = strmatch('ntheta', lower(options(1:2:end))); if ~isempty(ind) ind = ind(1); nTheta = options{2*ind}; options(2*ind-1:2*ind) = []; end # compute spherical coordinates theta = linspace(0, pi, nTheta+1); phi = linspace(0, 2*pi, nPhi+1); # convert to cartesian coordinates sintheta = sin(theta); x = xc + cos(phi')*sintheta*r; y = yc + sin(phi')*sintheta*r; z = zc + ones(length(phi),1)*cos(theta)*r; # Process output if nargout == 0 # no output: draw the sphere surf(x, y, z, options{:}); elseif nargout == 1 # one output: compute varargout{1} = surf(x, y, z, options{:}); elseif nargout == 3 varargout{1} = x; varargout{2} = y; varargout{3} = z; end endfunction %!demo %! # Draw four spheres with different centers %! figure(1); clf; hold on; %! drawSphere([10 10 30 5]); %! drawSphere([20 30 10 5]); %! drawSphere([30 30 30 5]); %! drawSphere([30 20 10 5]); %! view([-30 20]); %! axis tight %! axis equal; %!demo %! # Draw sphere with different settings %! figure(1); clf; %! drawSphere([10 20 30 10], 'linestyle', ':', 'facecolor', 'r'); %! axis tight %! axis equal; %!demo %! # Draw sphere with different settings, but changes style using graphic handle %! figure(1); clf; %! h = drawSphere([10 20 30 10]); %! set(h, 'edgecolor', 'none'); %! set(h, 'facecolor', 'r'); %! axis tight %! axis equal; #%!demo #%! # Draw a sphere with high resolution #%! figure(1); clf; #%! h = drawSphere([10 20 30 10], 'nPhi', 360, 'nTheta', 180); #%! view(3); #%! axis equal; geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawEdge3d.m0000644000000000000000000000013213066736044017410 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawEdge3d.m0000644000175000017500000000535013066736044017567 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawEdge (@var{edge}) ## Draw 3D edge in the current Window ## ## draw the edge EDGE on the current axis. EDGE has the form: ## [x1 y1 z1 x2 y2 z2]. ## No clipping is performed. ## ## @end deftypefn function varargout = drawEdge3d(varargin) # extract edges from input arguments nCol = size(varargin{1}, 2); if nCol==6 # all parameters in a single array edges = varargin{1}; options = varargin(2:end); elseif nCol==3 # parameters are two points, or two arrays of points, of size N*3. edges = [varargin{1} varargin{2}]; options = varargin(3:end); elseif nCol==6 # parameters are 6 parameters of the edge : x1 y1 z1 x2 y2 and z2 edges = [varargin{1} varargin{2} varargin{3} varargin{4} varargin{5} varargin{6}]; options = varargin(7:end); end # draw edges h = line( [edges(:, 1) edges(:, 4)]', ... [edges(:, 2) edges(:, 5)]', ... [edges(:, 3) edges(:, 6)]', 'color', 'b'); # apply optional drawing style if ~isempty(options) set(h, options{:}); end # return handle to created Edges if nargout>0 varargout{1}=h; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawSphericalPolygon.m0000644000000000000000000000013213066736044021577 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawSphericalPolygon.m0000644000175000017500000000436513066736044021763 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{} =} drawSphericalPolygon (@var{sphere}, @var{poly}) ## Draw a spherical polygon ## ## @end deftypefn function varargout = drawSphericalPolygon(sphere, poly, varargin) nv = size(poly, 1); h = zeros(nv, 1); figure(gcf); holded = false; if ~ishold(gca) hold on holded = true; endif for i = 1:nv v1 = poly(i, :); v2 = poly(mod(i, nv) + 1, :); h(i) = drawSphericalEdge(sphere, [v1 v2], varargin{:}); end if holded hold off endif if nargout > 0 varargout = {h}; end endfunction %!demo %! p = full(eye(3)); %! s = [0 0 0 1]; %! drawSphericalPolygon (s,p,"r"); %! drawSphericalPolygon (2*s,p,"g"); %! view(40,35) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/createRotationOy.m0000644000000000000000000000013213066736044020732 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/createRotationOy.m0000644000175000017500000000720213066736044021107 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{trans} =} createRotationOy (@var{theta}) ## @deftypefnx {Function File} {@var{trans} =} createRotationOy (@var{origin},@var{theta}) ## @deftypefnx {Function File} {@var{trans} =} createRotationOy (@var{x0},@var{y0},@var{z0},@var{theta}) ## Create the 4x4 matrix of a 3D rotation around x-axis ## ## TRANS = createRotationOy(THETA); ## Returns the transform matrix corresponding to a rotation by the angle ## THETA (in radians) around the Oy axis. A rotation by an angle of PI/2 ## would transform the vector [0 1 0] into the vector [0 0 1]. ## ## The returned matrix has the form: ## [1 0 0 0] ## [0 cos(THETA) -sin(THETA) 0] ## [0 sin(THETA) cos(THETA) 0] ## [0 0 0 1] ## ## TRANS = createRotationOy(ORIGIN, THETA); ## TRANS = createRotationOy(X0, Y0, Z0, THETA); ## Also specifies origin of rotation. The result is similar as performing ## translation(-X0, -Y0, -Z0), rotation, and translation(X0, Y0, Z0). ## ## @seealso{transforms3d, transformPoint3d, createRotationOx, createRotationOz} ## @end deftypefn function trans = createRotationOy(varargin) # default values dx = 0; dy = 0; dz = 0; theta = 0; # get input values if length(varargin)==1 # only angle theta = varargin{1}; elseif length(varargin)==2 # origin point (as array) and angle var = varargin{1}; dx = var(1); dy = var(2); dz = var(3); theta = varargin{2}; elseif length(varargin)==3 # origin (x and y) and angle dx = varargin{1}; dy = 0; dz = varargin{2}; theta = varargin{3}; elseif length(varargin)==4 # origin (x and y) and angle dx = varargin{1}; dy = varargin{2}; dz = varargin{3}; theta = varargin{4}; end # compute coefs cot = cos(theta); sit = sin(theta); # create transformation trans = [... cot 0 sit 0;... 0 1 0 0;... -sit 0 cot 0;... 0 0 0 1]; # add the translation part t = [1 0 0 dx;0 1 0 dy;0 0 1 dz;0 0 0 1]; trans = t*trans/t; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/planes3d.m0000644000000000000000000000013213066736044017150 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/planes3d.m0000644000175000017500000000417413066736044017332 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} planes3d () ##PLANES3D Description of functions operating on 3D planes ## ## Planes are represented by a 3D point (the plane origin) and 2 direction ## vectors, which should not be colinear. ## PLANE = [X0 Y0 Z0 DX1 DY1 DZ1 DX2 DY2 DZ2]; ## ## @seealso{createPlane, medianPlane, normalizePlane, ## planeNormal, planePosition, dihedralAngle, ## intersectPlanes, projPointOnPlane, isBelowPlane, ## intersectLinePlane, intersectEdgePlane, distancePointPlane, drawPlane3d} ## @end deftypefn function planes3d(varargin) help planes3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/intersectPlaneSphere.m0000644000000000000000000000013213066736044021566 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/intersectPlaneSphere.m0000644000175000017500000000725113066736044021747 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{circ} =} intersectPlaneSphere(@var{plane}, @var{sphere}) ## Return intersection circle between a plane and a sphere ## ## Returns the circle which is the intersection of the given plane ## and sphere. ## @var{plane} : [x0 y0 z0 dx1 dy1 dz1 dx2 dy2 dz2] ## @var{sphere} : [XS YS ZS RS] ## @var{circ} : [XC YC ZC RC THETA PHI PSI] ## [x0 y0 z0] is the origin of the plane, [dx1 dy1 dz1] and [dx2 dy2 dz2] ## are two direction vectors, ## [XS YS ZS] are coordinates of the sphere center, RS is the sphere ## radius, ## [XC YC ZC] are coordinates of the circle center, RC is the radius of ## the circle, [THETA PHI] is the normal of the plane containing the ## circle (THETA being the colatitude, and PHI the azimut), and PSI is a ## rotation angle around the normal (equal to zero in this function, but ## kept for compatibility with other functions). All angles are given in ## degrees. ## ## @seealso{planes3d, spheres, circles3d, intersectLinePlane, intersectLineSphere} ## @end deftypefn function circle = intersectPlaneSphere(plane, sphere) # number of inputs of each type Ns = size(sphere, 1); Np = size(plane, 1); # unify data dimension if Ns ~= Np if Ns == 1 sphere = sphere(ones(Np, 1), :); elseif Np == 1 plane = plane(ones(Ns, 1), :); else error('data should have same length, or one data should have length 1'); end end # center of the spheres center = sphere(:,1:3); # radius of spheres if size(sphere, 2) == 4 Rs = sphere(:,4); else # assume default radius equal to 1 Rs = ones(size(sphere, 1), 1); end # projection of sphere center on plane -> gives circle center circle0 = projPointOnPlane(center, plane); # radius of circles d = distancePoints (center, circle0); Rc = sqrt(Rs.*Rs - d.*d); # normal of planes = normal of circles nor = planeNormal(plane); # convert to angles [theta phi] = cart2sph2(nor(:,1), nor(:,2), nor(:,3)); psi = zeros(Np, 1); # create structure for circle k = 180 / pi; circle = [circle0 Rc [theta phi psi]*k]; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawSphericalTriangle.m0000644000000000000000000000013213066736044021715 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawSphericalTriangle.m0000644000175000017500000000476313066736044022103 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} function_name (@var{sphere}, @var{p1},@var{p2},@var{p3}) ## Draw a triangle on a sphere ## @seealso{drawSphere, fillSphericalTriangle, drawSphericalPolygon} ## @end deftypefn function varargout = drawSphericalTriangle(sphere, p1, p2, p3, varargin) # extract data of the sphere ori = sphere(:, 1:3); # extract direction vectors for each point v1 = normalizeVector (p1 - ori); v2 = normalizeVector (p2 - ori); v3 = normalizeVector (p3 - ori); holded = false; if !ishold() hold on holded = true; endif h1 = drawSphericalEdge (sphere, [v1 v2], varargin{:}); h2 = drawSphericalEdge (sphere, [v2 v3], varargin{:}); h3 = drawSphericalEdge (sphere, [v3 v1], varargin{:}); if holded hold off endif if nargout > 0 varargout = {h1, h2, h3}; end endfunction %!demo %! p = full(eye(3)); %! s = [0 0 0 2]; %! drawSphericalTriangle (s,p(1,:),p(2,:),p(3,:),"r"); %! view(40,35) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawPoint3d.m0000644000000000000000000000013213066736044017635 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawPoint3d.m0000644000175000017500000000606613066736044020021 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawPoint3d (@var{x}, @var{y}, @var{z}) ## @deftypefnx {Function File} {@var{h} =} drawPoint3d (@var{coord}) ## @deftypefnx {Function File} {@var{h} =} drawPoint3d (@dots{}) ## Draw 3D point on the current axis. ## ## drawPoint3d(X, Y, Z) ## will draw points defined by coordinates X and Y. ## X and Y are N*1 array, with N being number of points to be drawn. ## ## drawPoint3d(COORD) ## packs coordinates in a single [N*3] array. ## ## drawPoint3d(..., OPT) ## will draw each point with given option. OPT is a string compatible with ## 'plot' model. ## ## H = drawPoint3d(...) ## Also return a handle to each of the drawn points. ## ## @seealso{points3d, clipPoints3d} ## @end deftypefn function varargout = drawPoint3d(varargin) var = varargin{1}; if size(var, 2)==3 # points are given as one single array with 3 columns px = var(:, 1); py = var(:, 2); pz = var(:, 3); varargin = varargin(2:end); elseif length(varargin)<3 error('wrong number of arguments in drawPoint3d'); else # points are given as 3 columns with equal length px = varargin{1}; py = varargin{2}; pz = varargin{3}; varargin = varargin(4:end); end # default draw style: no line, marker is 'o' if length(varargin)~=1 varargin = ['linestyle', 'none', 'marker', 'o', varargin]; end # plot only points inside the axis. h = plot3(px, py, pz, varargin{:}); if nargout>0 varargout{1} = h; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/linePosition3d.m0000644000000000000000000000013213066736044020342 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/linePosition3d.m0000644000175000017500000000562513066736044020526 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %LINEPOSITION3D Return the position of a 3D point projected on a 3D line % % T = linePosition3d(POINT, LINE) % Computes position of point POINT on the line LINE, relative to origin % point and direction vector of the line. % LINE has the form [x0 y0 z0 dx dy dy], % POINT has the form [x y z], and is assumed to belong to line. % The result T is the value such that POINT = LINE(1:3) + T * LINE(4:6). % If POINT does not belong to LINE, the position of its orthogonal % projection is computed instead. % % T = linePosition3d(POINT, LINES) % If LINES is an array of NL lines, return NL positions, corresponding to % each line. % % T = linePosition3d(POINTS, LINE) % If POINTS is an array of NP points, return NP positions, corresponding % to each point. % % See also: % lines3d, createLine3d, distancePointLine3d, projPointOnLine3d function pos = linePosition3d(point, line) % vector from line origin to point dp = bsxfun(@minus, point, line(:,1:3)); % direction vector of the line vl = line(:, 4:6); % precompute and check validity of denominator denom = sum(vl.^2, 2); invalidLine = denom < eps; denom(invalidLine) = 1; % compute position using dot product normalized with norm of line vector. pos = bsxfun(@rdivide, sum(bsxfun(@times, dp, vl), 2), denom); % position on a degenerated line is set to 0 pos(invalidLine) = 0; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/cart2sph2d.m0000644000000000000000000000013013066736044017411 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/cart2sph2d.m0000644000175000017500000000641013066736044017570 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{theta} @var{phi} @var{rho}] =} cart2sph2d (@var{coord}) ## @deftypefnx {Function File} {[@dots{}] =} cart2sph2d (@var{x},@var{y},@var{z}) ## Convert cartesian coordinates to spherical coordinates in degrees ## ## The following convention is used: ## THETA is the colatitude, in degrees, 0 for north pole, 180 degrees for ## south pole, 90 degrees for points with z=0. ## PHI is the azimuth, in degrees, defined as matlab cart2sph: angle from ## Ox axis, counted counter-clockwise. ## RHO is the distance of the point to the origin. ## Discussion on choice for convention can be found at: ## @url{http://www.physics.oregonstate.edu/bridge/papers/spherical.pdf} ## ## Example: ## @example ## cart2sph2d([1 0 0]) ## ans = ## 90 0 1 ## ## cart2sph2d([1 1 0]) ## ans = ## 90 45 1.4142 ## ## cart2sph2d([0 0 1]) ## ans = ## 0 0 1 ## @end example ## ## @seealso{angles3d, sph2cart2d, cart2sph, cart2sph2} ## @end deftypefn function varargout = cart2sph2d(x, y, z) # if data are grouped, extract each coordinate if nargin == 1 y = x(:, 2); z = x(:, 3); x = x(:, 1); end # cartesian to spherical conversion hxy = hypot(x, y); rho = hypot(hxy, z); theta = 90 - atan2(z, hxy) * 180 / pi; phi = atan2(y, x) * 180 / pi; # # convert to degrees and theta to colatitude # theta = 90 - rad2deg(theta); # phi = rad2deg(phi); # format output if nargout <= 1 varargout{1} = [theta phi rho]; elseif nargout == 2 varargout{1} = theta; varargout{2} = phi; else varargout{1} = theta; varargout{2} = phi; varargout{3} = rho; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/rotation3dAxisAndAngle.m0000644000000000000000000000013013066736044021742 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/rotation3dAxisAndAngle.m0000644000175000017500000000673513066736044022133 0ustar00olafolaf00000000000000## Copyright (C) 2003-2017 David Legland ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ## The views and conclusions contained in the software and documentation are ## those of the authors and should not be interpreted as representing official ## policies, either expressed or implied, of the copyright holders. function [axis, theta] = rotation3dAxisAndAngle(mat) %ROTATION3DAXISANDANGLE Determine axis and angle of a 3D rotation matrix % % [AXIS, ANGLE] = rotation3dAxisAndAngle(MAT) % Where MAT is a 4-by-4 matrix representing a rotation, computes the % rotation axis (containing the points that remain invariant under the % rotation), and the rotation angle around that axis. % AXIS has the format [DX DY DZ], constrained to unity, and ANGLE is the % rotation angle in radians. % % Note: this method use eigen vector extraction. It would be more precise % to use quaternions, see: % http://www.mathworks.cn/matlabcentral/newsreader/view_thread/160945 % % % Example % origin = [1 2 3]; % direction = [4 5 6]; % line = [origin direction]; % angle = pi/3; % rot = createRotation3dLineAngle(line, angle); % [axis angle2] = rotation3dAxisAndAngle(rot); % angle2 % angle2 = % 1.0472 % % See also % transforms3d, vectors3d, angles3d, eulerAnglesToRotation3d % % ------ % Author: David Legland % e-mail: david.legland@inra.fr % Created: 2010-08-11, using Matlab 7.9.0.529 (R2009b) % Copyright 2010 INRA - Cepia Software Platform. % extract the linear part of the rotation matrix A = mat(1:3, 1:3); % extract eigen values and eigen vectors [V, D] = eig(A - eye(3)); % we need the eigen vector corresponding to eigenvalue==1 [dummy, ind] = min(abs(diag(D)-1)); %#ok % extract corresponding eigen vector vector = V(:, ind)'; % compute rotation angle t = [A(3,2)-A(2,3) , A(1,3)-A(3,1) , A(2,1)-A(1,2)]; theta = atan2(dot(t, vector), trace(A)-1); % If angle is negative, invert both angle and vector direction if theta<0 theta = -theta; vector = -vector; end % try to get a point on the line % seems to work, but not sure about stability [V, D] = eig(mat-eye(4)); %#ok origin = V(1:3,4)'/V(4, 4); % create line corresponding to rotation axis axis = [origin vector]; geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawTorus.m0000644000000000000000000000013213066736044017431 xustar0030 mtime=1490795556.624870061 30 atime=1490795556.624870061 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawTorus.m0000644000175000017500000000545713066736044017620 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} drawTorus (@var{torus}) ## Draw a torus (3D ring) ## ## drawTorus(TORUS) ## Draws the torus on the current axis. TORUS is given by ## [XC YC ZY R1 R2 THETA PHI] ## where (XC YZ ZC) is the center of the torus, R1 is the main radius, R2 ## is the radius of the torus section, and (THETA PHI) is the angle of the ## torus normal vector (both in degrees). ## ## Example ## @example ## figure; ## drawTorus([50 50 50 30 10 30 45]); ## axis equal; ## @end example ## ## @seealso{drawEllipsoid, revolutionSurface} ## @end deftypefn function varargout = drawTorus(torus, varargin) center = torus(1:3); r1 = torus(4); r2 = torus(5); if size(torus, 2) >= 7 normal = torus(6:7); end # default drawing options varargin = [{'FaceColor', 'g'}, varargin]; # create base torus circle = circleAsPolygon ([r1 0 r2], 60); [x y z] = revolutionSurface (circle, linspace(0, 2*pi, 60)); # transform torus trans = localToGlobal3d ([center normal]); [x y z] = transformPoint3d (x, y, z, trans); # draw the surface hs = surf(x, y, z, varargin{:}); if nargout > 0 varargout = {hs}; end endfunction %!demo %! figure; %! drawTorus([50 50 50 30 10 30 45]); %! axis square equal; %! view(45,40); geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawCircle3d.m0000644000000000000000000000013213066736044017745 xustar0030 mtime=1490795556.616869914 30 atime=1490795556.616869914 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawCircle3d.m0000644000175000017500000002067713066736044020135 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawCircle3d (@var{circle2d}, @var{normal}) ## @deftypefnx {Function File} {@var{h} =} drawCircle3d (@var{xc}, @var{yc}, @var{zc}, @var{r}, @var{theta}, @var{phi}, @var{psi}) ## Draw a 3D circle ## ## Possible calls for the function: ## drawCircle3d([XC YC ZC R THETA PHI]) ## drawCircle3d([XC YC ZC R], [THETA PHI]) ## ## where XC, YC, ZY are coordinates of circle center, R is the circle ## radius, PHI and THETA are 3D angles in degrees of the normal to the ## plane containing the circle: ## * THETA between 0 and 180 degrees, corresponding to the colatitude ## (angle with Oz axis). ## * PHI between 0 and 360 degrees corresponding to the longitude (angle ## with Ox axis) ## ## drawCircle3d([XC YC ZC R THETA PHI PSI]) ## drawCircle3d([XC YC ZC R], [THETA PHI PSI]) ## drawCircle3d([XC YC ZC R], THETA, PHI) ## drawCircle3d([XC YC ZC], R, THETA, PHI) ## drawCircle3d([XC YC ZC R], THETA, PHI, PSI) ## drawCircle3d([XC YC ZC], R, THETA, PHI, PSI) ## drawCircle3d(XC, YC, ZC, R, THETA, PHI) ## drawCircle3d(XC, YC, ZC, R, THETA, PHI, PSI) ## Are other possible syntaxes for this function. ## ## H = drawCircle3d(...) ## return handle on the created LINE object ## ## Example ## @example ## # display 3 mutually orthogonal 3D circles ## figure; hold on; ## drawCircle3d([10 20 30 50 0 0], 'LineWidth', 2, 'Color', 'b'); ## drawCircle3d([10 20 30 50 90 0], 'LineWidth', 2, 'Color', 'r'); ## drawCircle3d([10 20 30 50 90 90], 'LineWidth', 2, 'Color', 'g'); ## axis equal; ## axis([-50 100 -50 100 -50 100]); ## view([-10 20]) ## ## # Draw several circles at once ## center = [10 20 30]; ## circ1 = [center 50 0 0]; ## circ2 = [center 50 90 0]; ## circ3 = [center 50 90 90]; ## figure; hold on; ## drawCircle3d([circ1 ; circ2 ; circ3]); ## axis equal; ## @end example # ## @seealso{circles3d, drawCircleArc3d, drawEllipse3d, drawSphere} ## @end deftypefn function varargout = drawCircle3d(varargin) # Possible calls for the function, with number of arguments : # drawCircle3d([XC YC ZC R THETA PHI]) 1 # drawCircle3d([XC YC ZC R THETA PHI PSI]) 1 # drawCircle3d([XC YC ZC R], [THETA PHI]) 2 # drawCircle3d([XC YC ZC R], [THETA PHI PSI]) 2 # drawCircle3d([XC YC ZC R], THETA, PHI) 3 # drawCircle3d([XC YC ZC], R, THETA, PHI) 4 # drawCircle3d([XC YC ZC R], THETA, PHI, PSI) 4 # drawCircle3d([XC YC ZC], R, THETA, PHI, PSI) 5 # drawCircle3d(XC, YC, ZC, R, THETA, PHI) 6 # drawCircle3d(XC, YC, ZC, R, THETA, PHI, PSI) 7 # extract drawing options ind = find(cellfun(@ischar, varargin), 1, 'first'); options = {}; if ~isempty(ind) options = varargin(ind:end); varargin(ind:end) = []; end # Extract circle data if length(varargin) == 1 # get center and radius circle = varargin{1}; xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); r = circle(:,4); # get colatitude of normal if size(circle, 2) >= 5 theta = circle(:,5); else theta = zeros(size(circle, 1), 1); end # get azimut of normal if size(circle, 2)>=6 phi = circle(:,6); else phi = zeros(size(circle, 1), 1); end # get roll if size(circle, 2)==7 psi = circle(:,7); else psi = zeros(size(circle, 1), 1); end elseif length(varargin) == 2 # get center and radius circle = varargin{1}; xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); r = circle(:,4); # get angle of normal angle = varargin{2}; theta = angle(:,1); phi = angle(:,2); # get roll if size(angle, 2)==3 psi = angle(:,3); else psi = zeros(size(angle, 1), 1); end elseif length(varargin) == 3 # get center and radius circle = varargin{1}; xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); r = circle(:,4); # get angle of normal and roll theta = varargin{2}; phi = varargin{3}; psi = zeros(size(phi, 1), 1); elseif length(varargin) == 4 # get center and radius circle = varargin{1}; xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); if size(circle, 2)==4 r = circle(:,4); theta = varargin{2}; phi = varargin{3}; psi = varargin{4}; else r = varargin{2}; theta = varargin{3}; phi = varargin{4}; psi = zeros(size(phi, 1), 1); end elseif length(varargin) == 5 # get center and radius circle = varargin{1}; xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); r = varargin{2}; theta = varargin{3}; phi = varargin{4}; psi = varargin{5}; elseif length(varargin) == 6 xc = varargin{1}; yc = varargin{2}; zc = varargin{3}; r = varargin{4}; theta = varargin{5}; phi = varargin{6}; psi = zeros(size(phi, 1), 1); elseif length(varargin) == 7 xc = varargin{1}; yc = varargin{2}; zc = varargin{3}; r = varargin{4}; theta = varargin{5}; phi = varargin{6}; psi = varargin{7}; else error('drawCircle3d: please specify center and radius'); end # circle parametrisation (by using N=60, some vertices are located at # special angles like 45°, 30°...) Nt = 60; t = linspace(0, 2*pi, Nt+1); nCircles = length(xc); h = zeros(nCircles, 1); for i = 1:nCircles # compute position of circle points x = r(i) * cos(t)'; y = r(i) * sin(t)'; z = zeros(length(t), 1); circle0 = [x y z]; # compute transformation from local basis to world basis trans = localToGlobal3d(xc(i), yc(i), zc(i), theta(i), phi(i), psi(i)); # compute points of transformed circle circle = transformPoint3d(circle0, trans); # draw the curve of circle points h(i) = drawPolyline3d(circle, options{:}); end if nargout > 0 varargout = {h}; end endfunction %!demo %! # display 3 mutually orthogonal 3D circles %! figure; hold on; %! drawCircle3d([10 20 30 50 0 0], 'LineWidth', 2, 'Color', 'b'); %! drawCircle3d([10 20 30 50 90 0], 'LineWidth', 2, 'Color', 'r'); %! drawCircle3d([10 20 30 50 90 90], 'LineWidth', 2, 'Color', 'g'); %! axis square equal; %! axis([-50 100 -50 100 -50 100]); %! view([-10 20]) %! %! # Draw several circles at once %! center = [10 20 30]; %! circ1 = [center 50 0 0]; %! circ2 = [center 50 90 0]; %! circ3 = [center 50 90 90]; %! figure; hold on; %! drawCircle3d([circ1 ; circ2 ; circ3]); %! axis square equal; geometry-3.0.0/inst/geom3d/PaxHeaders.28738/vectors3d.m0000644000000000000000000000013013066736044017351 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/vectors3d.m0000644000175000017500000000404313066736044017530 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} vectors3d () ##VECTORS3D Description of functions operating on 3D vectors ## ## Vectors are represented by their 3 Cartesian coordinates: ## V = [VX VY VZ]; ## ## List of vectors are represented by N*3 arrays, with the coordinates of ## each vector on a row. ## ## ## @seealso{vectorNorm3d, normalizeVector3d, vectorAngle3d isParallel3d, ## isPerpendicular3d, createTranslation3d} ## @end deftypefn function vectors3d(varargin) help vectors3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/transformPoint3d.m0000644000000000000000000000013013066736044020711 xustar0029 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/transformPoint3d.m0000644000175000017500000001211613066736044021070 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pt2} =} transformPoint3d (@var{pt1}, @var{trans}) ## @deftypefnx {Function File} {@var{pt2} =} transformPoint3d (@var{x1},@var{y1},@var{z1}, @var{trans}) ## @deftypefnx {Function File} {[@var{x2},@var{y2},@var{z2}] =} transformPoint3d (@dots{}) ## Transform a point with a 3D affine transform ## ## PT2 = transformPoint3d(PT1, TRANS); ## PT2 = transformPoint3d(X1, Y1, Z1, TRANS); ## where PT1 has the form [xp yp zp], and TRANS is a [3x3], [3x4], [4x4] ## matrix, return the point transformed according to the affine transform ## specified by TRANS. ## ## Format of TRANS is a 4-by-4 matrix. ## ## The function accepts transforms given using the following formats: ## [a b c] , [a b c j] , or [a b c j] ## [d e f] [d e f k] [d e f k] ## [g h i] [g h i l] [g h i l] ## [0 0 0 1] ## ## PT2 = transformPoint3d(PT1, TRANS) ## also work when PT1 is a [Nx3xMxPxETC] array of double. In this case, ## PT2 has the same size as PT1. ## ## PT2 = transformPoint3d(X1, Y1, Z1, TRANS); ## also work when X1, Y1 and Z1 are 3 arrays with the same size. In this ## case, PT2 will be a 1-by-3 cell containing @{X Y Z@} outputs of size(X1). ## ## [X2 Y2 Z2] = transformPoint3d(@dots{}); ## returns the result in 3 different arrays the same size as the input. ## This form can be useful when used with functions like meshgrid or warp. ## ## @seealso{points3d, transforms3d, translation3d,meshgrid} ## @end deftypefn function varargout = transformPoint3d(varargin) # process input arguments if length(varargin) == 2 # Point coordinates are given in a single N-by-3-by-M-by-etc argument. # Preallocate x, y, and z to size N-by-1-by-M-by-etc, then fill them in dim = size(varargin{1}); dim(2) = 1; [x,y,z] = deal(zeros(dim,class(varargin{1}))); x(:) = varargin{1}(:,1,:); y(:) = varargin{1}(:,2,:); z(:) = varargin{1}(:,3,:); trans = varargin{2}; elseif length(varargin) == 4 # Point coordinates are given in 3 different arrays x = varargin{1}; y = varargin{2}; z = varargin{3}; dim = size(x); trans = varargin{4}; end # eventually add null translation if size(trans, 2) == 3 trans = [trans zeros(size(trans, 1), 1)]; end # eventually add normalization if size(trans, 1) == 3 trans = [trans;0 0 0 1]; end # convert coordinates NP = numel(x); try # vectorial processing, if there is enough memory #res = (trans*[x(:) y(:) z(:) ones(NP, 1)]')'; #res = [x(:) y(:) z(:) ones(NP, 1)]*trans'; res = [x(:) y(:) z(:) ones(NP,1,class(x))] * trans'; # Back-fill x,y,z with new result (saves calling costly reshape()) x(:) = res(:,1); y(:) = res(:,2); z(:) = res(:,3); catch ME disp(ME.message) # process each point one by one, writing in existing array for i = 1:NP res = [x(i) y(i) z(i) 1] * trans'; x(i) = res(1); y(i) = res(2); z(i) = res(3); end end # process output arguments if nargout <= 1 # results are stored in a unique array if length(dim) > 2 && dim(2) > 1 warning('geom3d:shapeMismatch',... 'Shape mismatch: Non-vector xyz input should have multiple x,y,z output arguments. Cell {x,y,z} returned instead.') varargout{1} = {x,y,z}; else varargout{1} = [x y z]; end elseif nargout == 3 varargout{1} = x; varargout{2} = y; varargout{3} = z; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/circles3d.m0000644000000000000000000000013013066736044017310 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/circles3d.m0000644000175000017500000000451113066736044017467 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} circles3d () ##CIRCLES3D Description of functions operating on 3D circles ## ## Circles are represented by a center, a radius and a 3D angle ## representing the normal of the plane containing the circle. ## C = [xc yc zc R theta phi psi]. ## THETA is the colatitude of the normal, in degrees, between 0 and 180 ## PHI is the azimut of the normal, in degrees, between 0 and 360 ## PSI is the proper rotation of the circle around the normal, between 0 ## and 360 degrees ## The parameter PSI is used to locate a point on the 3D circle. ## ## @seealso{circle3dOrigin, circle3dPosition, circle3dPoint, intersectPlaneSphere ## drawCircle3d, drawCircleArc3d, drawEllipse3d} ## @end deftypefn function circles3d () help circles3d endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/planePosition.m0000644000000000000000000000013213066736044020263 xustar0030 mtime=1490795556.628870136 30 atime=1490795556.628870136 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/planePosition.m0000644000175000017500000000543713066736044020450 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pt2} =} planePosition (@var{point}, @var{plane}) ## Compute position of a point on a plane ## ## PT2 = planePosition(POINT, PLANE) ## POINT has format [X Y Z], and plane has format ## [X0 Y0 Z0 DX1 DY1 DZ1 DX2 DY2 DZ2], where : ## - (X0, Y0, Z0) is a point belonging to the plane ## - (DX1, DY1, DZ1) is a first direction vector ## - (DX2, DY2, DZ2) is a second direction vector ## ## Result PT2 has the form [XP YP], with [XP YP] coordinate of the point ## in the coordinate system of the plane. ## ## ## CAUTION: ## WORKS ONLY FOR PLANES WITH ORTHOGONAL DIRECTION VECTORS ## ## @seealso{planes3d, points3d, planePoint} ## @end deftypefn function pos = planePosition(point, plane) # unify size of data if size (point, 1) ~= size (plane, 1) if size (point, 1) == 1 point = repmat (point, [size(plane, 1) 1]); elseif size (plane, 1) == 1 plane = repmat (plane, [size(point, 1) 1]); else error ('point and plane do not have the same dimension'); end end p0 = plane(:, 1:3); d1 = plane(:, 4:6); d2 = plane(:, 7:9); s = dot (point-p0, d1, 2) ./ vectorNorm (d1); t = dot (point-p0, d2, 2) ./ vectorNorm (d2); pos = [s t]; endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/box3dVolume.m0000644000000000000000000000013013066736044017644 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/box3dVolume.m0000644000175000017500000000407113066736044020024 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{v} =} box3dVolume (@var{box}) ## Volume of a 3-dimensional box ## ## A box is represented as a set of limits in each direction: ## BOX = [XMIN XMAX YMIN YMAX ZMIN ZMAX]. ## ## Example ## @example ## [n e f] = createCubeOctahedron; ## box = boundingBox3d(n); ## vol = box3dVolume(box) ## vol = ## 8 ## @end example ## ## @seealso{boxes3d, boundingBox3d} ## @end deftypefn function vol = box3dVolume(box) vol = prod(box(:, 2:2:end) - box(:, 1:2:end), 2); endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/cart2sph2.m0000644000000000000000000000013013066736044017245 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/cart2sph2.m0000644000175000017500000000604513066736044017430 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{theta} @var{phi} @var{rho}] =} cart2sph2([@var{x} @var{y} @var{z}]) ## @deftypefnx {Function File} {[@var{theta} @var{phi} @var{rho}] =} cart2sph2(@var{x}, @var{y}, @var{z}) ## Convert cartesian coordinates to spherical coordinates ## ## The following convention is used: ## @var{theta} is the colatitude, in radians, 0 for north pole, +pi for south ## pole, pi/2 for points with z=0. ## @var{phi} is the azimuth, in radians, defined as matlab cart2sph: angle from ## Ox axis, counted counter-clockwise. ## @var{rho} is the distance of the point to the origin. ## Discussion on choice for convention can be found at: ## @url{http://www.physics.oregonstate.edu/bridge/papers/spherical.pdf} ## ## Example: ## @example ## cart2sph2([1 0 0]) returns [pi/2 0 1]; ## cart2sph2([1 1 0]) returns [pi/2 pi/4 sqrt(2)]; ## cart2sph2([0 0 1]) returns [0 0 1]; ## @end example ## ## @seealso{angles3d, sph2cart2, cart2sph, cart2sph2d} ## @end deftypefn function varargout = cart2sph2(varargin) if length(varargin)==1 var = varargin{1}; elseif length(varargin)==3 var = [varargin{1} varargin{2} varargin{3}]; end if size(var, 2)==2 var(:,3)=1; end [p t r] = cart2sph(var(:,1), var(:,2), var(:,3)); if nargout == 1 || nargout == 0 varargout{1} = [pi/2-t p r]; elseif nargout==2 varargout{1} = pi/2-t; varargout{2} = p; else varargout{1} = pi/2-t; varargout{2} = p; varargout{3} = r; end endfunction geometry-3.0.0/inst/geom3d/PaxHeaders.28738/drawPolygon3d.m0000644000000000000000000000013213066736044020173 xustar0030 mtime=1490795556.620869987 30 atime=1490795556.620869987 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/drawPolygon3d.m0000644000175000017500000000756213066736044020361 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawPolygon3d (@var{poly}) ## @deftypefnx {Function File} {@var{h} =} drawPolygon3d (@var{px},@var{py},@var{pz}) ## @deftypefnx {Function File} {@var{h} =} drawPolygon3d (@dots{},@var{param},@var{value}) ## Draw a 3D polygon specified by a list of vertices ## ## drawPolygon3d(POLY); ## packs coordinates in a single N-by-3 array. ## ## drawPolygon3d(PX, PY, PZ); ## specifies coordinates in separate arrays. ## ## drawPolygon3d(..., PARAM, VALUE); ## Specifies style options to draw the polyline, see plot for details. ## ## H = drawPolygon3d(...); ## also return a handle to the list of line objects. ## ## @seealso{polygons3d, fillPolygon3d, drawPolyline3d} ## @end deftypefn function varargout = drawPolygon3d(varargin) # check case we want to draw several curves, stored in a cell array var = varargin{1}; if iscell(var) holded = false; if !ishold() hold on; holded = true; end h = []; for i = 1:length(var(:)) h = [h; drawPolygon3d(var{i}, varargin{2:end})]; ##ok end if holded hold off end if nargout > 0 varargout{1} = h; end return; end # extract curve coordinate if size(var, 2) == 1 # first argument contains x coord, second argument contains y coord # and third one the z coord px = var; if length(varargin) < 3 error('Wrong number of arguments in drawPolygon3d'); end py = varargin{2}; pz = varargin{3}; varargin = varargin(4:end); else # first argument contains both coordinate px = var(:, 1); py = var(:, 2); pz = var(:, 3); varargin = varargin(2:end); end ## draw the polygon # check that the polygon is closed if px(1) ~= px(end) || py(1) ~= py(end) || pz(1) ~= pz(end) px = [px; px(1)]; py = [py; py(1)]; pz = [pz; pz(1)]; end # draw the closed curve h = plot3(px, py, pz, varargin{:}); if nargout > 0 varargout = {h}; end endfunction %!demo %! l=0.25; %! # Corner Triangle with a wedge %! poly2 = [1 0 0; ... %! ([1 0 0]+l*[-1 1 0]); ... %! mean(eye(3)); ... %! ([1 0 0]+(1-l)*[-1 1 0]); ... %! 0 1 0; ... %! 0 0 1]; %! drawPolygon3d(poly2) %! axis square %! axis equal %! view([74 26]) geometry-3.0.0/inst/geom3d/PaxHeaders.28738/circle3dPosition.m0000644000000000000000000000013013066736044020652 xustar0029 mtime=1490795556.61286984 29 atime=1490795556.61286984 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom3d/circle3dPosition.m0000644000175000017500000000546513066736044021042 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pos} =} circle3dPosition(@var{point}, @var{circle}) ## Return the angular position of a point on a 3D circle ## ## Returns angular position of point on the circle, in degrees, between 0 ## and 360. ## with @var{point}: [xp yp zp] ## and @var{circle}: [X0 Y0 Z0 R THETA PHI] or [X0 Y0 Z0 R THETA PHI PSI] ## (THETA being the colatitude, and PHI the azimut) ## ## @seealso{circles3d, circle3dOrigin, circle3dPoint} ## @end deftypefn function theta = circle3dPosition(point, circle) # get center and radius xc = circle(:,1); yc = circle(:,2); zc = circle(:,3); # get angle of normal theta = circle(:,5); phi = circle(:,6); # find origin of the circle ori = circle3dOrigin(circle); # normal vector of the supporting plane (cartesian coords) vn = sph2cart2d([theta phi]); # create plane containing the circle plane = createPlane([xc yc zc], vn); # find position of point on the circle plane pp0 = planePosition(ori, plane); pp = planePosition(point, plane); # compute angles in the planes theta0 = mod(atan2(pp0(:,2), pp0(:,1)) + 2*pi, 2*pi); theta = mod(atan2(pp(:,2), pp(:,1)) + 2*pi - theta0, 2*pi); # convert to degrees theta = theta * 180 / pi; endfunction geometry-3.0.0/inst/PaxHeaders.28738/geom2d0000644000000000000000000000013213066736044015203 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/0002755000175000017500000000000013066736044015436 5ustar00olafolaf00000000000000geometry-3.0.0/inst/geom2d/PaxHeaders.28738/clipEdge.m0000644000000000000000000000013213066736044017152 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/clipEdge.m0000644000175000017500000001703613066736044017335 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{edge2} =} clipEdge (@var{edge}, @var{box}) ## Clip an edge with a rectangular box. ## ## @var{edge}: [x1 y1 x2 y2], ## @var{box} : [xmin xmax ; ymin ymax] or [xmin xmax ymin ymax]; ## return : ## @var{edge2} = [xc1 yc1 xc2 yc2]; ## ## If clipping is null, return [0 0 0 0]; ## ## if @var{edge} is a [nx4] array, return an [nx4] array, corresponding to each ## clipped edge. ## ## @seealso{edges2d, boxes2d, clipLine} ## @end deftypefn function edge2 = clipEdge(edge, bb) # process data input if size(bb, 1)==2 bb = bb'; end # get limits of window xmin = bb(1); xmax = bb(2); ymin = bb(3); ymax = bb(4); # convert window limits into lines lineX0 = [xmin ymin xmax-xmin 0]; lineX1 = [xmin ymax xmax-xmin 0]; lineY0 = [xmin ymin 0 ymax-ymin]; lineY1 = [xmax ymin 0 ymax-ymin]; # compute outcodes of each vertex p11 = edge(:,1)xmax; p22 = edge(:,3)>xmax; p13 = edge(:,2)ymax; p24 = edge(:,4)>ymax; out1 = [p11 p12 p13 p14]; out2 = [p21 p22 p23 p24]; # detect edges totally inside window -> no clip. inside = sum(out1 | out2, 2)==0; # detect edges totally outside window outside = sum(out1 & out2, 2)>0; # select edges not totally outside, and process separately edges totally # inside window ind = find(~(inside | outside)); edge2 = zeros(size(edge)); edge2(inside, :) = edge(inside, :); for i=1:length(ind) # current edge iedge = edge(ind(i), :); # compute intersection points with each line of bounding window px0 = intersectLineEdge(lineX0, iedge); px1 = intersectLineEdge(lineX1, iedge); py0 = intersectLineEdge(lineY0, iedge); py1 = intersectLineEdge(lineY1, iedge); # create array of points points = [px0; px1; py0; py1; iedge(1:2); iedge(3:4)]; # remove infinite points (edges parallel to box edges) points = points(all(isfinite(points), 2), :); # sort points by x then y points = sortrows(points); # get center positions between consecutive points centers = (points(2:end,:) + points(1:end-1,:))/2; # find the centers (if any) inside window inside = find( centers(:,1)>=xmin & centers(:,2)>=ymin & ... centers(:,1)<=xmax & centers(:,2)<=ymax); # if multiple segments are inside box, which can happen due to finite # resolution, only take the longest segment if length(inside)>1 # compute delta vectors of the segments dv = points(inside+1,:) - points(inside,:); # compute lengths of segments len = hypot(dv(:,1), dv(:,2)); # find index of longest segment [a, I] = max(len); ##ok inside = inside(I); end # if one of the center points is inside box, then the according edge # segment is indide box if length(inside)==1 # restore same direction of edge if iedge(1)>iedge(3) || (iedge(1)==iedge(3) && iedge(2)>iedge(4)) edge2(i, :) = [points(inside+1,:) points(inside,:)]; else edge2(i, :) = [points(inside,:) points(inside+1,:)]; end end end # end of loop of edges endfunction %!demo %! bb = [0 100 0 100]; %! edge = [-10 10 90 110]; %! ec = clipEdge (edge, bb); %! %! drawBox(bb,'color','k'); %! line(edge([1 3]),edge([2 4]),'color','b'); %! line(ec([1 3]),ec([2 4]),'color','r','linewidth',2); %! axis tight %! v = axis (); %! axis(v+[0 10 -10 0]) %!shared bb %! bb = [0 100 0 100]; %!assert (clipEdge([20 30 80 60], bb), [20 30 80 60],1e-6); %!assert (clipEdge([0 30 80 60], bb), [0 30 80 60],1e-6); %!assert (clipEdge([0 30 100 60], bb), [0 30 100 60],1e-6); %!assert (clipEdge([30 0 80 100], bb), [30 0 80 100],1e-6); %!assert (clipEdge([0 0 100 100], bb), [0 0 100 100],1e-6); %!assert (clipEdge([0 100 100 0], bb), [0 100 100 0],1e-6); %!assert (clipEdge([20 60 120 60], bb), [20 60 100 60],1e-6); %!assert (clipEdge([-20 60 80 60], bb), [0 60 80 60],1e-6); %!assert (clipEdge([20 60 20 160], bb), [20 60 20 100],1e-6); %!assert (clipEdge([20 -30 20 60], bb), [20 0 20 60],1e-6); %!assert (clipEdge([120 30 180 60], bb), [0 0 0 0],1e-6); %!assert (clipEdge([-20 30 -80 60], bb), [0 0 0 0],1e-6); %!assert (clipEdge([30 120 60 180], bb), [0 0 0 0],1e-6); %!assert (clipEdge([30 -20 60 -80], bb), [0 0 0 0],1e-6); %!assert (clipEdge([-120 110 190 150], bb), [0 0 0 0],1e-6); %!assert ([50 50 100 50], clipEdge([50 50 150 50], bb),1e-6); %!assert ([50 50 0 50], clipEdge([50 50 -50 50], bb),1e-6); %!assert ([50 50 50 100], clipEdge([50 50 50 150], bb),1e-6); %!assert ([50 50 50 0], clipEdge([50 50 50 -50], bb),1e-6); %!assert ([80 50 100 70], clipEdge([80 50 130 100], bb),1e-6); %!assert ([80 50 100 30], clipEdge([80 50 130 0], bb),1e-6); %!assert ([20 50 0 70], clipEdge([20 50 -30 100], bb),1e-6); %!assert ([20 50 0 30], clipEdge([20 50 -30 0], bb),1e-6); %!assert ([50 80 70 100], clipEdge([50 80 100 130], bb),1e-6); %!assert ([50 80 30 100], clipEdge([50 80 0 130], bb),1e-6); %!assert ([50 20 70 0], clipEdge([50 20 100 -30], bb),1e-6); %!assert ([50 20 30 0], clipEdge([50 20 0 -30], bb),1e-6); %!assert ([100 50 50 50], clipEdge([150 50 50 50], bb),1e-6); %!assert ([0 50 50 50], clipEdge([-50 50 50 50], bb),1e-6); %!assert ([50 100 50 50], clipEdge([50 150 50 50], bb),1e-6); %!assert ([50 0 50 50], clipEdge([50 -50 50 50], bb),1e-6); %!assert ([100 70 80 50], clipEdge([130 100 80 50], bb),1e-6); %!assert ([100 30 80 50], clipEdge([130 0 80 50], bb),1e-6); %!assert ([0 70 20 50], clipEdge([-30 100 20 50], bb),1e-6); %!assert ([0 30 20 50], clipEdge([-30 0 20 50], bb),1e-6); %!assert ([70 100 50 80], clipEdge([100 130 50 80], bb),1e-6); %!assert ([30 100 50 80], clipEdge([0 130 50 80], bb),1e-6); %!assert ([70 0 50 20], clipEdge([100 -30 50 20], bb),1e-6); %!assert ([30 0 50 20], clipEdge([0 -30 50 20], bb),1e-6); %!assert ([0 20 80 100], clipEdge([-10 10 90 110], bb),1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPointOnEdge.m0000644000000000000000000000013213066736044020145 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPointOnEdge.m0000644000175000017500000002170413066736044020325 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPointOnEdge (@var{point}, @var{edge}) ## @deftypefnx {Function File} {@var{b} = } isPointOnEdge (@var{point}, @var{edge}, @var{tol}) ## @deftypefnx {Function File} {@var{b} = } isPointOnEdge (@var{point}, @var{edgearray}) ## @deftypefnx {Function File} {@var{b} = } isPointOnEdge (@var{pointarray}, @var{edgearray}) ## Test if a point belongs to an edge. # # with @var{point} being [xp yp], and @var{edge} being [x1 y1 x2 y2], returns TRUE if # the point is located on the edge, and FALSE otherwise. # # Specify an optilonal tolerance value @var{tol}. The tolerance is given as a # fraction of the norm of the edge direction vector. Default is 1e-14. # # When one of the inputs has several rows, return the result of the test # for each element of the array tested against the single parameter. # # When both @var{pointarray} and @var{edgearray} have the same number of rows, # returns a column vector with the same number of rows. # When the number of rows are different and both greater than 1, returns # a Np-by-Ne matrix of booleans, containing the result for each couple of # point and edge. # # @seealso{edges2d, points2d, isPointOnLine} ## @end deftypefn function b = isPointOnEdge(point, edge, varargin) # extract computation tolerance tol = 1e-14; if ~isempty(varargin) tol = varargin{1}; end # number of edges and of points Np = size(point, 1); Ne = size(edge, 1); # adapt size of inputs if needed, and extract elements for computation if Np == Ne # When the number of points and edges is the same, the one-to-one test # will be computed, so there is no need to repeat matrices dx = edge(:,3) - edge(:,1); dy = edge(:,4) - edge(:,2); lx = point(:,1) - edge(:,1); ly = point(:,2) - edge(:,2); elseif Np == 1 # one point, several edges dx = edge(:, 3) - edge(:, 1); dy = edge(:, 4) - edge(:, 2); lx = point(ones(Ne, 1), 1) - edge(:, 1); ly = point(ones(Ne, 1), 2) - edge(:, 2); elseif Ne == 1 # several points, one edge dx = (edge(3) - edge(1)) * ones(Np, 1); dy = (edge(4) - edge(2)) * ones(Np, 1); lx = point(:, 1) - edge(1); ly = point(:, 2) - edge(2); else # Np points and Ne edges: # Create an array for each parameter, so that the result will be a # Np-by-Ne matrix of booleans (requires more memory, and uses repmat) x0 = repmat(edge(:, 1)', Np, 1); y0 = repmat(edge(:, 2)', Np, 1); dx = repmat(edge(:,3)', Np, 1) - x0; dy = repmat(edge(:,4)', Np, 1) - y0; lx = repmat(point(:, 1), 1, Ne) - x0; ly = repmat(point(:, 2), 1, Ne) - y0; end # test if point is located on supporting line b1 = (abs(lx.*dy - ly.*dx) ./ hypot(dx, dy)) < tol; # compute position of point with respect to edge bounds # use different tests depending on line angle ind = abs(dx) > abs(dy); t = zeros(size(dx)); t(ind) = lx( ind) ./ dx( ind); t(~ind) = ly(~ind) ./ dy(~ind); # check if point is located between edge bounds b = t >- tol & t-1 < tol & b1; endfunction %!shared points, vertices, edges %!demo %! # create a point array %! points = [10 10;15 10; 30 10]; %! # create an edge array %! vertices = [10 10;20 10;20 20;10 20]; %! edges = [vertices vertices([2:end 1], :)]; %! %! # Test one point and one edge %! isPointOnEdge(points(1,:), edges(1,:)) %! isPointOnEdge(points(3,:), edges(1,:)) %!demo %! # create a point array %! points = [10 10;15 10; 30 10]; %! # create an edge array %! vertices = [10 10;20 10;20 20;10 20]; %! edges = [vertices vertices([2:end 1], :)]; %! %! # Test one point and several edges %! isPointOnEdge(points(1,:), edges)' %!demo %! # create a point array %! points = [10 10;15 10; 30 10]; %! # create an edge array %! vertices = [10 10;20 10;20 20;10 20]; %! edges = [vertices vertices([2:end 1], :)]; %! %! # Test several points and one edge %! isPointOnEdge(points, edges(1,:))' %!demo %! # create a point array %! points = [10 10;15 10; 30 10]; %! # create an edge array %! vertices = [10 10;20 10;20 20;10 20]; %! edges = [vertices vertices([2:end 1], :)]; %! %! # Test N points and N edges %! isPointOnEdge(points, edges(1:3,:))' %!demo %! # create a point array %! points = [10 10;15 10; 30 10]; %! # create an edge array %! vertices = [10 10;20 10;20 20;10 20]; %! edges = [vertices vertices([2:end 1], :)]; %! %! # Test NP points and NE edges %! isPointOnEdge(points, edges) %!test %! p1 = [10 20]; %! p2 = [80 20]; %! edge = [p1 p2]; %! p0 = [10 20]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [80 20]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [50 20]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [9.99 20]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [80.01 20]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [50 21]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [79 19]; %! assert (!isPointOnEdge(p0, edge)); %!test %! p1 = [20 10]; %! p2 = [20 80]; %! edge = [p1 p2]; %! p0 = [20 10]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [20 80]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [20 50]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [20 9.99]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [20 80.01]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [21 50]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [19 79]; %! assert (!isPointOnEdge(p0, edge)); %!test %! p1 = [10 20]; %! p2 = [60 70]; %! edge = [p1 p2]; %! assert (isPointOnEdge(p1, edge)); %! assert (isPointOnEdge(p2, edge)); %! p0 = [11 21]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [59 69]; %! assert (isPointOnEdge(p0, edge)); %! p0 = [9.99 19.99]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [60.01 70.01]; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [30 50.01]; %! assert (!isPointOnEdge(p0, edge)); %!test %! edge = [10 20 80 20; 20 10 20 80; 20 10 60 70]; %! p0 = [20 20]; %! assert ([true ; true ; false], isPointOnEdge(p0, edge)); %!test %! k = 1e15; %! p1 = [10 20]*k; %! p2 = [60 70]*k; %! edge = [p1 p2]; %! assert (isPointOnEdge(p1, edge)); %! assert (isPointOnEdge(p2, edge)); %! p0 = [11 21]*k; %! assert (isPointOnEdge(p0, edge)); %! p0 = [59 69]*k; %! assert (isPointOnEdge(p0, edge)); %! p0 = [9.99 19.99]*k; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [60.01 70.01]*k; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [30 50.01]*k; %! assert (!isPointOnEdge(p0, edge)); %!test %! k = 1e-10; %! p1 = [10 20]*k; %! p2 = [60 70]*k; %! edge = [p1 p2]; %! assert (isPointOnEdge(p1, edge)); %! assert (isPointOnEdge(p2, edge)); %! p0 = [11 21]*k; %! assert (isPointOnEdge(p0, edge)); %! p0 = [59 69]*k; %! assert (isPointOnEdge(p0, edge)); %! p0 = [9.99 19.99]*k; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [60.01 70.01]*k; %! assert (!isPointOnEdge(p0, edge)); %! p0 = [30 50.01]*k; %! assert (!isPointOnEdge(p0, edge)); %!test %! p1 = [10 20]; %! p2 = [80 20]; %! edge = [p1 p2]; %! p0 = [10 20; 80 20; 50 20;50 21]; %! exp = [true;true;true;false]; %! assert (exp, isPointOnEdge(p0, edge)); %!test %! p1 = [10 20]; %! p2 = [80 20]; %! edge = [p1 p2]; %! p0 = [40 20]; %! exp = [true;true;true;true]; %! assert (exp, isPointOnEdge(p0, [edge;edge;edge;edge])); %!test %! edge1 = [10 20 80 20]; %! edge2 = [30 10 30 80]; %! edges = [edge1; edge2]; %! p0 = [40 20;30 90]; %! exp = [true;false]; %! assert (exp, isPointOnEdge(p0, edges)); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/vectors2d.m0000644000000000000000000000013213066736044017351 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/vectors2d.m0000644000175000017500000000420213066736044017523 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} vectors2d () ## Description of functions operating on plane vectors ## ## A vector is defined by its two cartesian coordinates, put into a row ## vector of 2 elements: ## @code{V = [vx vy];} ## ## Several vectors are stored in a matrix with two columns, one for the ## x-coordinate, one for the y-coordinate. ## @code{VS = [vx1 vy1 ; vx2 vy2 ; vx3 vy3];} ## ## @seealso{vectorNorm, vectorAngle, isPerpendicular, isParallel, ## normalizeVector, transformVector, rotateVector} ## @end deftypefn function vectors2d help('vectors2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/polarPoint.m0000644000000000000000000000013213066736044017565 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/polarPoint.m0000644000175000017500000000606013066736044017743 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} = } polarPoint (@var{rho}, @var{theta}) ## @deftypefnx {Function File} {@var{point} = } polarPoint (@var{theta}) ## @deftypefnx {Function File} {@var{point} = } polarPoint (@var{point}, @var{rho}, @var{theta}) ## @deftypefnx {Function File} {@var{point} = } polarPoint (@var{x0}, @var{y0}, @var{rho}, @var{theta}) ##Create a point from polar coordinates (rho + theta) ## ## Creates a point using polar coordinate. @var{theta} is angle with horizontal ## (counted counter-clockwise, and in radians), and @var{rho} is the distance to ## origin. If only angle is given radius @var{rho} is assumed to be 1. ## ## If a point is given, adds the coordinate of the point to the coordinate of the specified ## point. For example, creating a point with : ## P = polarPoint([10 20], 30, pi/2); ## will give a result of [40 20]. ## ## @seealso{points2d} ## @end deftypefn function point = polarPoint(varargin) # default values x0 = 0; y0=0; rho = 1; theta =0; # process input parameters if length(varargin)==1 theta = varargin{1}; elseif length(varargin)==2 rho = varargin{1}; theta = varargin{2}; elseif length(varargin)==3 var = varargin{1}; x0 = var(:,1); y0 = var(:,2); rho = varargin{2}; theta = varargin{3}; elseif length(varargin)==4 x0 = varargin{1}; y0 = varargin{2}; rho = varargin{3}; theta = varargin{4}; end point = [x0 + rho.*cos(theta) , y0+rho.*sin(theta)]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/edgeLength.m0000644000000000000000000000013213066736044017504 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/edgeLength.m0000644000175000017500000000442513066736044017665 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{len} = } edgeLength (@var{edge}) ## Return length of an edge ## ## L = edgeLength(EDGE); ## Returns the length of an edge, with parametric representation: ## [x1 y1 x2 y2]. ## ## The function also works for several edges, in this case input is a ## [N*4] array, containing parametric representation of each edge, and ## output is a [N*1] array containing length of each edge. ## ## @seealso{edges2d, edgeAngle} ## @end deftypefn function len = edgeLength(varargin) # TODO : specify norm (euclidian, taxi, ...). nargs = length(varargin); if nargs == 1 edge = varargin{1}; len = sqrt(power(edge(:,3)-edge(:,1), 2) + power(edge(:,4)-edge(:,2), 2)); end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/circleArcAsCurve.m0000644000000000000000000000013213066736044020616 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/circleArcAsCurve.m0000644000175000017500000000543213066736044020776 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{p} = } circleArcAsCurve (@var{arc}, @var{N}) ## Convert a circle arc into a series of points ## ## P = circleArcAsCurve(ARC, N); ## convert the circle ARC into a series of N points. ## ARC is given in the format: [XC YC R THETA1 DTHETA] ## where XC and YC define the center of the circle, R its radius, THETA1 ## is the start of the arc and DTHETA is the angle extent of the arc. Both ## angles are given in degrees. ## N is the number of vertices of the resulting polyline, default is 65. ## ## The result is a N-by-2 array containing coordinates of the N points. ## ## [X Y] = circleArcAsCurve(ARC, N); ## Return the result in two separate arrays with N lines and 1 column. ## ## ## @seealso{circles2d, circleAsPolygon, drawCircle, drawPolygon} ## @end deftypefn function varargout = circleArcAsCurve(arc, N) # default value for N if nargin < 2 N = 65; end # vector of positions t0 = deg2rad(arc(4)); t1 = t0 + deg2rad(arc(5)); t = linspace(t0, t1, N)'; # compute coordinates of vertices x = arc(1) + arc(3) * cos(t); y = arc(2) + arc(3) * sin(t); # format output if nargout <= 1 varargout = {[x y]}; else varargout = {x, y}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createLineReflection.m0000644000000000000000000000013213066736044021524 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createLineReflection.m0000644000175000017500000000471013066736044021702 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } function_name (@var{line}) ## Create the the 3x3 matrix of a line reflection. ## ## Where @var{line} is given as [x0 y0 dx dy], return the affine tansform ## corresponding to the desired line reflection. ## ## @seealso{lines2d, transforms2d, transformPoint, ## createTranslation, createHomothecy, createScaling} ## @end deftypefn function trans = createLineReflection(line) # extract line parameters x0 = line(:,1); y0 = line(:,2); dx = line(:,3); dy = line(:,4); # normalisation coefficient of line direction vector delta = dx*dx + dy*dy; # compute coefficients of transform m00 = (dx*dx - dy*dy)/delta; m01 = 2*dx*dy/delta; m02 = 2*dy*(dy*x0 - dx*y0)/delta; m10 = 2*dx*dy/delta; m11 = (dy*dy - dx*dx)/delta; m12 = 2*dx*(dx*y0 - dy*x0)/delta; # create transformation trans = [m00 m01 m02; m10 m11 m12; 0 0 1]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/transformLine.m0000644000000000000000000000013213066736044020261 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/transformLine.m0000644000175000017500000000475413066736044020447 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line2} = } transformLine (@var{line1}, @var{T}) ## Transform a line with an affine transform. ## ## Returns the line @var{line1} transformed with affine transform @var{T}. ## @var{line1} has the form [x0 y0 dx dy], and @var{T} is a transformation ## matrix. ## ## Format of @var{T} can be one of : ## [a b] , [a b c] , or [a b c] ## [d e] [d e f] [d e f] ## [0 0 1] ## ## Also works when @var{line1} is a [Nx4] array of double. In this case, @var{line2} ## has the same size as @var{line1}. ## ## @seealso{lines2d, transforms2d, transformPoint} ## @end deftypefn function dest = transformLine(line, trans) # isolate points points1 = line(:, 1:2); points2 = line(:, 1:2) + line(:, 3:4); # transform points points1 = transformPoint(points1, trans); points2 = transformPoint(points2, trans); dest = createLine(points1, points2); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/angle3Points.m0000644000000000000000000000013213066736044020004 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/angle3Points.m0000644000175000017500000000552113066736044020163 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{alpha} =} angle3Points (@var{p1}, @var{p2}, @var{p3}) ## Computes the angle between the points @var{p1}, @var{p2} and @var{p3}. ## ## @var{p1}, @var{p2} and @var{p3} are either [1x2] arrays, or [Nx2] arrays, in this case ## @var{alpha} is a [Nx1] array. The angle computed is the directed angle between line ## (@var{p2}@var{p1}) and line (@var{p2}@var{p3}). ## ## Result is always given in radians, between 0 and 2*pi. ## ## @seealso{points2d, angles2d, angle2points} ## @end deftypefn function theta = angle3Points(varargin) if length(varargin)==3 p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; elseif length(varargin)==1 var = varargin{1}; p1 = var(1,:); p2 = var(2,:); p3 = var(3,:); end # angle line (P2 P1) theta = lineAngle(createLine(p2, p1), createLine(p2, p3)); endfunction %!test %! # all points inside window, possibly touching edges %! p1 = [10 0]; %! p2 = [0 0]; %! p3 = [0 10]; %! angle_ = angle3Points(p1, p2, p3); %! assert(pi/2, angle_,1e-6); %! angle_ = angle3Points([p1; p2; p3]); %! assert(pi/2, angle_, 1e-6); %!test %! p1 = [10 0; 20 0]; %! p2 = [0 0;0 0]; %! p3 = [0 10; 0 20]; %! angle_ = angle3Points(p1, p2, p3); %! assert(2, size(angle_, 1)); %! assert([pi/2;pi/2], angle_, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawRay.m0000644000000000000000000000013213066736044017047 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawRay.m0000644000175000017500000000463213066736044017230 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawRay (@var{ray}) ## @deftypefnx {Function File} {@var{h} = } drawRay (@var{ray}, @var{param}, @var{value}) ## Draw a ray on the current axis. ## ## With @var{ray} having the syntax: [x0 y0 dx dy], draws the ray starting from ## point (x0 y0) and going to direction (dx dy), clipped with the current ## window axis. @var{param}, @var{value} pairs are passed to function @code{line}. ## ## @seealso{rays2d, drawLine, line} ## @end deftypefn function varargout = drawRay(ray, varargin) # get bounding box limits bb = axis(gca); # compute clipped shapes [clipped isInside] = clipRay(ray, bb); # allocate memory for handle h = -ones(size(ray, 1), 1); # draw visible rays h(isInside) = drawEdge(clipped(isInside, :), varargin{:}); # process output if nargout>0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/transforms2d.m0000644000000000000000000000013213066736044020062 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/transforms2d.m0000644000175000017500000000444613066736044020246 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} transforms2d () ## Description of functions operating on transforms ## ## By 'transform' we mean an affine transform. A planar affine transform ## can be represented by a 3x3 matrix. ## ## Example ## ## @example ## # create a translation by the vector [10 20]: ## T = createTranslation([10 20]) ## T = ## 1 0 10 ## 0 1 20 ## 0 0 1 ##@end example ## ## @seealso{createTranslation, createRotation, createScaling, createBasisTransform, ## createHomothecy, createLineReflection, fitAffineTransform2d, ## transformPoint, transformVector, transformLine, transformEdge, ## rotateVector} ## @end deftypefn function transforms2d(varargin) help('transforms2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/bisector.m0000644000000000000000000000013213066736044017250 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/bisector.m0000644000175000017500000000760313066736044017432 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{ray} = } bisector (@var{line1}, @var{line2}) ## @deftypefnx {Function File} {@var{ray} = } bisector (@var{p1}, @var{p2}, @var{p3}) ## Return the bisector of two lines, or 3 points. ## ## Creates the bisector of the two lines, given as [x0 y0 dx dy]. ## ## create the bisector of lines (@var{p2} @var{p1}) and (@var{p2} @var{p3}). ## ## The result has the form [x0 y0 dx dy], with [x0 y0] being the origin ## point ans [dx dy] being the direction vector, normalized to have unit ## norm. ## ## @seealso{lines2d, rays2d} ## @end deftypefn function ray = bisector(varargin) if length(varargin)==2 # two lines line1 = varargin{1}; line2 = varargin{2}; point = intersectLines(line1, line2); elseif length(varargin)==3 # three points p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; line1 = createLine(p2, p1); line2 = createLine(p2, p3); point = p2; elseif length(varargin)==1 # three points, given in one array var = varargin{1}; p1 = var(1, :); p2 = var(2, :); p3 = var(3, :); line1 = createLine(p2, p1); line2 = createLine(p2, p3); point = p2; end # compute line angles a1 = lineAngle(line1); a2 = lineAngle(line2); # compute bisector angle (angle of first line + half angle between lines) angle = mod(a1 + mod(a2-a1+2*pi, 2*pi)/2, pi*2); # create the resulting ray ray = [point cos(angle) sin(angle)]; endfunction %!shared privpath %! privpath = [fileparts(which('geom2d_Contents')) filesep() 'private']; %!test %! addpath (privpath,'-end') %! p0 = [0 0]; %! p1 = [10 0]; %! p2 = [0 10]; %! line1 = createLine(p0, p1); %! line2 = createLine(p0, p2); %! ray = bisector(line1, line2); %! assertElementsAlmostEqual([0 0], ray(1,1:2)); %! assertAlmostEqual(pi/4, lineAngle(ray)); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! p0 = [0 0]; %! p1 = [10 0]; %! p2 = [0 10]; %! ray = bisector(p1, p0, p2); %! assertElementsAlmostEqual([0 0], ray(1,1:2)); %! assertAlmostEqual(pi/4, lineAngle(ray)); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! p0 = [0 0]; %! p1 = [10 0]; %! p2 = [0 10]; %! ray = bisector([p1; p0; p2]); %! assertElementsAlmostEqual([0 0], ray(1,1:2)); %! assertAlmostEqual(pi/4, lineAngle(ray)); %! rmpath (privpath); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/randomPointInBox.m0000644000000000000000000000013213066736044020670 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/randomPointInBox.m0000644000175000017500000000545413066736044021054 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{points} =} randomPointInBox (@var{box}) ## @deftypefnx {Function File} {@var{points} =} randomPointInBox (@var{box}, @var{n}) ## Generate random points within a box. ## ## Generate a random point within the box @var{box}. The result is a 1-by-2 row ## vector. If @var{n} is given, generates @var{n} points. The result is a ## @var{n}-by-2 array. ## ## Example ## ## @example ## # draw points within a box ## box = [10 80 20 60]; ## pts = randomPointInBox(box, 500); ## figure(1); clf; hold on; ## drawBox(box); ## drawPoint(pts, '.'); ## axis('equal'); ## axis([0 100 0 100]); ## @end example ## ## @seealso{edges2d, boxes2d, clipLine} ## @end deftypefn function points = randomPointInBox(box, N=1, varargin) # extract box bounds xmin = box(1); xmax = box(2); ymin = box(3); ymax = box(4); # compute size of box dx = xmax - xmin; dy = ymax - ymin; # compute point coordinates points = [rand(N, 1)*dx+xmin , rand(N, 1)*dy+ymin]; endfunction %!demo %! # draw points within a box %! bb = [10 80 20 60]; %! pts = randomPointInBox(bb, 500); %! figure(1); clf; hold on; %! drawBox(bb); %! drawPoint(pts, '.'); %! axis equal %! axis([0 100 0 100]); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/ellipses2d.m0000644000000000000000000000013213066736044017504 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/ellipses2d.m0000644000175000017500000000401013066736044017653 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} ellipses2d () ## Description of functions operating on ellipses. ## ## Ellipses are represented by their center, the length of their 2 ## semi-axes length, and their angle from the Ox direction (in degrees). ## E = [XC YC A B THETA]; ## ## @seealso{circles2d, inertiaEllipse, isPointInEllipse, ellipseAsPolygon ## drawEllipse, drawEllipseArc} ## @end deftypefn function ellipses2d(varargin) help('ellipses2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/boxes2d.m0000644000000000000000000000013213066736044017004 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/boxes2d.m0000644000175000017500000000407413066736044017165 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} boxes2d () ## Description of functions operating on bounding boxes. ## ## A box is represented as a set of limits in each direction: ## @example ## BOX = [XMIN XMAX YMIN YMAX]. ## @end example ## @noindent ## Boxes are used as result of computation for bounding boxes, and to clip ## shapes. ## ## @seealso{clipPoints, clipLine, clipEdge, clipRay, mergeBoxes, ## intersectBoxes, randomPointInBox, drawBox} ## @end deftypefn function boxes2d(varargin) help('boxes2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/distancePointLine.m0000644000000000000000000000013213066736044021052 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/distancePointLine.m0000644000175000017500000000542713066736044021236 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dist} = } distancePointLine (@var{point}, @var{line}) ## Minimum distance between a point and a line ## ## D = distancePointLine(POINT, LINE) ## Return the euclidean distance between line LINE and point POINT. ## ## LINE has the form : [x0 y0 dx dy], and POINT is [x y]. ## ## If LINE is N-by-4 array, result is N-by-1 array computes for each line. ## ## If POINT is N-by-2, then result is computed for each point. ## ## If both POINT and LINE are array, result is N-by-1, computed for each ## corresponding point and line. ## ## ## @seealso{lines2d, points2d, distancePoints, distancePointEdge} ## @end deftypefn function dist = distancePointLine (point, line) if size(line, 1)==1 && size(point, 1)>1 line = repmat(line, [size(point, 1) 1]); end if size(point, 1)==1 && size(line, 1)>1 point = repmat(point, [size(line, 1) 1]); end dx = line(:, 3); dy = line(:, 4); # compute position of points projected on line tp = ((point(:, 2) - line(:, 2)).*dy + (point(:, 1) - line(:, 1)).*dx) ./ (dx.*dx+dy.*dy); p0 = line(:, 1:2) + [tp tp].*[dx dy]; # compute distances between points and their projections dx = point - p0; dist = sqrt(sum(dx.*dx, 2)); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPointOnCircle.m0000644000000000000000000000013213066736044020502 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPointOnCircle.m0000644000175000017500000000455513066736044020667 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPointOnCircle (@var{point}, @var{circle}) ## Test if a point is located on a given circle. ## ## B = isPointOnCircle(POINT, CIRCLE) ## return true if point is located on the circle, i.e. if the distance to ## the circle center equals the radius up to an epsilon value. ## ## B = isPointOnCircle(POINT, CIRCLE, TOL) ## Specifies the tolerance value. ## ## Example: ## isPointOnCircle([1 0], [0 0 1]) ## returns true, whereas ## isPointOnCircle([1 1], [0 0 1]) ## return false ## ## @seealso{circles2d, isPointInCircle} ## @end deftypefn function b = isPointOnCircle(point, circle, varargin) tol = 1e-14; if ~isempty(varargin) tol = varargin{1}; end d = sqrt(sum(power(point - circle(:,1:2), 2), 2)); b = abs(d-circle(:,3)) ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dist} = } distancePointEdge (@var{point}, @var{edge}) ## @deftypefnx {Function File} {@var{dist} = } distancePointEdge (@dots{}, @var{opt}) ## @deftypefnx {Function File} {[@var{dist} @var{pos}]= } distancePointEdge (@dots{}) ## Minimum distance between a point and an edge ## ## Return the euclidean distance between edge @var{edge} and point @var{point}. ## @var{edge} has the form: [x1 y1 x2 y2], and @var{point} is [x y]. ## If @var{edge} is Ne-by-4 and @var{point} is Np-by-2, then @var{dist} is ## Np-by-Ne, where each row contains the distance of each point to all the edges. ## ## If @var{opt} is true (or equivalent), the optput is cmpatible with the original function: ## @table @samp ## @item 1 ## If @var{point} is 1-by-2 array, the result is Ne-by-1 array computed for each edge. ## @item 2 ## If @var{edge} is a 1-by-4 array, the result is Np-by-1 computed for each point. ## @item 3 ## If both @var{point} and @var{edge} are array, they must have the same number of ## rows, and the result is computed for each couple @code{@var{point}(i,:),@var{edge}(i,:)}. ## @end table ## ## If the the second output argument @var{pos} is requested, the function also ## returns the position of closest point on the edge. @var{pos} is comprised ## between 0 (first point) and 1 (last point). ## ## @seealso{edges2d, points2d, distancePoints, distancePointLine} ## @end deftypefn ## Rewritten to accept different numbers of points and edges. ## 2012 - Juan Pablo Carbajal function [dist, tp] = distancePointEdge(point, edge, opt=[]) Np = size (point,1); Ne = size (edge,1); edge = edge.'; # direction vector of each edge dx = edge(3,:) - edge(1,:); dy = edge(4,:) - edge(2,:); # compute position of points projected on the supporting line # (Size of tp is the max number of edges or points) delta = dx .* dx + dy .* dy; mask = delta < eps; delta(mask) = 1; warning ('off', 'Octave:broadcast','local'); tp = ((point(:, 1) - edge(1, :)) .* dx + ... (point(:, 2) - edge(2, :)) .* dy) ./ delta; tp(:,mask) = 0; # change position to ensure projected point is located on the edge tp(tp < 0) = 0; tp(tp > 1) = 1; # coordinates of projected point p0x = (edge(1,:) + tp .* dx); p0y = (edge(2,:) + tp .* dy); # compute distance between point and its projection on the edge dist = sqrt ((point(:,1) - p0x) .^ 2 + (point(:,2) - p0y) .^ 2); warning ('on', 'Octave:broadcast','local'); ## backwards compatibility if opt if Np != Ne && (Ne != 1 && Np !=1) error ("geometry:InvalidArgument", ... "Sizes must be equal or one of the inputs must be 1-by-N array."); end if Np == Ne dist = diag(dist)(:); tp = diag(tp)(:); elseif Np == 1 dist = dist.'; tp = tp.'; end end endfunction ## Original code ##tp = ((point(:, 1) - edge(:, 1)) .* dx + (point(:, 2) - edge(:, 2)) .* dy) ./ delta; ### ensure degenerated edges are correclty processed (consider the first ### vertex is the closest) ##if Ne > 1 ## tp(delta < eps) = 0; ##elseif delta < eps ## tp(:) = 0; ##end ### change position to ensure projected point is located on the edge ##tp(tp < 0) = 0; ##tp(tp > 1) = 1; ### coordinates of projected point ##p0 = [edge(:,1) + tp .* dx, edge(:,2) + tp .* dy]; ### compute distance between point and its projection on the edge ##dist = sqrt((point(:,1) - p0(:,1)) .^ 2 + (point(:,2) - p0(:,2)) .^ 2); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/transformEdge.m0000644000000000000000000000013213066736044020236 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/transformEdge.m0000644000175000017500000000541213066736044020414 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{edge2} = } transformEdge (@var{edge1}, @var{T}) ## Transform an edge with an affine transform. ## ## Where @var{edge1} has the form [x1 y1 x2 y1], and @var{T} is a transformation ## matrix, return the edge transformed with affine transform @var{T}. ## ## Format of TRANS can be one of : ## [a b] , [a b c] , or [a b c] ## [d e] [d e f] [d e f] ## [0 0 1] ## ## Also works when @var{edge1} is a [Nx4] array of double. In this case, @var{edge2} ## has the same size as @var{edge1}. ## ## @seealso{edges2d, transforms2d, transformPoint, translation, rotation} ## @end deftypefn function dest = transformEdge(edge, trans) dest = zeros(size(edge)); # compute position dest(:,1) = edge(:,1)*trans(1,1) + edge(:,2)*trans(1,2); dest(:,2) = edge(:,1)*trans(2,1) + edge(:,2)*trans(2,2); dest(:,3) = edge(:,3)*trans(1,1) + edge(:,3)*trans(1,2); dest(:,4) = edge(:,4)*trans(2,1) + edge(:,4)*trans(2,2); # add translation vector, if exist if size(trans, 2)>2 dest(:,1) = dest(:,1)+trans(1,3); dest(:,2) = dest(:,2)+trans(2,3); dest(:,3) = dest(:,3)+trans(1,3); dest(:,4) = dest(:,4)+trans(2,3); end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/projPointOnLine.m0000644000000000000000000000013213066736044020527 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/projPointOnLine.m0000644000175000017500000000542313066736044020707 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} = } projPointOnLine (@var{pt1}, @var{line}) ## Project of a point orthogonally onto a line ## ## Computes the (orthogonal) projection of point @var{pt1} onto the line @var{line}. ## ## Function works also for multiple points and lines. In this case, it ## returns multiple points. ## Point @var{pt1} is a [N*2] array, and @var{line} is a [N*4] array (see createLine ## for details). Result @var{point} is a [N*2] array, containing coordinates of ## orthogonal projections of @var{pt1} onto lines @var{line}. ## ## @seealso{lines2d, points2d, isPointOnLine, linePosition} ## @end deftypefn function point = projPointOnLine(point, line) # ensure input arguments have same size if size(line, 1)==1 && size(point, 1)>1 line = repmat(line, [size(point, 1) 1]); end if size(point, 1)==1 && size(line, 1)>1 point = repmat(point, [size(line, 1) 1]); end # slope of line dx = line(:, 3); dy = line(:, 4); # first find relative position of projection on the line, tp = ((point(:, 2) - line(:, 2)).*dy + (point(:, 1) - line(:, 1)).*dx) ./ (dx.*dx+dy.*dy); # convert position on line to cartesian coordinate point = line(:,1:2) + [tp tp].*[dx dy]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/angleSort.m0000644000000000000000000000013213066736044017374 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/angleSort.m0000644000175000017500000000627313066736044017560 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {varargout =} angleSort (@var{pts}, varargin) ## Sort points in the plane according to their angle to origin ## ## ## PTS2 = angleSort(PTS); ## Computes angle of points with origin, and sort points with increasing ## angles in Counter-Clockwise direction. ## ## PTS2 = angleSort(PTS, PTS0); ## Computes angles between each point of PTS and PT0, which can be ## different from origin. ## ## PTS2 = angleSort(..., THETA0); ## Specifies the starting angle for sorting. ## ## [PTS2, I] = angleSort(...); ## Also returns in I the indices of PTS, such that PTS2 = PTS(I, :); ## ## @seealso{points2d, angles2d, angle2points, normalizeAngle} ## @end deftypefn function varargout = angleSort(pts, varargin) # default values pt0 = [0 0]; theta0 = 0; if length(varargin)==1 var = varargin{1}; if size(var, 2)==1 # specify angle theta0 = var; else pt0 = var; end elseif length(varargin)==2 pt0 = varargin{1}; theta0 = varargin{2}; end n = size(pts, 1); pts2 = pts - repmat(pt0, [n 1]); angle = lineAngle([zeros(n, 2) pts2]); angle = mod(angle - theta0 + 2*pi, 2*pi); [dummy, I] = sort(angle); # format output if nargout<2 varargout{1} = pts(I, :); elseif nargout==2 varargout{1} = pts(I, :); varargout{2} = I; end endfunction %!shared p1,p2,p3,p4,pts,center %! p1 = [0 0]; %! p2 = [10 0]; %! p3 = [10 10]; %! p4 = [0 10]; %! pts = [p1;p2;p3;p4]; %! center = [5 5]; %!test %! expected = pts([3 4 1 2], :); %! assert (expected, angleSort (pts, center), 1e-6); %!assert (pts, angleSort (pts, center, -pi), 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/reverseEdge.m0000644000000000000000000000013213066736044017676 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/reverseEdge.m0000644000175000017500000000375213066736044020061 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{res} = } reverseEdge (@var{edge}) ## Intervert the source and target vertices of edge ## ## REV = reverseEdge(EDGE); ## Returns the opposite edge of EDGE. ## EDGE has the format [X1 Y1 X2 Y2]. The resulting edge REV has value ## [X2 Y2 X1 Y1]; ## ## @seealso{edges2d, createEdge, reverseLine} ## @end deftypefn function res = reverseEdge(edge) res = [edge(:,3:4) edge(:,1:2)]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/intersectLineEdge.m0000644000000000000000000000013213066736044021033 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/intersectLineEdge.m0000644000175000017500000000770513066736044021220 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} = } intersecLineEdge (@var{line}, @var{edge}) ## Return intersection between a line and an edge. ## ## Returns the intersection point of lines @var{line} and edge @var{edge}. ## @var{line} is a 1x4 array containing parametric representation of the line ## (in the form [x0 y0 dx dy], see @code{createLine} for details). ## @var{edge} is a 1x4 array containing coordinates of first and second point ## (in the form [x1 y1 x2 y2], see @code{createEdge} for details). ## ## In case of colinear line and edge, returns [Inf Inf]. ## If line does not intersect edge, returns [NaN NaN]. ## ## If each input is [N*4] array, the result is a [N*2] array containing ## intersections for each couple of edge and line. ## If one of the input has N rows and the other 1 row, the result is a ## [N*2] array. ## ## @seealso{lines2d, edges2d, intersectEdges, intersectLine} ## @end deftypefn function point = intersectLineEdge(lin, edge) x0 = lin(:,1); y0 = lin(:,2); dx1 = lin(:,3); dy1 = lin(:,4); x1 = edge(:,1); y1 = edge(:,2); x2 = edge(:,3); y2 = edge(:,4); dx2 = x2-x1; dy2 = y2-y1; N1 = length(x0); N2 = length(x1); # indices of parallel lines par = abs(dx1.*dy2-dx2.*dy1)<1e-14; # indices of colinear lines col = abs((x1-x0).*dy1-(y1-y0).*dx1)<1e-14 & par ; xi(col) = Inf; yi(col) = Inf; xi(par & ~col) = NaN; yi(par & ~col) = NaN; i = ~par; # compute intersection points if N1==N2 xi(i) = ((y1(i)-y0(i)).*dx1(i).*dx2(i) + x0(i).*dy1(i).*dx2(i) - x1(i).*dy2(i).*dx1(i)) ./ ... (dx2(i).*dy1(i)-dx1(i).*dy2(i)) ; yi(i) = ((x1(i)-x0(i)).*dy1(i).*dy2(i) + y0(i).*dx1(i).*dy2(i) - y1(i).*dx2(i).*dy1(i)) ./ ... (dx1(i).*dy2(i)-dx2(i).*dy1(i)) ; elseif N1==1 xi(i) = ((y1(i)-y0).*dx1.*dx2(i) + x0.*dy1.*dx2(i) - x1(i).*dy2(i).*dx1) ./ ... (dx2(i).*dy1-dx1.*dy2(i)) ; yi(i) = ((x1(i)-x0).*dy1.*dy2(i) + y0.*dx1.*dy2(i) - y1(i).*dx2(i).*dy1) ./ ... (dx1.*dy2(i)-dx2(i).*dy1) ; elseif N2==1 xi(i) = ((y1-y0(i)).*dx1(i).*dx2 + x0(i).*dy1(i).*dx2 - x1(i).*dy2.*dx1(i)) ./ ... (dx2.*dy1(i)-dx1(i).*dy2) ; yi(i) = ((x1-x0(i)).*dy1(i).*dy2 + y0(i).*dx1(i).*dy2 - y1(i).*dx2.*dy1(i)) ./ ... (dx1(i).*dy2-dx2.*dy1(i)) ; end point = [xi' yi']; out = find(~isPointOnEdge(point, edge)); point(out, :) = repmat([NaN NaN], [length(out) 1]); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createEdge.m0000644000000000000000000000013213066736044017466 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createEdge.m0000644000175000017500000001151413066736044017644 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{edge} = } createEdge (@var{p1}, @var{p2}) ## @deftypefnx {Function File} {@var{edge} = } createEdge (@var{x0}, @var{y0}, @var{dx}, @var{dy}) ## @deftypefnx {Function File} {@var{edge} = } createEdge (@var{param}) ## @deftypefnx {Function File} {@var{edge} = } createEdge (@var{line}, @var{d}) ## Create an edge between two points, or from a line. ## ## The internal format for edge representation is given by coordinates of ## two points : [x1 y1 x2 y2]. ## This function can serve as a line to edge converter. ## ## ## Returns the edge between the two given points @var{p1} and @var{p2}. ## ## Returns the edge going through point (@var{x0}, @var{y0}) and with direction ## vector (@var{dx},@var{dy}). ## ## When @var{param} is an array of 4 values, creates the edge going through the ## point (param(1) param(2)), and with direction vector given by ## (param(3) param(4)). ## ## When @var{line} is given, creates the edge contained in @var{line}, with same ## direction and start point, but with length given by @var{d}. ## ## ## Note: in all cases, parameters can be vertical arrays of the same ## dimension. The result is then an array of edges, of dimensions [N*4]. ## ## @seealso{edges2d, lines2d, drawEdge, clipEdge} ## @end deftypefn function edge = createEdge(varargin) if length(varargin)==1 # Only one input parameter. It can be : # - line angle # - array of four parameters # TODO : add control for arrays of lines. var = varargin{1}; if size(var, 2)==4 # 4 parameters of the line in a single array. #edge = var; edge = zeros(size(var)); edge(:, 1:2) = var(:,1:2); edge(:, 3:4) = edge(:, 1:2)+var(:,3:4); elseif size(var, 2)==1 # 1 parameter : angle of the line, going through origin. edge = [zeros(size(var,1)) zeros(size(var,1)) cos(var) sin(var)]; else error('wrong number of dimension for arg1 : can be 1 or 4'); end elseif length(varargin)==2 # 2 input parameters. They can be : # - 2 points, then 2 arrays of 1*2 double, # - a line, and a distance. v1 = varargin{1}; v2 = varargin{2}; if size(v1, 2)==2 # first input parameter is first point, and second input is the # second point. #edge = [v1(:,1), v1(:,2), v2(:,1), v2(:,2)]; edge = [v1 v2]; else # first input parameter is a line, and second one a distance. angle = atan2(v1(:,4), v1(:,3)); edge = [v1(:,1), v1(:,2), v1(:,1)+v2.*cos(angle), v1(:,2)+v2.*sin(angle)]; end elseif length(varargin)==3 # 3 input parameters : # first one is a point belonging to the line, # second and third ones are direction vector of the line (dx and dy). p = varargin{1}; edge = [p(:,1) p(:,2) p(:,1)+varargin{2} p(:,2)+varargin{3}]; elseif length(varargin)==4 # 4 input parameters : # they are x0, y0 (point belonging to line) and dx, dy (direction # vector of the line). # All parameters should have the same size. edge = [varargin{1} varargin{2} varargin{1}+varargin{3} varargin{2}+varargin{4}]; else error('Wrong number of arguments in ''createLine'' '); end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawRect.m0000644000000000000000000000013213066736044017211 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawRect.m0000644000175000017500000000662113066736044017372 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{r} = } drawRect (@var{x}, @var{y}, @var{w}, @var{h}) ## @deftypefnx {Function File} {@var{r} = } drawRect (@var{x}, @var{y}, @var{w}, @var{h}, @var{theta}) ## @deftypefnx {Function File} {@var{r} = } drawRect (@var{coord}) ## Draw rectangle on the current axis. ## ## r = DRAWRECT(x, y, w, h) draw rectangle with width W and height H, at ## position (X, Y). ## the four corners of rectangle are then : ## (X, Y), (X+W, Y), (X, Y+H), (X+W, Y+H). ## ## r = DRAWRECT(x, y, w, h, theta) also specifies orientation for ## rectangle. Theta is given in degrees. ## ## r = DRAWRECT(coord) is the same as DRAWRECT(X,Y,W,H), but all ## parameters are packed into one array, whose dimensions is 4*1 or 5*1. ## ## ## @seealso{drawBox, drawOrientedBox} ## @end deftypefn function varargout = drawRect(varargin) # default values theta = 0; # get entered values if length(varargin) > 3 x = varargin{1}; y = varargin{2}; w = varargin{3}; h = varargin{4}; if length(varargin)> 4 theta = varargin{5} * pi / 180; end else coord = varargin{1}; x = coord(1); y = coord(2); w = coord(3); h = coord(4); if length(coord) > 4 theta = coord(5) * pi / 180; end end r = zeros(size(x)); for i = 1:length(x) tx = zeros(5, 1); ty = zeros(5, 1); tx(1) = x(i); ty(1) = y(i); tx(2) = x(i) + w(i) * cos(theta(i)); ty(2) = y(i) + w(i) * sin(theta(i)); tx(3) = x(i) + w(i) * cos(theta(i)) - h(i) * sin(theta(i)); ty(3) = y(i) + w(i) * sin(theta(i)) + h(i) * cos(theta(i)); tx(4) = x(i) - h(i) * sin(theta(i)); ty(4) = y(i) + h(i) * cos(theta(i)); tx(5) = x(i); ty(5) = y(i); r(i) = line(tx, ty); end if nargout > 0 varargout{1} = r; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/crackPattern.m0000644000000000000000000000013213066736044020057 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/crackPattern.m0000644000175000017500000001616413066736044020243 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{e} = } crackPattern (@var{box}, @var{points}, @var{alpha}) ## Create a (bounded) crack pattern tessellation ## ## E = crackPattern2(BOX, POINTS, ALPHA) ## create a crack propagation pattern wit following parameters : ## - pattern is bounded by area BOX which is a polygon. ## - each crack originates from points given in POINTS ## - directions of each crack is given by a [NxM] array ALPHA, where M is ## the number of rays emanating from each seed/ ## - a crack stop when it reaches another already created crack. ## - all cracks stop when they reach the border of the frame, given by box ## (a serie of 4 points). ## The result is a collection of edges, in the form [x1 y1 x2 y2]. ## ## E = crackPattern2(BOX, POINTS, ALPHA, SPEED) ## Also specify speed of propagation of each crack. ## ## ## See the result with : ## figure; ## drawEdge(E); ## ## @seealso{drawEdge} ## @end deftypefn function edges = crackPattern(box, points, alpha, varargin) if ~isempty(varargin) speed = varargin{1}; else speed = ones(size(points, 1), 1); end # Compute line equations for each initial crack. # The two 'Inf' at the end correspond to the position of the limit. # If an intersection point is found with another line, but whose position # is after this value, this means that another crack stopped it before it # reach the intersection point. # There is one 'end position' for each side of the crack. lines = [points speed.*cos(alpha) speed.*sin(alpha) Inf*ones(size(points, 1), 2)]; # initialize lines for borders, but assign a very high speed, to be sure # borders will stop all cracks. dx = (box([2 3 4 1],1)-box([1 2 3 4],1))*max(speed)*5; dy = (box([2 3 4 1],2)-box([1 2 3 4],2))*max(speed)*5; # add borders to the lines set lines = [lines ; createLine(box, dx, dy) Inf*ones(4,2)]; edges = zeros(0, 4); while true modif = 0; # try to update each line for i=1:size(points, 1) # compute intersections with all other lines pi = intersectLines(lines(i,:), lines); # compute position of all intersection points on the current line pos = linePosition(pi, lines(i,:)); # consider points to the right (positive position), and sort them indr = find(pos>=0 & pos~=Inf); [posr, indr2] = sort(pos(indr)); # look for the closest intersection to the right for i2=1:length(indr2) # index of intersected line il = indr(indr2(i2)); # position of point relative to intersected line pos2 = linePosition(pi(il, :), lines(il, :)); # depending on the sign of position, tests if the line2 can # stop the current line, or if it was stopped before if pos2>0 if pos20 if pos2 ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{vn} = } normalizeVector (@var{v}) ## Normalize a vector to have norm equal to 1 ## ## Returns the normalization of vector @var{v}, such that ||@var{v}|| = 1. ## @var{v} can be either a row or a column vector. ## ## When @var{v} is a MxN array, normalization is performed for each row of the ## array. ## ## Example: ## ## @example ## vn = normalizeVector([3 4]) ## vn = ## 0.6000 0.8000 ## vectorNorm(vn) ## ans = ## 1 ## @end example ## ## @seealso{vectors2d, vectorNorm} ## @end deftypefn function vn = normalizeVector(v) dim = size (v); if dim(1)==1 || dim(2)==1 vn = v / sqrt (sumsq (v)); else #same as: vn = v./repmat(sqrt(sum(v.*v, 2)), [1 dim(2)]); vn = bsxfun (@rdivide, v, sqrt (sumsq (v, 2))); end endfunction %!assert (1,vectorNorm (normalizeVector ([3 4]))) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/circles2d.m0000644000000000000000000000013213066736044017310 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/circles2d.m0000644000175000017500000000504713066736044017472 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} circles2d () ## Description of functions operating on circles ## ## Circles are represented by their center and their radius: ## C = [xc yc r]; ## One sometimes considers orientation of circle, by adding an extra ## boolean value in 4-th position, with value TRUE for direct (i.e. ## turning Counter-clockwise) circles. ## ## Circle arcs are represented by their center, their radius, the starting ## angle and the angle extent, both in degrees: ## CA = [xc yc r theta0 dtheta]; ## ## Ellipses are represented by their center, their 2 semi-axis length, and ## their angle (in degrees) with Ox direction. ## E = [xc yc A B theta]; ## ## @seealso{ellipses2d, createCircle, createDirectedCircle, enclosingCircle ## isPointInCircle, isPointOnCircle ## intersectLineCircle, intersectCircles, radicalAxis ## circleAsPolygon, circleArcAsCurve ## drawCircle, drawCircleArc} ## @end deftypefn function circles2d(varargin) help('circles2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/cov2ellipse.m0000644000000000000000000000013213066736044017665 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/cov2ellipse.m0000644000175000017500000000614613066736044020050 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{ellipse} = } cov2ellipse (@var{K}) ## @deftypefnx {Function File} {[@var{ra} @var{rb} @var{theta}] = } cov2ellipse (@var{K}) ## @deftypefnx {Function File} {@dots{} = } cov2ellipse (@dots{}, @samp{tol},@var{tol}) ## Calculates ellipse parameters from covariance matrix. ## ## @var{K} must be symmetric positive (semi)definite. The optional argument ## @samp{tol} sets the tolerance for the verification of the ## positive-(semi)definiteness of the matrix @var{K} (see @command{isdefinite}). ## ## If only one output argument is supplied a vector defining a ellipse is returned ## as defined in @command{ellipses2d}. Otherwise the angle @var{theta} is given ## in radians. ## ## Run @code{demo cov2ellipse} to see an example. ## ## @seealso{ellipses2d, cov2ellipse, drawEllipse} ## @end deftypefn function varargout = cov2ellipse (K, varargin); parser = inputParser (); parser.FunctionName = "cov2ellipse"; parser.addParamValue ('Tol', 100*eps*norm (K, "fro"), @(x)x>0); parser.parse(varargin{:}); if isdefinite (K,parser.Results.Tol) == -1 print_usage end [R S W] = svd (K); theta = atan2 (R(2,1), R(1,1)); v = sqrt (diag(S))'; if nargout == 1 varargout{1} = [0 0 v theta*180/pi]; elseif nargout == 3 varargout{1} = v(1); varargout{2} = v(2); varargout{3} = theta; end endfunction %!demo %! K = [2 1; 1 2]; %! L = chol(K,'lower'); %! u = randn(1e3,2)*L'; %! %! elli = cov2ellipse (K) %! %! figure(1) %! plot(u(:,1),u(:,2),'.r'); %! hold on; %! drawEllipse(elli,'linewidth',2); %! hold off %! axis tight geometry-3.0.0/inst/geom2d/PaxHeaders.28738/ellipse2cov.m0000644000000000000000000000013213066736044017665 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/ellipse2cov.m0000644000175000017500000000652713066736044020053 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{K} = } ellipse2cov (@var{elli}) ## @deftypefnx {Function File} {@var{K} = } ellipse2cov (@var{ra}, @var{rb}) ## @deftypefnx {Function File} {@var{K} = } ellipse2cov (@dots{}, @var{theta}) ## Calculates covariance matrix from ellipse. ## ## If only one input is given, @var{elli} must define an ellipse as described in ## @command{ellipses2d}. ## If two inputs are given, @var{ra} and @var{rb} define the half-lenght of the ## axes. ## If a third input is given, @var{theta} must be the angle of rotation of the ## ellipse in radians, and in counter-clockwise direction. ## ## The output @var{K} contains the covariance matrix define by the ellipse. ## ## Run @code{demo ellipse2cov} to see an example. ## ## @seealso{ellipses2d, cov2ellipse, drawEllipse} ## @end deftypefn function K = ellipse2cov (elli, varargin); ra = 1; rb = 1; theta = 0; switch numel (varargin) case 0 ## ellipse format if numel (elli) != 5 print_usage (); end ra = elli(1,3); rb = elli(1,4); theta = elli(1,5)*pi/180; case 1 ## ra,rb if numel (elli) != 1 print_usage (); end ra = elli; rb = varargin{1}; case 2 ## ra,rb, theta if numel (elli) != 1 print_usage (); end ra = elli; rb = varargin{1}; theta = varargin{2}; otherwise print_usage (); end T = createRotation (theta)(1:2,1:2); K = T*diag([ra rb])*T'; endfunction %!demo %! elli = [0 0 1 3 -45]; %! %! # Create 2D normal random variables with covarinace defined by elli. %! K = ellipse2cov (elli) %! L = chol(K,'lower'); %! u = randn(1e3,2)*L'; %! %! Kn = cov (u) %! %! figure(1) %! plot(u(:,1),u(:,2),'.r'); %! hold on; %! drawEllipse(elli,'linewidth',2); %! hold off %! axis tight geometry-3.0.0/inst/geom2d/PaxHeaders.28738/angle2Points.m0000644000000000000000000000013213066736044020003 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/angle2Points.m0000644000175000017500000000677713066736044020200 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{alpha} =} angle2Points (@var{p1}, @var{p2}) ## Compute horizontal angle between 2 points ## ## @var{p1} and @var{p2} are either [1x2] arrays, or [Nx2] arrays, in this case ## @var{alpha} is a [Nx1] array. The angle computed is the horizontal angle of ## the line (@var{p1},@var{p2}). ## ## Result is always given in radians, between 0 and 2*pi. ## ## @seealso{points2d, angles2d, angle3points, normalizeAngle, vectorAngle} ## @end deftypefn function theta = angle2Points(varargin) # process input arguments if length(varargin)==2 p1 = varargin{1}; p2 = varargin{2}; elseif length(varargin)==1 var = varargin{1}; p1 = var(1,:); p2 = var(2,:); end # ensure data have correct size n1 = size(p1, 1); n2 = size(p2, 1); if n1~=n2 && min(n1, n2)>1 error('angle2Points: wrong size for inputs'); end # angle of line (P2 P1), between 0 and 2*pi. dp = bsxfun(@minus, p2, p1); theta = mod(atan2(dp(:,2), dp(:,1)) + 2*pi, 2*pi); endfunction %!test %! # all points inside window, possibly touching edges %! p1 = [0 0]; %! p2 = [10 0]; %! angle_ = angle2Points (p1, p2); %! assert (angle_,0,1e-6); %! angle_ = angle2Points (p2, p1); %! assert (angle_,pi,1e-6); %!test %! # all points inside window, possibly touching edges %! p1 = [0 0]; %! p2 = [0 10]; %! angle_ = angle2Points (p1, p2); %! assert (pi/2, angle_,1e-6); %! angle_ = angle2Points (p2, p1); %! assert (3*pi/2, angle_,1e-6); %!test %! # all points inside window, possibly touching edges %! p1 = [0 0;0 0;0 0;0 0]; %! p2 = [10 0;10 10;0 10;-10 10]; %! angle_ = angle2Points (p1, p2); %! assert (size (p1, 1), size (angle_, 1)); %! res = [0;pi/4;pi/2;3*pi/4]; %! assert (res, angle_, 1e-6); %!test %! # all points inside window, possibly touching edges %! p1 = [0 0]; %! p2 = [10 0;10 10;0 10;-10 10]; %! angle_ = angle2Points (p1, p2); %! assert(size (p2, 1), size (angle_, 1)); %! res = [0;pi/4;pi/2;3*pi/4]; %! assert(res, angle_,1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/beltProblem.m0000644000000000000000000000013213066736044017705 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/beltProblem.m0000644000175000017500000001133113066736044020060 0ustar00olafolaf00000000000000## Copyright (C) 2012-2017 Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{tangent},@var{inner}] = } beltProblem (@var{c}, @var{r}) ## Finds the four lines tangent to two circles with given centers and radii. ## ## The function solves the belt problem in 2D for circles with center @var{c} and ## radii @var{r}. ## ## @strong{INPUT} ## @table @var ## @item c ## 2-by-2 matrix containig coordinates of the centers of the circles; one row per circle. ## @item r ## 2-by-1 vector with the radii of the circles. ##@end table ## ## @strong{OUPUT} ## @table @var ## @item tangent ## 4-by-4 matrix with the points of tangency. Each row describes a segment(edge). ## @item inner ## 4-by-2 vector with the point of intersection of the inner tangents (crossed belts) ## with the segment that joins the centers of the two circles. If ## the i-th edge is not an inner tangent then @code{inner(i,:)=[NaN,NaN]}. ## @end table ## ## Example: ## ## @example ## c = [0 0;1 3]; ## r = [1 0.5]; ## [T inner] = beltProblem(c,r) ## @result{} T = ## -0.68516 0.72839 1.34258 2.63581 ## 0.98516 0.17161 0.50742 2.91419 ## 0.98675 -0.16225 1.49338 2.91888 ## -0.88675 0.46225 0.55663 3.23112 ## ## @result{} inner = ## 0.66667 2.00000 ## 0.66667 2.00000 ## NaN NaN ## NaN NaN ## ## @end example ## ## @seealso{edges2d} ## @end deftypefn function [edgeTan inner] = beltProblem(c,r) x0 = [c(1,1) c(1,2) c(2,1) c(2,2)]; r0 = r([1 1 2 2]); middleEdge = createEdge(c(1,:),c(2,:)); ind0 = [1 0 1 0; 0 1 1 0; 1 1 1 0; -1 0 1 0; 0 -1 1 0; -1 -1 1 0;... 1 0 0 1; 0 1 0 1; 1 1 0 1; -1 0 0 1; 0 -1 0 1; -1 -1 0 1;... 1 0 1 1; 0 1 1 1; 1 1 1 1; -1 0 1 1; 0 -1 1 1; -1 -1 1 1;... 1 0 -1 0; 0 1 -1 0; 1 1 -1 0; -1 0 -1 0; 0 -1 -1 0; -1 -1 -1 0;... 1 0 0 -1; 0 1 0 -1; 1 1 0 -1; -1 0 0 -1; 0 -1 0 -1; -1 -1 0 -1;... 1 0 -1 -1; 0 1 -1 -1; 1 1 -1 -1; -1 0 -1 -1; 0 -1 -1 -1; -1 -1 -1 -1]; nInit = size(ind0,1); ir = randperm(nInit); edgeTan = zeros(4,4); inner = zeros(4,2); nSol = 0; i=1; ## Solve for 2 different lines while nSol<4 && i 1e-6); end if all(notequal) nSol = nSol+1; edgeTan(nSol,:) = createEdge(sol(1:2),sol(3:4)); # Find innerTangent inner(nSol,:) = intersectEdges(middleEdge,edgeTan(nSol,:)); end i = i+1; end endfunction function res = belt(x,c,r) res = zeros(4,1); res(1,1) = (x(3:4) - c(2,1:2))*(x(3:4) - x(1:2))'; res(2,1) = (x(1:2) - c(1,1:2))*(x(3:4) - x(1:2))'; res(3,1) = sumsq(x(1:2) - c(1,1:2)) - r(1)^2; res(4,1) = sumsq(x(3:4) - c(2,1:2)) - r(2)^2; end %!demo %! c = [0 0;1 3]; %! r = [1 0.5]; %! [T inner] = beltProblem(c,r) %! %! figure(1) %! clf %! h = drawEdge(T); %! set(h(find(~isnan(inner(:,1)))),'color','r'); %! set(h,'linewidth',2); %! hold on %! drawCircle([c(1,:) r(1); c(2,:) r(2)],'linewidth',2); %! axis tight %! axis equal %! %! # ------------------------------------------------------------------- %! # The circles with the tangents edges are plotted. The solution with %! # crossed belts (inner tangets) is shown in red. geometry-3.0.0/inst/geom2d/PaxHeaders.28738/circleAsPolygon.m0000644000000000000000000000013213066736044020533 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/circleAsPolygon.m0000644000175000017500000000507313066736044020714 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{P} = } circleAsPolygon (@var{circle}, @var{N}) ## Convert a circle into a series of points ## ## P = circleAsPolygon(CIRCLE, N); ## convert circle given as [x0 y0 r], where x0 and y0 are coordinate of ## center, and r is the radius, into an array of [(N+1)x2] double, ## containing x and y values of points. ## The polygon is closed ## ## P = circleAsPolygon(CIRCLE); ## uses a default value of N=64 points ## ## Example ## circle = circleAsPolygon([10 0 5], 16); ## figure; ## drawPolygon(circle); ## ## @seealso{circles2d, polygons2d, createCircle} ## @end deftypefn function varargout = circleAsPolygon(circle, varargin) # determines number of points N = 64; if ~isempty(varargin) N = varargin{1}; end # create circle t = linspace(0, 2*pi, N+1)'; x = circle(1) + circle(3)*cos(t); y = circle(2) + circle(3)*sin(t); if nargout==1 varargout{1}=[x y]; elseif nargout==2 varargout{1}=x; varargout{2}=y; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawCircle.m0000644000000000000000000000013213066736044017515 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawCircle.m0000644000175000017500000001020013066736044017662 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawCircle (@var{x0}, @var{y0}, @var{r}) ## @deftypefnx {Function File} {@var{h} = } drawCircle (@var{circle}) ## @deftypefnx {Function File} {@var{h} = } drawCircle (@var{center}, @var{radius}) ## @deftypefnx {Function File} {@var{h} = } drawCircle (@dots{}, @var{nstep}) ## @deftypefnx {Function File} {@var{h} = } drawCircle (@dots{}, @var{name}, @var{value}) ## Draw a circle on the current axis ## ## drawCircle(X0, Y0, R); ## Draw the circle with center (X0,Y0) and the radius R. If X0, Y0 and R ## are column vectors of the same length, draw each circle successively. ## ## drawCircle(CIRCLE); ## Concatenate all parameters in a Nx3 array, where N is the number of ## circles to draw. ## ## drawCircle(CENTER, RADIUS); ## Specify CENTER as Nx2 array, and radius as a Nx1 array. ## ## drawCircle(..., NSTEP); ## Specify the number of edges that will be used to draw the circle. ## Default value is 72, creating an approximation of one point for each 5 ## degrees. ## ## drawCircle(..., NAME, VALUE); ## Specifies plotting options as pair of parameters name/value. See plot ## documentation for details. ## ## ## H = drawCircle(...); ## return handles to each created curve. ## ## @seealso{circles2d, drawCircleArc, drawEllipse} ## @end deftypefn function varargout = drawCircle(varargin) # process input parameters var = varargin{1}; if size(var, 2) == 1 x0 = varargin{1}; y0 = varargin{2}; r = varargin{3}; varargin(1:3) = []; elseif size(var, 2) == 2 x0 = var(:,1); y0 = var(:,2); r = varargin{2}; varargin(1:2) = []; elseif size(var, 2) == 3 x0 = var(:,1); y0 = var(:,2); r = var(:,3); varargin(1) = []; else error('bad format for input in drawCircle'); end # ensure each parameter is column vector x0 = x0(:); y0 = y0(:); r = r(:); # default number of discretization steps N = 72; # check if discretization step is specified if ~isempty(varargin) var = varargin{1}; if length(var)==1 && isnumeric(var) N = round(var); varargin(1) = []; end end # parametrization variable for circle (use N+1 as first point counts twice) t = linspace(0, 2*pi, N+1); cot = cos(t); sit = sin(t); # empty array for graphic handles h = zeros(size(x0)); # compute discretization of each circle for i = 1:length(x0) xt = x0(i) + r(i) * cot; yt = y0(i) + r(i) * sit; h(i) = plot(xt, yt, varargin{:}); end if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/edges2d.m0000644000000000000000000000013213066736044016753 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/edges2d.m0000644000175000017500000000415213066736044017131 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} edges2d () ## Description of functions operating on planar edges # # An edge is represented by the corodinate of its end points: # EDGE = [X1 Y1 X2 Y2]; # # A set of edges is represented by a N*4 array, each row representing an # edge. # # # @seealso{lines2d, rays2d, points2d # createEdge, edgeAngle, edgeLength, edgeToLine, midPoint # intersectEdges, intersectLineEdge, isPointOnEdge # clipEdge, transformEdge # drawEdge, drawCenteredEdge} ## @end deftypefn function edges2d(varargin) help('edges2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/lines2d.m0000644000000000000000000000013213066736044016776 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/lines2d.m0000644000175000017500000000512613066736044017156 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} lines2d () ## Description of functions operating on planar lines. # # The term 'line' refers to a planar straight line, which is an unbounded # curve. Line segments defined between 2 points, which are bounded, are # called 'edge', and are presented in file 'edges2d'. # # A straight line is defined by a point (its origin), and a vector (its # direction). The different parameters are bundled into a row vector: # LINE = [x0 y0 dx dy]; # # A line contains all points (x,y) such that: # x = x0 + t*dx # y = y0 + t*dy; # for all t between -infinity and +infinity. # # @seealso{points2d, vectors2d, edges2d, rays2d # createLine, cartesianLine, medianLine, edgeToLine # orthogonalLine, parallelLine, bisector, radicalAxis # lineAngle, linePosition, projPointOnLine # isPointOnLine, distancePointLine, isLeftOriented # intersectLines, intersectLineEdge, clipLine # invertLine, transformLine, drawLine # lineFit} ## @end deftypefn function lines2d(varargin) help('lines2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createDirectedCircle.m0000644000000000000000000000013213066736044021467 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createDirectedCircle.m0000644000175000017500000000622713066736044021652 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{circle} = } createDirectedCircle (@var{p1}, @var{p2}, @var{p3}) ## @deftypefnx {Function File} {@var{circle} = } createDirectedCircle (@var{p1}, @var{p2}) ## Create a circle from 2 or 3 points. ## ## Creates the circle passing through the 3 given points. ## C is a 1x4 array of the form: [XC YX R INV]. ## ## When two points are given, creates the circle whith center @var{p1} and passing ## throuh the point @var{p2}. ## ## Works also when input are point arrays the same size, in this case the ## result has as many lines as the point arrays. ## ## Example ## ## ## @seealso{circles2d, createCircle} ## @end deftypefn function circle = createDirectedCircle(varargin) if nargin == 2 # inputs are the center and a point on the circle p1 = varargin{1}; p2 = varargin{2}; x0 = (p1(:,1) + p2(:,1))/2; y0 = (p1(:,2) + p2(:,2))/2; r = hypot((p2(:,1)-p1(:,1)), (p2(:,2)-p1(:,2)))/2; # circle is direct by default d = 0; elseif nargin == 3 # inputs are three points on the circle p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; # compute circle center line1 = medianLine(p1, p2); line2 = medianLine(p1, p3); center = intersectLines(line1, line2); x0 = center(:, 1); y0 = center(:, 2); # circle radius r = hypot((p1(:,1)-x0), (p1(:,2)-y0)); # compute circle orientation angle = angle3Points(p1, center, p2) + angle3Points(p2, center, p3); d = angle>2*pi; end circle = [x0 y0 r d]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createLine.m0000644000000000000000000000013213066736044017511 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createLine.m0000644000175000017500000001400413066736044017664 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line} =} createLine(varargin) ## Create a straight line from 2 points, or from other inputs ## ## Line is represented in a parametric form : [x0 y0 dx dy] ## x = x0 + t*dx ## y = y0 + t*dy; ## ## ## L = createLine(p1, p2); ## Returns the line going through the two given points. ## ## L = createLine(x0, y0, dx, dy); ## Returns the line going through point (x0, y0) and with direction ## vector(dx, dy). ## ## L = createLine(LINE); ## where LINE is an array of 4 values, creates the line going through the ## point (LINE(1) LINE(2)), and with direction given by vector (LINE(3) ## LINE(4)). ## ## L = createLine(THETA); ## Create a polar line originated at (0,0) and with angle THETA. ## ## L = createLine(RHO, THETA); ## Create a polar line with normal theta, and with min distance to origin ## equal to rho. rho can be negative, in this case, the line is the same ## as with CREATELINE(-rho, theta+pi), but the orientation is different. ## ## ## Note: in all cases, parameters can be vertical arrays of the same ## dimension. The result is then an array of lines, of dimensions [N*4]. ## ## NOTE : A line can also be represented with a 1*5 array : ## [x0 y0 dx dy t]. ## whith 't' being one of the following : ## - t=0 : line is a singleton (x0,y0) ## - t=1 : line is an edge segment, between points (x0,y0) and (x0+dx, ## y0+dy). ## - t=Inf : line is a Ray, originated from (x0,y0) and going to infinity ## in the direction(dx,dy). ## - t=-Inf : line is a Ray, originated from (x0,y0) and going to infinity ## in the direction(-dx,-dy). ## - t=NaN : line is a real straight line, and contains all points ## verifying the above equation. ## This seems us a convenient way to represent uniformly all kind of lines ## (including edges, rays, and even point). ## ## NOTE2 : Any line object can be represented using a 1x6 array : ## [x0 y0 dx dy t0 t1] ## the first 4 parameters define the supporting line, ## t0 represent the position of the first point on the line, ## and t1 the position of the last point. ## * for edges : t0 = 0, and t1=1 ## * for straight lines : t0 = -inf, t1=inf ## * for rays : t0=0, t1=inf (or t0=-inf,t1=0 for inverted ray). ## I propose to call these objects 'lineArc' ## ## @seealso{lines2d, createEdge, createRay} ## @end deftypefn function line = createLine(varargin) if length(varargin)==1 # Only one input parameter. It can be : # - line angle # - array of four parameters # TODO : add control for arrays of lines. var = varargin{1}; if size(var, 2)==4 # 4 parameters of the line in a single array. line = var; elseif size(var, 2)==1 # 1 parameter : angle of the line, going through origin. line = [zeros(size(var)) zeros(size(var)) cos(var) sin(var)]; else error('wrong number of dimension for arg1 : can be 1 or 4'); end elseif length(varargin)==2 # 2 input parameters. They can be : # - line angle and signed distance to origin. # - 2 points, then 2 arrays of 1*2 double. v1 = varargin{1}; v2 = varargin{2}; if size(v1, 2)==1 # first param is angle of line, and second param is signed distance # to origin. line = [v1.*cos(v2) v1.*sin(v2) -sin(v2) cos(v2)]; else # first input parameter is first point, and second input is the # second point. line = [v1(:,1), v1(:,2), v2(:,1)-v1(:,1), v2(:,2)-v1(:,2)]; end elseif length(varargin)==3 # 3 input parameters : # first one is a point belonging to the line, # second and third ones are direction vector of the line (dx and dy). p = varargin{1}; line = [p(:,1) p(:,2) varargin{2} varargin{3}]; elseif length(varargin)==4 # 4 input parameters : # they are x0, y0 (point belongng to line) and dx, dy (direction vector # of the line). # All parameters should have the same size. line = [varargin{1} varargin{2} varargin{3} varargin{4}]; else error('Wrong number of arguments in ''createLine'' '); end endfunction %!test %! p1 = [1 1]; %! p2 = [2 3]; %! lin = createLine(p1, p2); %! assert (p1, lin(1,1:2), 1e-6); %! assert (p2-p1, lin(1,3:4), 1e-6); %!test %! p1 = [1 1;1 1]; %! p2 = [2 3;2 4]; %! lin = createLine(p1, p2); %! assert (2, size(lin, 1)); %! assert (p1, lin(:,1:2), 1e-6); %! assert (p2-p1, lin(:,3:4), 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createBasisTransform.m0000644000000000000000000000013213066736044021557 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createBasisTransform.m0000644000175000017500000001001113066736044021724 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } createBasisTransfrom (@var{@var{target}}) ## @deftypefnx {Function File} {@var{T} = } createBasisTransfrom (@var{@var{source}}, @var{@var{target}}) ## Compute matrix for transforming a basis into another basis ## ## With only one input arguemnt, assumes the @var{source} is the standard (Oij) basis, with origin at (0,0), ## first direction vector equal to (1,0) and second direction vector ## equal to (0,1). Otherwise @var{@var{source}} specifies the @var{source} basis. ## ## Both @var{source} and @var{target} represent basis, in the following form: ## [x0 y0 ex1 ey1 ex2 ey2] ## [y0 y0] is the origin of the basis, [ex1 ey1] is the first direction ## vector, and [ex2 ey2] is the second direction vector. ## ## The result @var{T} is a 3-by-3 matrix such that a point expressed with ## coordinates of the first basis will be represented by new coordinates ## @code{P2 = transformPoint(P1, @var{T})} in the @var{target} basis. ## ## Example ## @example ## # standard basis transform ## src = [0 0 1 0 0 1]; ## # @var{target} transform, just a rotation by atan(2/3) followed by a scaling ## tgt = [0 0 .75 .5 -.5 .75]; ## # compute transform ## trans = createBasisTransform(src, tgt); ## # transform the point (.25,1.25) into the point (1,1) ## p1 = [.25 1.25]; ## p2 = transformPoint(p1, trans) ## ans = ## 1 1 ## @end example ## ## @seealso{transforms2d} ## @end deftypefn function transfo = createBasisTransform(source, target) # init basis transform to identity t1 = eye(3); t2 = eye(3); if nargin==2 # from source to reference basis t1(1:2, 1) = source(3:4); t1(1:2, 2) = source(5:6); t1(1:2, 3) = source(1:2); else # if only one input, use first input as target basis, and leave the # first matrix to identity target = source; end # from reference to target basis t2(1:2, 1) = target(3:4); t2(1:2, 2) = target(5:6); t2(1:2, 3) = target(1:2); # compute transfo # same as: transfo = inv(t2)*t1; transfo = t2\t1; endfunction %!demo %! # standard basis transform %! src = [0 0 1 0 0 1]; %! # target transform, just a rotation by atan(2/3) followed by a scaling %! tgt = [0 0 .75 .5 -.5 .75]; %! # compute transform %! trans = createBasisTransform(src, tgt); %! # transform the point (.25,1.25) into the point (1,1) %! p1 = [.25 1.25]; %! p2 = transformPoint(p1, trans) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/intersectEdges.m0000644000000000000000000000013213066736044020406 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/intersectEdges.m0000644000175000017500000001357713066736044020577 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} = } intersectEdges (@var{edge1}, @var{edge2}) ## Return all intersections between two set of edges ## ## returns the intersection point of edges E1 and E2. ## E1 and E2 are 1-by-4 arrays, containing parametric representation of ## each edge (in the form [x1 y1 x2 y2], see 'createEdge' for details). ## ## In case of colinear edges, the result P contains [Inf Inf]. ## In case of parallel but not colinear edges, the result P contains ## [NaN NaN]. ## ## If each input is N-by-4 array, the result is a N-by-2 array containing ## the intersection of each couple of edges. ## If one of the input has N rows and the other 1 row, the result is a ## N-by-2 array. ## ## P = intersectEdges(E1, E2, TOL); ## Specifies a tolerance parameter to determine parallel and colinear ## edges, and if a point belongs to an edge or not. The latter test is ## performed on the relative position of the intersection point over the ## edge, that should lie within [-TOL; 1+TOL]. ## ## @seealso{edges2d, intersectLines} ## @end deftypefn function point = intersectEdges(edge1, edge2, tol = eps) ## Initialisations # ensure input arrays are same size N1 = size (edge1, 1); N2 = size (edge2, 1); # ensure input have same size if N1 ~= N2 if N1 == 1 edge1 = repmat (edge1, [N2 1]); N1 = N2; elseif N2 == 1 edge2 = repmat (edge2, [N1 1]); end end # initialize result array x0 = zeros(N1, 1); y0 = zeros(N1, 1); ## Detect parallel and colinear cases # indices of parallel edges #par = abs(dx1.*dy2 - dx1.*dy2) return [NaN NaN] x0(par & ~col) = NaN; y0(par & ~col) = NaN; ## Process colinear edges # colinear edges may have 0, 1 or infinite intersection # Discrimnation based on position of edge2 vertices on edge1 if sum(col)>0 # array for storing results of colinear edges resCol = Inf*ones(size(col)); # compute position of edge2 vertices wrt edge1 t1 = edgePosition(edge2(col, 1:2), edge1(col, :)); t2 = edgePosition(edge2(col, 3:4), edge1(col, :)); # control location of vertices: we want t1t2 tmp = t1; t1 = t2; t2 = tmp; end # edge totally before first vertex or totally after last vertex resCol(col(t2 < -tol)) = NaN; resCol(col(t1 > 1+tol)) = NaN; # set up result into point coordinate x0(col) = resCol; y0(col) = resCol; # touches on first point of first edge touch = col(abs(t2) < tol); x0(touch) = edge1(touch, 1); y0(touch) = edge1(touch, 2); # touches on second point of first edge touch = col(abs(t1-1) < tol); x0(touch) = edge1(touch, 3); y0(touch) = edge1(touch, 4); end ## Process non parallel cases # process intersecting edges whose interecting lines intersect i = find(~par); # use a test to avoid process empty arrays if sum(i)>0 # extract base parameters of supporting lines for non-parallel edges x1 = edge1(i,1); y1 = edge1(i,2); dx1 = edge1(i,3)-x1; dy1 = edge1(i,4)-y1; x2 = edge2(i,1); y2 = edge2(i,2); dx2 = edge2(i,3)-x2; dy2 = edge2(i,4)-y2; # compute intersection points of supporting lines delta = (dx2.*dy1-dx1.*dy2); x0(i) = ((y2-y1).*dx1.*dx2 + x1.*dy1.*dx2 - x2.*dy2.*dx1) ./ delta; y0(i) = ((x2-x1).*dy1.*dy2 + y1.*dx1.*dy2 - y2.*dx2.*dy1) ./ -delta; # compute position of intersection points on each edge # t1 is position on edge1, t2 is position on edge2 t1 = ((y0(i)-y1).*dy1 + (x0(i)-x1).*dx1) ./ (dx1.*dx1+dy1.*dy1); t2 = ((y0(i)-y2).*dy2 + (x0(i)-x2).*dx2) ./ (dx2.*dx2+dy2.*dy2); # check position of points on edges. # it should be comprised between 0 and 1 for both t1 and t2. # if not, the edges do not intersect out = t1<-tol | t1>1+tol | t2<-tol | t2>1+tol; x0(i(out)) = NaN; y0(i(out)) = NaN; end ## format output arguments point = [x0 y0]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/intersectLineCircle.m0000644000000000000000000000013213066736044021370 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/intersectLineCircle.m0000644000175000017500000000644113066736044021551 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{points} = } intersectLineCircle (@var{line}, @var{circle}) ## Intersection point(s) of a line and a circle ## ## INTERS = intersectLineCircle(LINE, CIRCLE); ## Returns a 2-by-2 array, containing on each row the coordinates of an ## intersection point. If the line and circle do not intersect, the result ## is filled with NaN. ## ## Example ## # base point ## center = [10 0]; ## # create vertical line ## l1 = [center 0 1]; ## # circle ## c1 = [center 5]; ## pts = intersectLineCircle(l1, c1) ## pts = ## 10 -5 ## 10 5 ## # draw the result ## figure; clf; hold on; ## axis([0 20 -10 10]); ## drawLine(l1); ## drawCircle(c1); ## drawPoint(pts, 'rx'); ## axis equal; ## ## @seealso{lines2d, circles2d, intersectLines, intersectCircles} ## @end deftypefn function points = intersectLineCircle(line, circle) # local precision eps = 1e-14; # center parameters center = circle(:, 1:2); radius = circle(:, 3); # line parameters dp = line(:, 1:2) - center; vl = line(:, 3:4); # coefficient of second order equation a = sum(line(:, 3:4).^2, 2); b = 2*sum(dp .* vl, 2); c = sum(dp.^2, 2) - radius.^2; # discriminant delta = b .^ 2 - 4 * a .* c; if delta > eps # find two roots of second order equation u1 = (-b - sqrt(delta)) / 2 ./ a; u2 = (-b + sqrt(delta)) / 2 ./ a; # convert into 2D coordinate points = [line(1:2) + u1 * line(3:4) ; line(1:2) + u2 * line(3:4)]; elseif abs(delta) < eps # find unique root, and convert to 2D coord. u = -b / 2 ./ a; points = line(1:2) + u*line(3:4); else # fill with NaN points = NaN * ones(2, 2); return; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/ellipseAsPolygon.m0000644000000000000000000000013213066736044020727 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/ellipseAsPolygon.m0000644000175000017500000000605613066736044021112 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{p} = } ellipseAsPolygon (@var{ell}, @var{n}) ## Convert an ellipse into a series of points ## ## P = ellipseAsPolygon(ELL, N); ## converts ELL given as [x0 y0 a b] or [x0 y0 a b theta] into a polygon ## with N edges. The result P is (N+1)-by-2 array containing coordinates ## of the N+1 vertices of the polygon. ## The resulting polygon is closed, i.e. the last point is the same as the ## first one. ## ## P = ellipseAsPolygon(ELL); ## Use a default number of edges equal to 72. This result in one piont for ## each 5 degrees. ## ## [X Y] = ellipseAsPolygon(...); ## Return the coordinates o fvertices in two separate arrays. ## ## @seealso{ellipses2d, circleAsPolygon, rectAsPolygon, drawEllipse} ## @end deftypefn function varargout = ellipseAsPolygon(ellipse, N) # default value for N if nargin < 2 N = 72; end # angle of ellipse theta = 0; if size(ellipse, 2) > 4 theta = ellipse(:,5); end # get ellipse parameters xc = ellipse(:,1); yc = ellipse(:,2); a = ellipse(:,3); b = ellipse(:,4); # create time basis t = linspace(0, 2*pi, N+1)'; # pre-compute trig functions (angles is in degrees) cot = cosd(theta); sit = sind(theta); # position of points x = xc + a * cos(t) * cot - b * sin(t) * sit; y = yc + a * cos(t) * sit + b * sin(t) * cot; # format output depending on number of a param. if nargout == 1 varargout = {[x y]}; elseif nargout == 2 varargout = {x, y}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isCounterClockwise.m0000644000000000000000000000013213066736044021255 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isCounterClockwise.m0000644000175000017500000001257613066736044021444 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{ccw} = } isCounterClockwise (@var{p1}, @var{p2}, @var{p3}) ## @deftypefnx {Function File} {@var{ccw} = } isCounterClockwise (@var{p1}, @var{p2}, @var{p3},@var{tol}) ## Compute relative orientation of 3 points ## ## Computes the orientation of the 3 points. The returns is: ## +1 if the path @var{p1}-> @var{p2}-> @var{p3} turns Counter-Clockwise (i.e., the point @var{p3} ## is located "on the left" of the line @var{p1}- @var{p2}) ## -1 if the path turns Clockwise (i.e., the point @var{p3} lies "on the right" ## of the line @var{p1}- @var{p2}) ## 0 if the point @var{p3} is located on the line segment [ @var{p1} @var{p2}]. ## ## This function can be used in more complicated algorithms: detection of ## line segment intersections, convex hulls, point in triangle... ## ## @var{ccw} = isCounterClockwise( @var{p1}, @var{p2}, @var{p3}, EPS); ## Specifies the threshold used for detecting colinearity of the 3 points. ## Default value is 1e-12 (absolute). ## ## Example ## ## @example ## isCounterClockwise([0 0], [10 0], [10 10]) ## ans = ## 1 ## isCounterClockwise([0 0], [0 10], [10 10]) ## ans = ## -1 ## isCounterClockwise([0 0], [10 0], [5 0]) ## ans = ## 0 ## @end example ## ## @seealso{points2d, isPointOnLine, isPointInTriangle} ## @end deftypefn function res = isCounterClockwise(p1, p2, p3, varargin) # get threshold value eps = 1e-12; if ~isempty(varargin) eps = varargin{1}; end # ensure all data have same size np = max([size(p1, 1) size(p2, 1) size(p3,1)]); if np > 1 if size(p1,1) == 1 p1 = repmat(p1, np, 1); end if size(p2,1) == 1 p2 = repmat(p2, np, 1); end if size(p3,1) == 1 p3 = repmat(p3, np, 1); end end # init with 0 res = zeros(np, 1); # extract vector coordinates x0 = p1(:, 1); y0 = p1(:, 2); dx1 = p2(:, 1) - x0; dy1 = p2(:, 2) - y0; dx2 = p3(:, 1) - x0; dy2 = p3(:, 2) - y0; # check non colinear cases res(dx1 .* dy2 > dy1 .* dx2) = 1; res(dx1 .* dy2 < dy1 .* dx2) = -1; # case of colinear points ind = abs(dx1 .* dy2 - dy1 .* dx2) < eps; res(ind( (dx1(ind) .* dx2(ind) < 0) | (dy1(ind) .* dy2(ind) < 0) )) = -1; res(ind( hypot(dx1(ind), dy1(ind)) < hypot(dx2(ind), dy2(ind)) )) = 1; endfunction %!shared p0,pu,pd,pl,pr %! p0 = [2, 3]; # center point %! pu = [2, 4]; # up point %! pd = [2, 2]; # down point %! pl = [1, 3]; # left point %! pr = [3, 3]; # right point %!assert (+1, isCounterClockwise(pl, p0, pu)); %!assert (+1, isCounterClockwise(pd, p0, pl)); %!assert (+1, isCounterClockwise(pr, p0, pd)); %!assert (+1, isCounterClockwise(pu, p0, pr)); # turn 90° right => return -1 %!assert (-1, isCounterClockwise(pl, p0, pd)); %!assert (-1, isCounterClockwise(pd, p0, pr)); %!assert (-1, isCounterClockwise(pr, p0, pu)); %!assert (-1, isCounterClockwise(pu, p0, pl)); %!test # turn 90° left => return +1 %! pts1 = [pl;pd;pr;pu;pl;pd;pr;pu]; %! pts2 = [p0;p0;p0;p0;p0;p0;p0;p0]; %! pts3 = [pu;pl;pd;pr;pd;pr;pu;pl]; %! expected = [1;1;1;1;-1;-1;-1;-1]; %! result = isCounterClockwise(pts1, pts2, pts3); %! assert (result, expected, 1e-6); # aligned with p0-p1-p2 => return +1 %!assert (+1, isCounterClockwise(pl, p0, pr)); %!assert (+1, isCounterClockwise(pu, p0, pd)); %!assert (+1, isCounterClockwise(pr, p0, pl)); %!assert (+1, isCounterClockwise(pd, p0, pu)); # aligned ]ith p0-p2-p1 => return 0 %!assert (0, isCounterClockwise(pl, pr, p0)); %!assert (0, isCounterClockwise(pu, pd, p0)); %!assert (0, isCounterClockwise(pr, pl, p0)); %!assert (0, isCounterClockwise(pd, pu, p0)); # aligned with p1-p0-p2 => return -1 %!assert (-1, isCounterClockwise(p0, pl, pr)); %!assert (-1, isCounterClockwise(p0, pu, pd)); %!assert (-1, isCounterClockwise(p0, pr, pl)); %!assert (-1, isCounterClockwise(p0, pr, pl)); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/midPoint.m0000644000000000000000000000013213066736044017221 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/midPoint.m0000644000175000017500000001104613066736044017377 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{mid} = } midPoint (@var{p1}, @var{p2}) ## @deftypefnx {Function File} {@var{mid} = } midPoint (@var{edge}) ## @deftypefnx {Function File} {[@var{midx}, @var{midy}] = } midPoint (@var{edge}) ## Middle point of two points or of an edge ## ## Computes the middle point of the two points @var{p1} and @var{p2}. ## ## If an edge is given, computes the middle point of the edge given by @var{edge}. ## @var{edge} has the format: [X1 Y1 X2 Y2], and @var{mid} has the format [XMID YMID], ## with XMID = (X1+X2)/2, and YMID = (Y1+Y2)/2. ## ## If two output arguments are given, it returns the result as two separate variables or arrays. ## ## Works also when @var{edge} is a N-by-4 array, in this case the result is a ## N-by-2 array containing the midpoint of each edge. ## ## Example ## ## @example ## p1 = [10 20]; ## p2 = [30 40]; ## midPoint([p1 p2]) ## ans = ## 20 30 ## @end example ## ## @seealso{edges2d, points2d} ## @end deftypefn function varargout = midPoint(varargin) if nargin == 1 # input is an edge edge = varargin{1}; mid = [mean(edge(:, [1 3]), 2) mean(edge(:, [2 4]), 2)]; elseif nargin == 2 # input are two points p1 = varargin{1}; p2 = varargin{2}; # assert inputs are equal n1 = size(p1, 1); n2 = size(p2, 1); if n1 != n2 && min(n1, n2)>1 error('geom2d:midPoint', ... 'Inputs must have same size, or one must have length 1'); end # compute middle point mid = bsxfun(@plus, p1, p2) / 2; end # process output arguments if nargout<=1 varargout{1} = mid; else varargout = {mid(:,1), mid(:,2)}; end endfunction %!test %! p1 = [10 20]; %! p2 = [30 40]; %! exp = [20 30]; %! mid = midPoint(p1, p2); %! assert (mid, exp); %!test %! p1 = [ ... %! 10 20 ; ... %! 30 40 ; ... %! 50 60 ; ... %! ]; %! p2 = [ ... %! 30 40; ... %! 50 60; ... %! 70 80]; %! exp = [... %! 20 30; ... %! 40 50; ... %! 60 70]; %! mid = midPoint(p1, p2); %! assert (mid, exp); %!test %! p1 = [30 40]; %! p2 = [ ... %! 30 40; ... %! 50 60; ... %! 70 80]; %! exp = [... %! 30 40; ... %! 40 50; ... %! 50 60]; %! mid = midPoint(p1, p2); %! assert (mid, exp); %!test %! p1 = [ ... %! 10 20 ; ... %! 30 40 ; ... %! 50 60 ; ... %! ]; %! p2 = [30 40]; %! exp = [... %! 20 30; ... %! 30 40; ... %! 40 50]; %! mid = midPoint(p1, p2); %! assert (mid, exp); %!test %! p1 = [ ... %! 10 20 ; ... %! 30 40 ; ... %! 50 60 ; ... %! ]; %! p2 = [30 40]; %! expX = [20 ; 30 ; 40]; %! expY = [30 ; 40 ; 50]; %! [x y] = midPoint(p1, p2); %! assert (x, expX); %! assert (y, expY); %!test %! edge = [10 20 30 40]; %! exp = [20 30]; %! mid = midPoint(edge); %! assert (mid, exp); %! edge = [10 20 30 40; 30 40 50 60; 50 60 70 80]; %! exp = [20 30;40 50; 60 70]; %! mid = midPoint(edge); %! assert (mid, exp); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/nndist.m0000644000000000000000000000013213066736044016735 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/nndist.m0000644000175000017500000000742113066736044017115 0ustar00olafolaf00000000000000## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %NNDIST Nearest-neighbor distances of each point in a set % % DISTS = nndist(POINTS) % Returns the distance to the nearest neighbor of each point in an array % of points. % POINTS is an array of points, NP-by-ND. % DISTS is a NP-by-1 array containing the distances to the nearest % neighbor. % % This functions first computes the Delaunay triangulation of the set of % points, then search for nearest distance in the set of each vertex % neighbors. This reduces the overall complexity, but difference was % noticed only for large sets (>10000 points) % % Example % % Display Stienen diagram of a set of random points in unit square % pts = rand(100, 2); % [dists, inds] = nndist(pts); % figure; drawPoint(pts, 'k.'); % hold on; drawCircle([pts dists/2], 'b'); % axis equal; axis([-.1 1.1 -.1 1.1]); % % also display edges % drawEdge([pts pts(inds, :)], 'b'); % % See also % points2d, distancePoints, minDistancePoints, findPoint % % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % Created: 2011-12-01, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. function [dists, neighInds] = nndist(points) % number of points n = size(points, 1); % allocate memory dists = zeros(n, 1); neighInds = zeros(n, 1); % in case of few points, use direct computation if n < 3 inds = 1:n; for i = 1:n % compute minimal distance [dists(i), indN] = minDistancePoints(points(i,:), points(inds~=i, :)); if indN >= i neighInds(i) = inds(indN) + 1; else neighInds(i) = inds(indN); end end return; end % use Delaunay Triangulation to facilitate computations DT = delaunayTriangulation(points); % compute distance to nearest neighbor of each point in the pattern for i = 1:n % find indices of neighbor vertices in Delaunay Triangulation. % this set contains the nearest neighbor inds = unique(DT.ConnectivityList(sum(DT.ConnectivityList == i, 2) > 0, :)); inds = inds(inds~=i); % compute minimal distance [dists(i), indN] = min(distancePoints(points(i,:), points(inds, :))); neighInds(i) = inds(indN); end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/edgeAngle.m0000644000000000000000000000013213066736044017311 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/edgeAngle.m0000644000175000017500000000434613066736044017474 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{theta} =} edgeAngle(@var{edge}) ## Return angle of edge ## ## A = edgeAngle(EDGE) ## Returns the angle between horizontal, right-axis and the edge EDGE. ## Angle is given in radians, between 0 and 2*pi, in counter-clockwise ## direction. ## Notation for edge is [x1 y1 x2 y2] (coordinates of starting and ending ## points). ## ## Example ## p1 = [10 20]; ## p2 = [30 40]; ## rad2deg(edgeAngle([p1 p2])) ## ans = ## 45 ## ## @seealso{edges2d, angles2d, edgeAngle, lineAngle, edgeLength} ## @end deftypefn function theta = edgeAngle(edge) line = createLine(edge(:,1:2), edge(:,3:4)); theta = lineAngle(line); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/findClosestPoint.m0000644000000000000000000000013213066736044020725 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/findClosestPoint.m0000644000175000017500000000524413066736044021106 0ustar00olafolaf00000000000000## Copyright (C) 2004-2015 David Legland ## Copyright (C) 2004-2015 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{index}, @var{mindist}] =} findClosestPoint (@var{point}, @var{pointarray}) ## Find index of closest point in an array and the distance between @var{point} and closest point in @var{pointarray}. ## ## Example: ##@example ## pts = rand(10, 2); ## findClosestPoint(pts(4, :), pts) ## ans = ## 4 ##@end example ## @seealso{points2d, minDistancePoints, distancePoints} ## @end deftypefn function [index, minDist] = findClosestPoint(coord, points) % number of point in first input to process np = size (coord, 1); % allocate memory for result index = zeros (np, 1); minDist = zeros (np, 1); for i = 1:np % compute squared distance between current point and all point in array dist = sumsq (coord(i,:) - points, 2); % keep index of closest point [minDist(i), index(i)] = min(dist); endfor endfunction %!demo %! pts = rand (10, 2); %! pt = rand (1, 2); %! [idx d] = findClosestPoint (pt, pts); %! printf ("Point (%g,%g).\n", pt); %! printf ("The %dth is the closest point (%g,%g).\n", idx, pts(idx,:)); %! printf ("The distance between them is %g.\n", d); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/vectorAngle.m0000644000000000000000000000013213066736044017707 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/vectorAngle.m0000644000175000017500000001336013066736044020066 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{alpha} =} vectorAngle (@var{v1}) ## Angle of a vector, or between 2 vectors ## ## A = vectorAngle(V); ## Returns angle between Ox axis and vector direction, in Counter ## clockwise orientation. ## The result is normalised between 0 and 2*PI. ## ## A = vectorAngle(V1, V2); ## Returns the angle from vector V1 to vector V2, in counter-clockwise ## order, and in radians. ## ## A = vectorAngle(..., 'cutAngle', CUTANGLE); ## A = vectorAngle(..., CUTANGLE); # (deprecated syntax) ## Specifies convention for angle interval. CUTANGLE is the center of the ## 2*PI interval containing the result. See normalizeAngle for details. ## ## Example: ## rad2deg(vectorAngle([2 2])) ## ans = ## 45 ## rad2deg(vectorAngle([1 sqrt(3)])) ## ans = ## 60 ## rad2deg(vectorAngle([0 -1])) ## ans = ## 270 ## ## @seealso{vectors2d, angles2d, normalizeAngle} ## @end deftypefn function alpha = vectorAngle(v1, varargin) ## Initializations # default values v2 = []; cutAngle = pi; # process input arguments while ~isempty(varargin) var = varargin{1}; if isnumeric(var) && isscalar(var) # argument is normalization constant cutAngle = varargin{1}; varargin(1) = []; elseif isnumeric(var) && size(var, 2) == 2 # argument is second vector v2 = varargin{1}; varargin(1) = []; elseif ischar(var) && length(varargin) >= 2 # argument is option given as string + value if strcmpi(var, 'cutAngle') cutAngle = varargin{2}; varargin(1:2) = []; else error(['Unknown option: ' var]); end else error('Unable to parse inputs'); end end ## Case of one vector # If only one vector is provided, computes its angle if isempty(v2) # compute angle and format result in a 2*pi interval alpha = atan2(v1(:,2), v1(:,1)); # normalize within a 2*pi interval alpha = normalizeAngle(alpha + 2*pi, cutAngle); return; end ## Case of two vectors # compute angle of each vector alpha1 = atan2(v1(:,2), v1(:,1)); alpha2 = atan2(v2(:,2), v2(:,1)); # difference alpha = bsxfun(@minus, alpha2, alpha1); # normalize within a 2*pi interval alpha = normalizeAngle(alpha + 2*pi, cutAngle); endfunction %!test %! ang = vectorAngle([1 0]); %! assert(0, ang, 1e-6); %!test %! ang = vectorAngle([0 1]); %! assert(pi/2, ang, 1e-6); %!test %! ang = vectorAngle([-1 0]); %! assert(pi, ang, 1e-6); %!test %! ang = vectorAngle([0 -1]); %! assert(3*pi/2, ang, 1e-6); %!test %! ang = vectorAngle([-1 1]); %! assert(3*pi/4, ang, 1e-6); %!test %! ang = vectorAngle([1 0], pi); %! assert(0, ang, 1e-6); %!test %! ang = vectorAngle([0 1], pi); %! assert(pi/2, ang, 1e-6); %!test %! ang = vectorAngle([-1 0], pi); %! assert(pi, ang, 1e-6); %!test %! ang = vectorAngle([0 -1], pi); %! assert(3*pi/2, ang, 1e-6); %!test %! ang = vectorAngle([-1 1], pi); %! assert(3*pi/4, ang, 1e-6); %!test %! vecs = [1 0;0 1;-1 0;0 -1;1 1]; %! angs = [0;pi/2;pi;3*pi/2;pi/4]; %! assert(angs, vectorAngle(vecs)); %! assert(angs, vectorAngle(vecs, pi)); %!test %! ang = vectorAngle([1 0], 0); %! assert(0, ang, 1e-6); %!test %! ang = vectorAngle([0 1], 0); %! assert(pi/2, ang, 1e-6); %!test %! ang = vectorAngle([0 -1], 0); %! assert(-pi/2, ang, 1e-6); %!test %! ang = vectorAngle([-1 1], 0); %! assert(3*pi/4, ang, 1e-6); %!test %! vecs = [1 0;0 1;0 -1;1 1;1 -1]; %! angs = [0;pi/2;-pi/2;pi/4;-pi/4]; %! assert(angs, vectorAngle(vecs, 0), 1e-6); %!test %! v1 = [1 0]; %! v2 = [0 1]; %! ang = pi /2 ; %! assert(ang, vectorAngle(v1, v2), 1e-6); %!test %! v1 = [1 0]; %! v2 = [0 1; 0 1; 1 1; -1 1]; %! ang = [pi / 2 ;pi / 2 ;pi / 4 ; 3 * pi / 4]; %! assert(ang, vectorAngle(v1, v2), 1e-6); %!test %! v1 = [0 1; 0 1; 1 1; -1 1]; %! v2 = [-1 0]; %! ang = [pi / 2 ;pi / 2 ; 3 * pi / 4 ; pi / 4]; %! assert(ang, vectorAngle(v1, v2), 1e-6); %!test %! v1 = [1 0; 0 1; 1 1; -1 1]; %! v2 = [0 1; 1 0; -1 1; -1 0]; %! ang = [pi / 2 ;3 * pi / 2 ;pi / 2 ; pi / 4]; %! assert(ang, vectorAngle(v1, v2), 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPerpendicular.m0000644000000000000000000000013213066736044020567 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPerpendicular.m0000644000175000017500000000632313066736044020747 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPerpendicular (@var{v1}, @var{v2}) ## @deftypefnx {Function File} {@var{b} = } isPerpendicula (@var{v1}, @var{v2},@var{tol}) ## heck orthogonality of two vectors. ## ## @var{v1} and @var{v2} are 2 row vectors of length Nd, Nd being the dimension, ## returns @code{true} if the vectors are perpendicular, and @code{false} otherwise. ## ## Also works when @var{v1} and @var{v2} are two [NxNd] arrays with same number of ## rows. In this case, return a [Nx1] array containing @code{true} at the positions ## of parallel vectors. ## ## @var{tol} specifies the accuracy of numerical computation. Default value is 1e-14. ## ## Example ## ## @example # isPerpendicular([1 2 0], [0 0 2]) ## ans = ## 1 # isPerpendicular([1 2 1], [1 3 2]) ## ans = ## 0 ## @end example ## ## @seealso{vectors2d, isParallel, lines2d} ## @end deftypefn ## FIXME or erase me ## Also works when one of @var{v1} or @var{v2} is scalar and the other one is [NxNd] ## array, in this case return [Nx1] results. function b = isPerpendicular(v1, v2, varargin) # default accuracy acc = 1e-14; if ~isempty (varargin) acc = abs (varargin{1}); end # adapt size of inputs n1 = size (v1, 1); n2 = size (v2, 1); if n1~=n2 if n1==1 v1 = v1(ones (n2, 1), :); elseif n2==1 v2 = v2(ones (n1, 1), :); else error('Inputs must either have same size, or one must be scalar'); end end # performs test b = abs (dot (v1, v2, 2)) < acc; endfunction %!assert (isPerpendicular ([1 2 0], [0 0 2])) %!assert (!isPerpendicular([1 2 1], [1 3 2])) %!error (isPerpendicular(1, rand(4,3))) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/reverseLine.m0000644000000000000000000000013213066736044017721 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/reverseLine.m0000644000175000017500000000376213066736044020105 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line} = } reverseLine (@var{line}) ## Return same line but with opposite orientation ## ## INVLINE = reverseLine(LINE); ## Returns the opposite line of LINE. ## LINE has the format [x0 y0 dx dy], then INVLINE will have following ## parameters: [x0 y0 -dx -dy]. ## ## @seealso{lines2d, createLine} ## @end deftypefn function line = reverseLine(line) line(:, 3:4) = -line(:, 3:4); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/rotateVector.m0000644000000000000000000000013213066736044020117 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/rotateVector.m0000644000175000017500000000435413066736044020301 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{vr} = } rotateVector (@var{v}, @var{theta}) ## Rotate a vector by a given angle ## ## Rotate the vector @var{v} by an angle @var{theta}, given in radians. ## ## Example ## ## @example ## rotateVector([1 0], pi/2) ## ans = ## 0 1 ## @end example ## ## @seealso{vectors2d, transformVector, createRotation} ## @end deftypefn function vr = rotateVector(v, angle) # precomputes angles cot = cos(angle); sit = sin(angle); # compute rotated coordinates vr = [cot * v(:,1) - sit * v(:,2) , sit * v(:,1) + cot * v(:,2)]; endfunction %!assert ([0 1],rotateVector([1 0],pi/2), 1e-6) %!assert (sqrt([0.5 0.5]),rotateVector([1 0],pi/4), 1e-6) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/intersectLines.m0000644000000000000000000000013213066736044020431 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/intersectLines.m0000644000175000017500000001350713066736044020613 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} =} intersectLines (@var{line1}, @var{line2}) ## @deftypefnx {Function File} {@var{point} =} intersectLines (@var{line1}, @var{line2},@var{eps}) ## Return all intersection points of N lines in 2D. ## ## Returns the intersection point of lines @var{line1} and @var{line2}. ## @var{line1} and @var{line2} are [1*4] ## arrays, containing parametric representation of each line (in the form ## [x0 y0 dx dy], see @code{createLine} for details). ## ## In case of colinear lines, returns [Inf Inf]. ## In case of parallel but not colinear lines, returns [NaN NaN]. ## ## If each input is [N*4] array, the result is a [N*2] array containing ## intersections of each couple of lines. ## If one of the input has N rows and the other 1 row, the result is a ## [N*2] array. ## ## A third input argument specifies the tolerance for detecting parallel lines. ## Default is 1e-14. ## ## Example ## ## @example ## line1 = createLine([0 0], [10 10]); ## line2 = createLine([0 10], [10 0]); ## point = intersectLines(line1, line2) ## point = ## 5 5 ## @end example ## ## @seealso{lines2d, edges2d, intersectEdges, intersectLineEdge, intersectLineCircle} ## @end deftypefn function point = intersectLines(line1, line2, varargin) # extreact tolerance tol = 1e-14; if !isempty(varargin) tol = varargin{1}; end x1 = line1(:,1); y1 = line1(:,2); dx1 = line1(:,3); dy1 = line1(:,4); x2 = line2(:,1); y2 = line2(:,2); dx2 = line2(:,3); dy2 = line2(:,4); N1 = length(x1); N2 = length(x2); # indices of parallel lines par = abs(dx1.*dy2 - dx2.*dy1) < tol; # indices of colinear lines col = abs((x2-x1) .* dy1 - (y2-y1) .* dx1) < tol & par ; x0(col) = Inf; y0(col) = Inf; x0(par & !col) = NaN; y0(par & !col) = NaN; i = !par; # compute intersection points if N1==N2 x0(i) = ((y2(i)-y1(i)).*dx1(i).*dx2(i) + x1(i).*dy1(i).*dx2(i) - x2(i).*dy2(i).*dx1(i)) ./ ... (dx2(i).*dy1(i)-dx1(i).*dy2(i)) ; y0(i) = ((x2(i)-x1(i)).*dy1(i).*dy2(i) + y1(i).*dx1(i).*dy2(i) - y2(i).*dx2(i).*dy1(i)) ./ ... (dx1(i).*dy2(i)-dx2(i).*dy1(i)) ; elseif N1==1 x0(i) = ((y2(i)-y1).*dx1.*dx2(i) + x1.*dy1.*dx2(i) - x2(i).*dy2(i).*dx1) ./ ... (dx2(i).*dy1-dx1.*dy2(i)) ; y0(i) = ((x2(i)-x1).*dy1.*dy2(i) + y1.*dx1.*dy2(i) - y2(i).*dx2(i).*dy1) ./ ... (dx1.*dy2(i)-dx2(i).*dy1) ; elseif N2==1 x0(i) = ((y2-y1(i)).*dx1(i).*dx2 + x1(i).*dy1(i).*dx2 - x2.*dy2.*dx1(i)) ./ ... (dx2.*dy1(i)-dx1(i).*dy2) ; y0(i) = ((x2-x1(i)).*dy1(i).*dy2 + y1(i).*dx1(i).*dy2 - y2.*dx2.*dy1(i)) ./ ... (dx1(i).*dy2-dx2.*dy1(i)) ; else # formattage a rajouter x0(i) = ((y2(i)-y1(i)).*dx1(i).*dx2(i) + x1(i).*dy1(i).*dx2(i) - x2(i).*dy2(i).*dx1(i)) ./ ... (dx2(i).*dy1(i)-dx1(i).*dy2(i)) ; y0(i) = ((x2(i)-x1(i)).*dy1(i).*dy2(i) + y1(i).*dx1(i).*dy2(i) - y2(i).*dx2(i).*dy1(i)) ./ ... (dx1(i).*dy2(i)-dx2(i).*dy1(i)) ; end # concatenate result point = [x0' y0']; endfunction %!test # basic test with two orthogonal lines %! line1 = [3 1 0 1]; %! line2 = [1 4 1 0]; %! assert (intersectLines(line1, line2), [3 4], 1e-6); %!test # orthognal diagonal lines %! line1 = [0 0 3 2]; %! line2 = [5 -1 4 -6]; %! assert (intersectLines(line1, line2), [3 2], 1e-6); %!test # one diagonal and one horizontal line %! line1 = [10 2 25 0]; %! line2 = [5 -1 4 -6]; %! assert (intersectLines(line1, line2), [3 2], 1e-6); %!test # check for dx and dy very big compared to other line %! line1 = [3 1 0 1000]; %! line2 = [1 4 -14 0]; %! assert (intersectLines(line1, line2), [3 4], 1e-6); %!test %! line1 = [2 0 20000 30000]; %! line2 = [1 6 1 -1]; %! assert (intersectLines(line1, line2), [4 3], 1e-6); %!test %! line1 = [3 1 0 1]; %! line2 = repmat([1 4 1 0], 5, 1); %! res = repmat([3 4], 5, 1); %! inters = intersectLines(line1, line2); %! assert (res, inters, 1e-6); %!test %! line1 = repmat([3 1 0 1], 5, 1); %! line2 = [1 4 1 0]; %! res = repmat([3 4], 5, 1); %! inters = intersectLines(line1, line2); %! assert (res, inters, 1e-6); %!test %! line1 = repmat([3 1 0 1], 5, 1); %! line2 = repmat([1 4 1 0], 5, 1); %! res = repmat([3 4], 5, 1); %! inters = intersectLines(line1, line2); %! assert (res, inters, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/geom2d_Contents.m0000644000000000000000000000013213066736044020470 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/geom2d_Contents.m0000644000175000017500000002677413066736044020664 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} geom2d_Contents () ## Geometry 2D Toolbox ## Version 1.2.0 21-Oct-2011 . ## ## Library to handle and visualize geometric primitives such as points, ## lines, circles and ellipses, polygons... ## ## The goal is to provide a low-level library for manipulating geometrical ## primitives, making easier the development of more complex geometric ## algorithms. ## ## Most functions works for planar shapes, but some ones have been ## extended to 3D or to any dimension. ## ## Points ## points2d - Description of functions operating on points ## clipPoints - Clip a set of points by a box ## centroid - Compute centroid (center of mass) of a set of points ## midPoint - Middle point of two points or of an edge ## isCounterClockwise - Compute relative orientation of 3 points ## polarPoint - Create a point from polar coordinates (rho + theta) ## angle2Points - Compute horizontal angle between 2 points ## angle3Points - Compute oriented angle made by 3 points ## angleSort - Sort points in the plane according to their angle to origin ## distancePoints - Compute distance between two points ## minDistancePoints - Minimal distance between several points ## transformPoint - Transform a point with an affine transform ## drawPoint - Draw the point on the axis. ## ## Vectors ## vectors2d - Description of functions operating on plane vectors ## createVector - Create a vector from two points ## vectorNorm - Compute norm of a vector, or of a set of vectors ## vectorAngle - Angle of a vector, or between 2 vectors ## normalizeVector - Normalize a vector to have norm equal to 1 ## isPerpendicular - Check orthogonality of two vectors ## isParallel - Check parallelism of two vectors ## transformVector - Transform a vector with an affine transform ## rotateVector - Rotate a vector by a given angle ## ## Straight lines ## lines2d - Description of functions operating on planar lines ## createLine - Create a straight line from 2 points, or from other inputs ## medianLine - Create a median line between two points ## cartesianLine - Create a straight line from cartesian equation coefficients ## orthogonalLine - Create a line orthogonal to another one. ## parallelLine - Create a line parallel to another one. ## intersectLines - Return all intersection points of N lines in 2D ## lineAngle - Computes angle between two straight lines ## linePosition - Position of a point on a line ## lineFit - Fit a straight line to a set of points ## clipLine - Clip a line with a box ## reverseLine - Return same line but with opposite orientation ## transformLine - Transform a line with an affine transform ## drawLine - Draw the line on the current axis ## ## Edges (line segments between 2 points) ## edges2d - Description of functions operating on planar edges ## createEdge - Create an edge between two points, or from a line ## edgeToLine - Convert an edge to a straight line ## edgeAngle - Return angle of edge ## edgeLength - Return length of an edge ## midPoint - Middle point of two points or of an edge ## edgePosition - Return position of a point on an edge ## clipEdge - Clip an edge with a rectangular box ## reverseEdge - Intervert the source and target vertices of edge ## intersectEdges - Return all intersections between two set of edges ## intersectLineEdge - Return intersection between a line and an edge ## transformEdge - Transform an edge with an affine transform ## drawEdge - Draw an edge given by 2 points ## drawCenteredEdge - Draw an edge centered on a point ## ## Rays ## rays2d - Description of functions operating on planar rays ## createRay - Create a ray (half-line), from various inputs ## bisector - Return the bisector of two lines, or 3 points ## clipRay - Clip a ray with a box ## drawRay - Draw a ray on the current axis ## ## Relations between points and lines ## distancePointEdge - Minimum distance between a point and an edge ## distancePointLine - Minimum distance between a point and a line ## projPointOnLine - Project of a point orthogonally onto a line ## pointOnLine - Create a point on a line at a given position on the line ## isPointOnLine - Test if a point belongs to a line ## isPointOnEdge - Test if a point belongs to an edge ## isPointOnRay - Test if a point belongs to a ray ## isLeftOriented - Test if a point is on the left side of a line ## ## Circles ## circles2d - Description of functions operating on circles ## createCircle - Create a circle from 2 or 3 points ## createDirectedCircle - Create a directed circle ## intersectCircles - Intersection points of two circles ## intersectLineCircle - Intersection point(s) of a line and a circle ## circleAsPolygon - Convert a circle into a series of points ## circleArcAsCurve - Convert a circle arc into a series of points ## isPointInCircle - Test if a point is located inside a given circle ## isPointOnCircle - Test if a point is located on a given circle. ## enclosingCircle - Find the minimum circle enclosing a set of points. ## radicalAxis - Compute the radical axis (or radical line) of 2 circles ## drawCircle - Draw a circle on the current axis ## drawCircleArc - Draw a circle arc on the current axis ## ## Ellipses ## ellipses2d - Description of functions operating on ellipses ## inertiaEllipse - Inertia ellipse of a set of points ## isPointInEllipse - Check if a point is located inside a given ellipse ## ellipseAsPolygon - Convert an ellipse into a series of points ## drawEllipse - Draw an ellipse on the current axis ## drawEllipseArc - Draw an ellipse arc on the current axis ## ## Geometric transforms ## transforms2d - Description of functions operating on transforms ## createTranslation - Create the 3*3 matrix of a translation ## createRotation - Create the 3*3 matrix of a rotation ## createScaling - Create the 3*3 matrix of a scaling in 2 dimensions ## createHomothecy - Create the the 3x3 matrix of an homothetic transform ## createBasisTransform - Compute matrix for transforming a basis into another basis ## createLineReflection - Create the the 3x3 matrix of a line reflection ## fitAffineTransform2d - Fit an affine transform using two point sets ## ## Angles ## angles2d - Description of functions for manipulating angles ## normalizeAngle - Normalize an angle value within a 2*PI interval ## angleAbsDiff - Absolute difference between two angles ## angleDiff - Difference between two angles ## deg2rad - Convert angle from degrees to radians ## rad2deg - Convert angle from radians to degrees ## ## Boxes ## boxes2d - Description of functions operating on bounding boxes ## intersectBoxes - Intersection of two bounding boxes ## mergeBoxes - Merge two boxes, by computing their greatest extent ## randomPointInBox - Generate random point within a box ## drawBox - Draw a box defined by coordinate extents ## ## Various drawing functions ## drawBezierCurve - Draw a cubic bezier curve defined by 4 control points ## drawParabola - Draw a parabola on the current axis ## drawOrientedBox - Draw centered oriented rectangle ## drawRect - Draw rectangle on the current axis ## drawArrow - Draw an arrow on the current axis ## drawLabels - Draw labels at specified positions ## drawShape - Draw various types of shapes (circles, polygons...) ## ## Other shapes ## squareGrid - Generate equally spaces points in plane. ## hexagonalGrid - Generate hexagonal grid of points in the plane. ## triangleGrid - Generate triangular grid of points in the plane. ## crackPattern - Create a (bounded) crack pattern tessellation ## crackPattern2 - Create a (bounded) crack pattern tessellation ## ## ## Credits: ## * function 'enclosingCircle' rewritten from a file from Yazan Ahed ## , available on Matlab File Exchange ## ## @end deftypefn function geom2d_Contents () help('geom2d_Contents'); ## Deprecated functions # createMedian - create a median line # minDistance - compute minimum distance between a point and a set of points # homothecy - create a homothecy as an affine transform # rotation - return 3*3 matrix of a rotation # translation - return 3*3 matrix of a translation # scaling - return 3*3 matrix of a scaling in 2 dimensions # lineSymmetry - create line symmetry as 2D affine transform # vecnorm - compute norm of vector or of set of vectors # normalize - normalize a vector # onCircle - test if a point is located on a given circle. # inCircle - test if a point is located inside a given circle. # onEdge - test if a point belongs to an edge # onLine - test if a point belongs to a line # onRay - test if a point belongs to a ray # invertLine - return same line but with opposite orientation # clipLineRect - clip a line with a polygon # formatAngle - Ensure an angle value is comprised between 0 and 2*PI ## Others... # drawRect2 - Draw centered rectangle on the current axis endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/rays2d.m0000644000000000000000000000013213066736044016642 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/rays2d.m0000644000175000017500000000454613066736044017027 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} rays2d () ## Description of functions operating on planar rays ## ## A ray is defined by a point (its origin), and a vector (its ## direction). The different parameters are bundled into a row vector: ## @code{RAY = [x0 y0 dx dy];} ## ## The ray contains all the points (x,y) such that: ## x = x0 + t*dx ## y = y0 + t*dy; ## for all t>0 ## ## Contrary to a (straight) line, the points located before the origin do ## not belong to the ray. ## However, as rays and lines have the same representation, some functions ## working on lines are also working on rays (like @code{transformLine}). ## ## @seealso{points2d, vectors2d, lines2d, createRay, bisector, isPointOnRay, ## clipRay, drawRay} ## @end deftypefn function rays2d(varargin) help('rays2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawBox.m0000644000000000000000000000013213066736044017044 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawBox.m0000644000175000017500000000525713066736044017231 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawBox (@var{box}) ## @deftypefnx {Function File} {@var{h} =} drawBox (@var{box}, @var{param}, @var{value}, @dots{}) ## Draw a box defined by coordinate extents ## ## Draws a box defined by its extent: @var{box} = [@var{xmin} @var{xmax} ## @var{ymin} @var{ymax}]. Addtional ## arguments are passed to function @code{plot}. If requested, it returns the ## handle to the graphics object created. ## ## @seealso{drawOrientedBox, drawRect, plot} ## @end deftypefn function varargout = drawBox(box, varargin) # default values xmin = box(:,1); xmax = box(:,2); ymin = box(:,3); ymax = box(:,4); nBoxes = size(box, 1); r = zeros(nBoxes, 1); # iterate on boxes for i = 1:nBoxes # exract min and max values tx(1) = xmin(i); ty(1) = ymin(i); tx(2) = xmax(i); ty(2) = ymin(i); tx(3) = xmax(i); ty(3) = ymax(i); tx(4) = xmin(i); ty(4) = ymax(i); tx(5) = xmin(i); ty(5) = ymin(i); # display polygon r(i) = plot(tx, ty, varargin{:}); end # format output if nargout > 0 varargout = {r}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/inertiaEllipse.m0000644000000000000000000000013213066736044020407 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/inertiaEllipse.m0000644000175000017500000000646613066736044020577 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{ell} = } inertiaEllipse (@var{pts}) ## Inertia ellipse of a set of points ## ## ELL = inertiaEllipse(PTS); ## where PTS is a N*2 array containing coordinates of N points, computes ## the inertia ellispe of the set of points. ## ## The result has the form: ## ELL = [XC YC A B THETA], ## with XC and YC being the center of mass of the point set, A and B are ## the lengths of the inertia ellipse (see below), and THETA is the angle ## of the main inertia axis with the horizontal (counted in degrees ## between 0 and 180). ## A and B are the standard deviations of the point coordinates when ## ellipse is aligned with the inertia axes. ## ## @example ## pts = randn(100, 2); ## pts = transformPoint(pts, createScaling(5, 2)); ## pts = transformPoint(pts, createRotation(pi/6)); ## pts = transformPoint(pts, createTranslation(3, 4)); ## ell = inertiaEllipse(pts); ## figure(1); clf; hold on; ## drawPoint(pts); ## drawEllipse(ell, 'linewidth', 2, 'color', 'r'); ## @end example ## ## @seealso{ellipses2d, drawEllipse} ## @end deftypefn function ell = inertiaEllipse(points) # ellipse center xc = mean (points(:,1)); yc = mean (points(:,2)); # recenter points x = points(:,1) - xc; y = points(:,2) - yc; # number of points n = size (points, 1); # inertia parameters Ixx = sumsq (x) / n; Iyy = sumsq (y) / n; Ixy = sum (x.*y) / n; # compute ellipse semi-axis lengths common = sqrt ( (Ixx - Iyy)^2 + 4 * Ixy^2); ra = sqrt (2) * sqrt (Ixx + Iyy + common); rb = sqrt (2) * sqrt (Ixx + Iyy - common); # compute ellipse angle in degrees theta = atan2 (2 * Ixy, Ixx - Iyy) / 2; theta = rad2deg (theta); # create the resulting inertia ellipse ell = [xc yc ra rb theta]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/cbezier2poly.m0000644000000000000000000000013213066736044020047 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/cbezier2poly.m0000644000175000017500000001242713066736044020231 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pp} =} cbezier2poly (@var{points}) ## @deftypefnx {Function File} {[@var{x} @var{y}] =} cbezier2poly (@var{points},@var{t}) ## Returns the polynomial representation of the cubic Bezier defined by the control points @var{points}. ## ## With only one input argument, calculates the polynomial @var{pp} of the cubic ## Bezier curve defined by the 4 control points stored in @var{points}. The first ## point is the inital point of the curve. The segment joining the first point ## with the second point (first center) defines the tangent of the curve at the initial point. ## The segment that joints the third point (second center) with the fourth defines the tanget at ## the end-point of the curve, which is defined in the fourth point. ## @var{points} is either a 4-by-2 array (vertical concatenation of point ## coordinates), or a 1-by-8 array (horizotnal concatenation of point ## coordinates). @var{pp} is a 2-by-3 array, 1st row is the polynomial for the ## x-coordinate and the 2nd row for the y-coordinate. Each row can be evaluated ## with @code{polyval}. The polynomial @var{pp}(t) is defined for t in [0,1]. ## ## When called with a second input argument @var{t}, it returns the coordinates ## @var{x} and @var{y} corresponding to the polynomial evaluated at @var{t} in ## [0,1]. ## ## @seealso{drawBezierCurve, polyval} ## @end deftypefn function varargout = cbezier2poly (points, ti=[]) # rename points if size(points, 2)==2 # case of points given as a 4-by-2 array p1 = points(1,:); c1 = points(2,:); c2 = points(3,:); p2 = points(4,:); elseif size(points,2) == 8 # case of points given as a 1-by-8 array, [X1 Y1 CX1 CX2..] p1 = points(1:2); c1 = points(3:4); c2 = points(5:6); p2 = points(7:8); else print_usage ; end # compute coefficients of Bezier Polynomial pp = zeros(2,4); pp(:,4) = [p1(1); ... p1(2)]; pp(:,3) = [3 * c1(1) - 3 * p1(1); ... 3 * c1(2) - 3 * p1(2)]; pp(:,2) = [3 * p1(1) - 6 * c1(1) + 3 * c2(1); ... 3 * p1(2) - 6 * c1(2) + 3 * c2(2)]; pp(:,1) = [p2(1) - 3 * c2(1) + 3 * c1(1) - p1(1); ... p2(2) - 3 * c2(2) + 3 * c1(2) - p1(2)]; if isempty (ti) varargout{1} = pp; else varargout{1} = polyval (pp(1,:), ti); varargout{2} = polyval (pp(2,:), ti); end endfunction %!demo %! points = [45.714286 483.79075; ... %! 241.65656 110.40445; ... %! 80.185847 741.77381; ... %! 537.14286 480.93361]; %! %! pp = cbezier2poly(points); %! t = linspace(0,1,64); %! x = polyval(pp(1,:),t); %! y = polyval(pp(2,:),t); %! plot (x,y,'b-',points([1 4],1),points([1 4],2),'s',... %! points([2 3],1),points([2 3],2),'o'); %! line(points([2 1],1),points([2 1],2),'color','r'); %! line(points([3 4],1),points([3 4],2),'color','r'); %!demo %! points = [0 0; ... %! 1 1; ... %! 1 1; ... %! 2 0]; %! %! t = linspace(0,1,64); %! [x y] = cbezier2poly(points,t); %! plot (x,y,'b-',points([1 4],1),points([1 4],2),'s',... %! points([2 3],1),points([2 3],2),'o'); %! line(points([2 1],1),points([2 1],2),'color','r'); %! line(points([3 4],1),points([3 4],2),'color','r'); %!test %! points = [0 0; ... %! 1 1; ... %! 1 1; ... %! 2 0]; %! t = linspace(0,1,64); %! %! [x y] = cbezier2poly(points,t); %! pp = cbezier2poly(points); %! x2 = polyval(pp(1,:),t); %! y2 = polyval(pp(2,:),t); %! assert(x,x2); %! assert(y,y2); %!test %! points = [0 0; ... %! 1 1; ... %! 1 1; ... %! 2 0]; %! t = linspace(0,1,64); %! %! p = reshape(points,1,8); %! [x y] = cbezier2poly(p,t); %! pp = cbezier2poly(p); %! x2 = polyval(pp(1,:),t); %! y2 = polyval(pp(2,:),t); %! assert(x,x2); %! assert(y,y2); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isLeftOriented.m0000644000000000000000000000013213066736044020356 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isLeftOriented.m0000644000175000017500000000441213066736044020533 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isLeftOriented (@var{point}, @var{line}) ## Test if a point is on the left side of a line ## ## B = isLeftOriented(POINT, LINE); ## Returns TRUE if the point lies on the left side of the line with ## respect to the line direction. ## ## @seealso{lines2d, points2d, isCounterClockwise, isPointOnLine, distancePointLine} ## @end deftypefn function b = isLeftOriented(point, line) Nl = size(line, 1); Np = size(point, 1); x0 = repmat(line(:,1)', Np, 1); y0 = repmat(line(:,2)', Np, 1); dx = repmat(line(:,3)', Np, 1); dy = repmat(line(:,4)', Np, 1); xp = repmat(point(:,1), 1, Nl); yp = repmat(point(:,2), 1, Nl); b = (xp-x0).*dy-(yp-y0).*dx < 0; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/parallelLine.m0000644000000000000000000000013213066736044020042 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/parallelLine.m0000644000175000017500000000541713066736044020225 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{res} = } parallelLine (@var{line}, @var{point}) ## @deftypefnx {Function File} {@var{res} = } parallelLine (@var{line}, @var{dist}) ## Create a line parallel to another one. ## ## Returns the line with same direction vector than @var{line} and going through ## the point given by @var{point}. ## @var{line} is given as [x0 y0 dx dy] and @var{point} is [xp yp]. ## ## Uses relative distance to specify position. The new line will be ## located at distance @var{dist}, counted positive in the right side of @var{line} ## and negative in the left side. ## ## @seealso{lines2d, orthogonalLine, distancePointLine} ## @end deftypefn function res = parallelLine (l, point) if size (point, 2) == 1 # use a distance. Compute position of point located # at distance DIST on the line orthogonal to the first one. point = pointOnLine ([l(:,[1 2 4]) -l(:,3)], point); end # normal case: compute line through a point with given direction res = zeros (size (l, 1), 4); res(:,1:2) = point; res(:,3:4) = l (:, 3:4); endfunction %!demo %! l = createLine ([0,0],[1,1]); %! lp = parallelLine (l, [0,1]); %! plot (0,1,'.r',1,1,'.g'); %! axis ([-1 1 -1 1]) %! drawLine([l; lp]); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/enclosingCircle.m0000644000000000000000000000013213066736044020541 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/enclosingCircle.m0000644000175000017500000000707213066736044020723 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{circle} = } enclosingCircle (@var{pts}) ## Find the minimum circle enclosing a set of points. ## ## CIRCLE = enclosingCircle(POINTS); ## computes the circle CIRCLE=[xc yc r] which encloses all the points POINTS ## given as a N-by-2 array. ## ## ## Rewritten from a file from ## Yazan Ahed ## which was rewritten from a Java applet by Shripad Thite : ## @url{http://heyoka.cs.uiuc.edu/~thite/mincircle/} ## ## @seealso{circles2d, points2d, boxes2d} ## @end deftypefn % ------ % Author: David Legland % e-mail: david.legland@nantes.inra.fr % created the 07/07/2005. % Copyright 2012 INRA - Cepia Software Platform. function circle = enclosingCircle(pts) # works on convex hull : it is faster pts = pts(convhull (pts(:,1), pts(:,2)), :); % call the recursive function circle = recurseCircle (size (pts, 1), pts, 1, zeros (3, 2)); endfunction function circ = recurseCircle(n, p, m, b) # n: number of points given # m: an argument used by the function. Always use 1 for m. # bnry: an argument (3x2 array) used by the function to set the points that # determines the circle boundry. You have to be careful when choosing this # array's values. I think the values should be somewhere outside your points # boundary. For my case, for example, I know the (x,y) I have will be something # in between (-5,-5) and (5,5), so I use bnry as: # [-10 -10 # -10 -10 # -10 -10] if m == 4 circ = createCircle(b(1,:), b(2,:), b(3,:)); return; end circ = [Inf Inf 0]; if m == 2 circ = [b(1,1:2) 0]; elseif m == 3 c = (b(1,:) + b(2,:))/2; circ = [c distancePoints(b(1,:), c)]; end for i = 1:n if distancePoints (p(i,:), circ(1:2)) > circ(3) if sum (b(:,1)==p(i,1) & b(:,2)==p(i,2)) == 0 b(m,:) = p(i,:); circ = recurseCircle (i, p, m+1, b); end end end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/medianLine.m0000644000000000000000000000013213066736044017503 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/medianLine.m0000644000175000017500000001102413066736044017655 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line} = } medianLine (@var{p1}, @var{p2}) ## @deftypefnx {Function File} {@var{line} = } medianLine (@var{pts}) ## @deftypefnx {Function File} {@var{line} = } medianLine (@var{edge}) ## Create a median line between two points. ## ## Create the median line of points @var{p1} and @var{p2}, that is the line containing ## all points located at equal distance of @var{p1} and @var{p2}. ## ## Creates the median line of 2 points, given as a 2*2 array @var{pts}. Array has ## the form: ## [ [ x1 y1 ] ; [ x2 y2 ] ] ## ## Creates the median of the @var{edge}. @var{edge} is a 1*4 array, containing [X1 Y1] ## coordinates of first point, and [X2 Y2], the coordinates of the second ## point. ## ## Example ## ## @example ## # Draw the median line of two points ## P1 = [10 20]; ## P2 = [30 50]; ## med = medianLine(P1, P2); ## figure; axis square; axis([0 100 0 100]); ## drawEdge([P1 P2], 'linewidth', 2, 'color', 'k'); ## drawLine(med) ## ## # Draw the median line of an edge ## P1 = [50 60]; ## P2 = [80 30]; ## edge = createEdge(P1, P2); ## figure; axis square; axis([0 100 0 100]); ## drawEdge(edge, 'linewidth', 2) ## med = medianLine(edge); ## drawLine(med) ## @end example ## ## @seealso{lines2d, createLine, orthogonalLine} ## @end deftypefn function lin = medianLine(varargin) nargs = length(varargin); x0 = 0; y0 = 0; dx = 0; dy = 0; if nargs == 1 tab = varargin{1}; if size(tab, 2)==2 # input is an array of two points x0 = tab(1,1); y0 = tab(1,2); dx = tab(2,1)-x0; dy = tab(2,2)-y0; else # input is an edge x0 = tab(:, 1); y0 = tab(:, 2); dx = tab(:, 3) - tab(:, 1); dy = tab(:, 4) - tab(:, 2); end elseif nargs==2 # input is given as two points, or two point arrays p1 = varargin{1}; p2 = varargin{2}; x0 = p1(:, 1); y0 = p1(:, 2); dx = bsxfun(@minus, p2(:, 1), x0); dy = bsxfun(@minus, p2(:, 2), y0); else error('Too many input arguments'); end # compute median using middle point of the edge, and the direction vector # rotated by 90 degrees counter-clockwise lin = [bsxfun(@plus, x0, dx/2), bsxfun(@plus, y0, dy/2), -dy, dx]; endfunction %!shared privpath %! privpath = [fileparts(which('geom2d_Contents')) filesep() 'private']; %!test %! addpath (privpath,'-end') %! p1 = [0 0]; %! p2 = [10 0]; %! exp = [5 0 0 10]; %! lin = medianLine(p1, p2); %! assertElementsAlmostEqual(exp, lin); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! p1 = [0 0]; %! p2 = [10 0]; %! exp = [5 0 0 10]; %! lin = medianLine([p1 p2]); %! assertElementsAlmostEqual(exp, lin); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! p1 = [0 0; 10 10]; %! p2 = [10 0;10 20]; %! exp = [5 0 0 10; 10 15 -10 0]; %! lin = medianLine(p1, p2); %! assertElementsAlmostEqual(exp, lin); %! rmpath (privpath); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawArrow.m0000644000000000000000000000013213066736044017406 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawArrow.m0000644000175000017500000001426013066736044017565 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawArrow (@var{x1}, @var{y1}, @var{x2}, @var{y2}) ## @deftypefnx {Function File} {@var{h} = } drawArrow ([@var{ @var{x1}} @var{ @var{y1}} @var{x2} @var{y2}]) ## @deftypefnx {Function File} {@var{h} = } drawArrow (@dots{}, @var{L}, @var{W},@var{R},@var{TYPE}) ## Draw an arrow on the current axis. ## ## Draw an arrow between the points (@var{x1} @var{y1}) and (@var{x2} @var{y2}). ## The points can be given as a single array. @var{L}, @var{W} specify length ## and width of the arrow. ## ## The length wings of the arrow can be modified with @var{R}. By default ## @var{R} is 0.1, giving a wing legnth of 0.1*@var{L}. ## ## Also specify arrow type. @var{TYPE} can be one of the following : ## 0: draw only two strokes ## 1: fill a triangle ## .5: draw a half arrow (try it to see ...) ## ## Arguments can be single values or array of size [N*1]. In this case, ## the function draws multiple arrows. ## ## The handle(s) to created arrow elements are retuned in @var{h}. ## The handles are returned in a structure with the fields ## @code{body},@code{wing} and @code{head} containing the handles to the ## different parts of the arrow(s). ## ## @end deftypefn function varargout = drawArrow (varargin) if isempty (varargin) error ('should specify at least one argument'); end # parse arrow coordinate if size (varargin{1}, 2) == 4 x1 = varargin{1}(:,1); y1 = varargin{1}(:,2); x2 = varargin{1}(:,3); y2 = varargin{1}(:,4); varargin = varargin(2:end); elseif length (varargin) > 3 x1 = varargin{1}; y1 = varargin{2}; x2 = varargin{3}; y2 = varargin{4}; varargin = varargin(5:end); else error ('wrong number of arguments, please read the doc'); end N = size (x1, 1); # default values l = 10 * ones (N, 1); % Body length w = 5 * ones (N, 1); % Head width r = 0.1 * ones (N, 1); % Head to body ratio h = zeros (N, 1); % Head type if ~isempty (varargin) # Parse paramters k = length (varargin); vartxt = 'lwrh'; cmd = ['%s = varargin{%d}; %s = %s(:);' ... 'if length (%s) < N; %s = %s(1) * ones (N , 1); end']; for i = 1:k v = vartxt(i); eval (sprintf (cmd, v, i, v, v, v, v, v)); end end ## Calculation # angle of the edge theta = atan2 (y2-y1, x2-x1); rl = r .* l; rh = r .* h; cT = cos (theta); sT = sin (theta); # point on the 'left' xa1 = x2 - rl .* cT - w .* sT / 2; ya1 = y2 - rl .* sT + w .* cT / 2; # point on the 'right' xa2 = x2 - rl .* cT + w .* sT / 2; ya2 = y2 - rl .* sT - w .* cT / 2; # point on the middle of the arrow xa3 = x2 - rh .* cT; ya3 = y2 - rh .* sT; ## Drawing # Get holding state old_hold = ishold (gca); if ~old_hold hold on; end axis equal; # draw main edge tmp = line ([x1.'; x2.'], [y1.'; y2.'], 'color', [0 0 1]); handle.body = tmp; # draw only 2 wings ind = find (h == 0); if ~isempty (ind) tmp = line ([xa1(ind).'; x2(ind).'], [ya1(ind).'; y2(ind).'], ... 'color', [0 0 1]); handle.wing(:,1) = tmp; tmp = line([xa2(ind).'; x2(ind).'], [ya2(ind).'; y2(ind).'], ... 'color', [0 0 1]); handle.wing(:,2) = tmp; end # draw a full arrow ind = find (h ~= 0); if ~isempty (ind) tmp = patch ([x2(ind) xa1(ind) xa3(ind) xa2(ind) x2(ind)].', ... [y2(ind) ya1(ind) ya3(ind) ya2(ind) y2(ind)].', [0 0 1]); handle.head = tmp; end if nargout > 0 varargout{1} = handle; end # Restore holding state if ~old_hold hold off end endfunction %!demo %! # Arrow type %! clf; %! orig = [cumsum(0.5*ones(3,1))-0.5 zeros(3,1)]; %! tip = orig + [0 1]; %! arrows = [orig tip]; %! %! # Different ratios %! subplot (2,1,1) %! r = [0.8 0.5 0.1]; %! h = drawArrow (arrows, 1, 0.1, r); %! title ("Ratios (3rd argument)") %! text (tip(:,1)+0.1,tip(:,2)-0.5,arrayfun(@num2str, r,"unif", 0)) %! %! # Different types %! subplot (2,1,2) %! ht = [0 0.5 1]; %! h = drawArrow (arrows, 1, 0.1 , 0.1, ht); %! title ("Head types (4th argument)") %! text (tip(:,1)+0.1,tip(:,2)-0.5,arrayfun(@num2str, ht,"unif", 0)) %!demo %! # Orthogonal projection respect to vector b %! dim = 2; %! b = 2*rand(dim,1); %! P = eye(dim) - (b*b')/(b'*b); %! v = 2*rand(dim,1)-1; %! Pv = P*v; %! %! # Draw the vectors %! clf; %! h = drawArrow ([zeros(3,dim) [b'; v'; Pv']],1,0.1); %! %! # Color them %! arrayfun(@(x,y)set(x,'color',y), [h.body; h.wing(:)],repmat(['rgb']',3,1)); %! # Name them %! legend (h.body, {'b','v','Pv'},'location','northoutside','orientation','horizontal'); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/normalizeAngle.m0000644000000000000000000000013213066736044020405 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/normalizeAngle.m0000644000175000017500000000625613066736044020572 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{alpha2} =} normalizeAngle (@var{alpha}) ## @deftypefnx {Function File} {@var{alpha2} =} normalizeAngle (@var{alpha}, @var{center}) ## Normalize an angle value within a 2*PI interval ## ## ALPHA2 = normalizeAngle(ALPHA); ## ALPHA2 is the same as ALPHA modulo 2*PI and is positive. ## ## ALPHA2 = normalizeAngle(ALPHA, CENTER); ## Specifies the center of the angle interval. ## If CENTER==0, the interval is [-pi ; +pi] ## If CENTER==PI, the interval is [0 ; 2*pi] (default). ## ## Example: ## # normalization between 0 and 2*pi (default) ## normalizeAngle(5*pi) ## ans = ## 3.1416 ## ## # normalization between -pi and +pi ## normalizeAngle(7*pi/2, 0) ## ans = ## -1.5708 ## ## @seealso{vectorAngle, lineAngle} ## @end deftypefn function alpha = normalizeAngle(alpha, varargin) center = pi; if ~isempty(varargin) center = varargin{1}; end alpha = mod(alpha-center+pi, 2*pi) + center-pi; endfunction %!assert (pi/2, normalizeAngle (pi/2), 1e-6); %!assert (pi, normalizeAngle (pi), 1e-6); %!assert (3*pi/2, normalizeAngle (3*pi/2), 1e-6); %!assert (pi/2, normalizeAngle (pi/2, pi), 1e-6); %!assert (pi, normalizeAngle (pi, pi), 1e-6); %!assert (3*pi/2, normalizeAngle (3*pi/2, pi), 1e-6); %!test %! theta = linspace(0, 2*pi-.1, 100); %! assert(theta, normalizeAngle (theta), 1e-6); %!assert (0, normalizeAngle (0, 0), 1e-6); %!assert (pi/2, normalizeAngle (pi/2, 0), 1e-6); %!assert (-pi, normalizeAngle (-pi, 0), 1e-6); %!assert (-pi/2, normalizeAngle (7*pi/2, 0), 1e-6); %!test %! theta = linspace(-pi+.1, pi-.1, 100); %! assert(theta, normalizeAngle (theta, 0), 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/minDistancePoints.m0000644000000000000000000000013213066736044021071 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/minDistancePoints.m0000644000175000017500000002444013066736044021251 0ustar00olafolaf00000000000000%% Copyright (C) 2004-2011 David Legland %% Copyright (C) 2016 Juan Pablo Carbajal %% All rights reserved. %% %% Redistribution and use in source and binary forms, with or without %% modification, are permitted provided that the following conditions are met: %% %% 1 Redistributions of source code must retain the above copyright notice, %% this list of conditions and the following disclaimer. %% 2 Redistributions in binary form must reproduce the above copyright %% notice, this list of conditions and the following disclaimer in the %% documentation and/or other materials provided with the distribution. %% %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' %% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE %% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE %% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR %% ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL %% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR %% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER %% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, %% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE %% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %% -*- texinfo -*- %% @deftypefn {Function File} {@var{dist} = } minDistancePoints (@var{pts}) %% @deftypefnx {Function File} {@var{dist} = } minDistancePoints (@var{pts1},@var{pts2}) %% @deftypefnx {Function File} {@var{dist} = } minDistancePoints (@dots{},@var{norm}) %% @deftypefnx {Function File} {[@var{dist} @var{i} @var{j}] = } minDistancePoints (@var{pts1}, @var{pts2}, @dots{}) %% @deftypefnx {Function File} {[@var{dist} @var{j}] = } minDistancePoints (@var{pts1}, @var{pts2}, @dots{}) %% Minimal distance between several points. %% %% Returns the minimum distance between all couple of points in @var{pts}. @var{pts} is %% an array of [NxND] values, N being the number of points and ND the %% dimension of the points. %% %% Computes for each point in @var{pts1} the minimal distance to every point of %% @var{pts2}. @var{pts1} and @var{pts2} are [NxD] arrays, where N is the number of points, %% and D is the dimension. Dimension must be the same for both arrays, but %% number of points can be different. %% The result is an array the same length as @var{pts1}. %% %% When @var{norm} is provided, it uses a user-specified norm. @var{norm}=2 means euclidean norm (the default), %% @var{norm}=1 is the Manhattan (or "taxi-driver") distance. %% Increasing @var{norm} growing up reduces the minimal distance, with a limit %% to the biggest coordinate difference among dimensions. %% %% Returns indices @var{i} and @var{j} of the 2 points which are the closest. @var{dist} %% verifies relation: %% @var{dist} = distancePoints(@var{pts}(@var{i},:), @var{pts}(@var{j},:)); %% %% If only 2 output arguments are given, it returns the indices of points which are the closest. @var{j} has the %% same size as @var{dist}. for each I It verifies the relation : %% @var{dist}(I) = distancePoints(@var{pts1}(I,:), @var{pts2}(@var{J},:)); %% %% %% Examples: %% %% @example %% % minimal distance between random planar points %% points = rand(20,2)*100; %% minDist = minDistancePoints(points); %% %% % minimal distance between random space points %% points = rand(30,3)*100; %% [minDist ind1 ind2] = minDistancePoints(points); %% minDist %% distancePoints(points(ind1, :), points(ind2, :)) %% % results should be the same %% %% % minimal distance between 2 sets of points %% points1 = rand(30,2)*100; %% points2 = rand(30,2)*100; %% [minDists inds] = minDistancePoints(points1, points2); %% minDists(10) %% distancePoints(points1(10, :), points2(inds(10), :)) %% % results should be the same %% @end example %% %% @seealso{points2d, distancePoints} %% @end deftypefn function varargout = minDistancePoints (p1, varargin) %% Initialisations % default norm (euclidean) n = 2; % a single array is given one_array = true; % process input variables if nargin == 1 % specify only one array of points, not the norm p2 = p1; elseif nargin == 2 if isscalar (varargin{1}) % specify array of points and the norm n = varargin{1}; p2 = p1; else % specify two arrays of points p2 = varargin{1}; one_array = false; end elseif nargin == 3 % specify two array of points and the norm p2 = varargin{1}; n = varargin{2}; one_array = false; else error ('Wrong number of input arguments'); end % number of points in each array n1 = size (p1, 1); n2 = size (p2, 1); % dimension of points d = size (p1, 2); %% Computation of distances % allocate memory dist = zeros (n1, n2); % Compute difference of coordinate for each pair of point (n1-by-n2 array) % and for each dimension. -> dist is a n1-by-n2 array. % in 2D: dist = dx.*dx + dy.*dy; if n == inf % infinite norm corresponds to maximum absolute value of differences % in 2D: dist = max(abs(dx) + max(abs(dy)); for i=1:d dist = max (dist, abs(bsxfun (@minus, p1(:,i), p2(:,i).'))); end else for i=1:d dist = dist + abs (bsxfun (@minus, p1(:,i), p2(:,i).')).^n; end end % TODO the previous could be optimized when a single array is given (maybe!) % If two array of points where given if ~one_array [minSqDist ind] = min(dist, [], 2); minDist = power (minSqDist, 1/n); [ind2 ind1] = ind2sub ([n1 n2], ind); else % A single array was given dist = dist + diag (inf (n1,1)); % remove zeros from diagonal dist = vech (dist); [minSqDist ind] = min (dist); % index on packed lower trinagular matrix minDist = power (minSqDist, 1/n); [ind2 ind1] = ind2sub_tril (n1, ind); ind = sub2ind ([n1 n1], ind2, ind1); endif %% format output parameters % format output depending on number of asked parameters if nargout<=1 varargout{1} = minDist; elseif nargout==2 % If two arrays are asked, 'ind' is an array of indices of p2, one for each % point in p1, corresponding to the result in minDist varargout{1} = minDist; varargout{2} = ind; elseif nargout==3 % If only one array is asked, minDist is a scalar, ind1 and ind2 are 2 % indices corresponding to the closest points. varargout{1} = minDist; varargout{2} = ind1; varargout{3} = ind2; end endfunction %!xtest %! pts = [50 10;40 60;30 30;20 0;10 60;10 30;0 10]; %! assert (minDistancePoints(pts), 20); %!xtest %! pts = [10 10;25 5;20 20;30 20;10 30]; %! [dist ind1 ind2] = minDistancePoints(pts); %! assert (10, dist, 1e-6); %! assert (3, ind1, 1e-6); %! assert (4, ind2, 1e-6); %!xtest %! pts = [0 80;10 60;20 40;30 20;40 0;0 0;100 0;0 100;0 -10;-10 -20]; %! assert (minDistancePoints([40 50], pts), 10*sqrt(5), 1e-6); %! assert (minDistancePoints([25 30], pts), 5*sqrt(5), 1e-6); %! assert (minDistancePoints([30 40], pts), 10, 1e-6); %! assert (minDistancePoints([20 40], pts), 0, 1e-6); %!xtest %! pts = [50 10;40 60;40 30;20 0;10 60;10 30;0 10]; %! assert (minDistancePoints(pts, 1), 30, 1e-6); %! assert (minDistancePoints(pts, 100), 20, 1e-6); %!xtest %! points = rand(30,3)*100; %! [minDist ind1 ind2] = minDistancePoints(points); %! assert (minDist, distancePoints(points(ind1, :), points(ind2, :)), sqrt(eps)); %!test %! pts = [0 80;10 60;20 40;30 20;40 0;0 0;100 0;0 100;0 -10;-10 -20]; %! assert (minDistancePoints([40 50], pts, 2), 10*sqrt(5), 1e-6); %! assert (minDistancePoints([25 30], pts, 2), 5*sqrt(5), 1e-6); %! assert (minDistancePoints([30 40], pts, 2), 10, 1e-6); %! assert (minDistancePoints([20 40], pts, 2), 0, 1e-6); %! assert (minDistancePoints([40 50], pts, 1), 30, 1e-6); %! assert (minDistancePoints([25 30], pts, 1), 15, 1e-6); %! assert (minDistancePoints([30 40], pts, 1), 10, 1e-6); %! assert (minDistancePoints([20 40], pts, 1), 0, 1e-6); %!test %! pts1 = [40 50;25 30;40 20]; %! pts2 = [0 80;10 60;20 40;30 20;40 0;0 0;100 0;0 100;0 -10;-10 -20]; %! res = [10*sqrt(5);5*sqrt(5);10]; %! assert (minDistancePoints(pts1, pts2), res, 1e-6); %!test %! pts1 = [40 50;25 30;40 20]; %! pts2 = [0 80;10 60;20 40;30 20;40 0;0 0;100 0;0 100;0 -10;-10 -20]; %! res1 = [10*sqrt(5);5*sqrt(5);10]; %! assert (minDistancePoints(pts1, pts2, 2), res1, 1e-6); %! res2 = [30;15;10]; %! assert (minDistancePoints(pts1, pts2, 1), res2); %!test %! pts1 = [40 50;20 30;40 20]; %! pts2 = [0 80;10 60;20 40;30 20;40 0;0 0;100 0;0 100;0 -10;-10 -20]; %! dists0 = [10*sqrt(5);10;10]; %! inds1 = [3;3;4]; %! [minDists inds] = minDistancePoints(pts1, pts2); %! assert (dists0, minDists); %! assert (inds1, inds); %!xtest %bug 50084 %! pt1 = [1 1]; %! pts = [0 0; 1 0; 1 1; 0 1; 1 2]; %! [d, r, c] = minDistancePoints (pt1, pts); %! assert (d, 0, sqrt(eps)); %! assert (r, 3, sqrt(eps)); %! assert (c, 1, sqrt(eps)); %%%%%%%%%%%%% % SUBFUNCTION %% -*- texinfo -*- %% @deftypefn {Function File} {[ @var{r}, @var{c} ] = } ind2sub_tril (@var{N}, @var{idx}) %% Convert a linear index to subscripts of a trinagular matrix. %% %% An example of trinagular matrix linearly indexed follows %% %% @example %% N = 4; %% A = -repmat (1:N,N,1); %% A += repmat (diagind, N,1) - A.'; %% A = tril(A) %% => A = %% 1 0 0 0 %% 2 5 0 0 %% 3 6 8 0 %% 4 7 9 10 %% @end example %% %% The following example shows how to convert the linear index `6' in %% the 4-by-4 matrix of the example into a subscript. %% %% @example %% [r, c] = ind2sub_tril (4, 6) %% => r = 3 %% c = 2 %% @end example %% %% when @var{idx} is a row or column matrix of linear indeces then @var{r} and %% @var{c} have the same shape as @var{idx}. %% %% @seealso{vech, ind2sub, sub2ind_tril} %% @end deftypefn function [r c] = ind2sub_tril (N,idx) endofrow = 0.5 * (1:N) .* (2*N:-1:N + 1); c = lookup (endofrow, idx - 1) + 1; r = N - endofrow(c) + idx ; end geometry-3.0.0/inst/geom2d/PaxHeaders.28738/lineAngle.m0000644000000000000000000000013213066736044017334 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/lineAngle.m0000644000175000017500000000712013066736044017510 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{theta} =} lineAngle(varargin) ## Computes angle between two straight lines ## ## A = lineAngle(LINE); ## Returns the angle between horizontal, right-axis and the given line. ## Angle is fiven in radians, between 0 and 2*pi, in counter-clockwise ## direction. ## ## A = lineAngle(LINE1, LINE2); ## Returns the directed angle between the two lines. Angle is given in ## radians between 0 and 2*pi, in counter-clockwise direction. ## ## @seealso{lines2d, angles2d, createLine, normalizeAngle} ## @end deftypefn function theta = lineAngle(varargin) nargs = length(varargin); if nargs == 1 # angle of one line with horizontal line = varargin{1}; theta = mod(atan2(line(:,4), line(:,3)) + 2*pi, 2*pi); elseif nargs==2 # angle between two lines theta1 = lineAngle(varargin{1}); theta2 = lineAngle(varargin{2}); theta = mod(bsxfun(@minus, theta2, theta1)+2*pi, 2*pi); end endfunction # horizontal %!test %! line1 = createLine([2 3 1 0]); %! assert (lineAngle(line1), 0, 1e-6); %!test %! line1 = createLine([2 3 0 1]); %! assert (lineAngle(line1), pi/2, 1e-6); %!test %! line1 = createLine([2 3 1 1]); %! assert (lineAngle(line1), pi/4, 1e-6); %!test %! line1 = createLine([2 3 5 -1]); %! assert (lineAngle(line1), mod(atan2(-1, 5)+2*pi, 2*pi), 1e-6); %!test %! line1 = createLine([2 3 5000 -1000]); %! assert (lineAngle(line1), mod(atan2(-1, 5)+2*pi, 2*pi), 1e-6); %!test %! line1 = createLine([2 3 -1 0]); %! assert (lineAngle(line1), pi, 1e-6); # test lineAngle with two parameters : angle between 2 lines # check for 2 orthogonal lines %!test %! line1 = createLine([1 3 1 0]); %! line2 = createLine([-2 -1 0 1]); %! assert (lineAngle(line1, line2), pi/2, 1e-6); %! assert (lineAngle(line2, line1), 3*pi/2, 1e-6); # check for 2 orthogonal lines, with very different parametrizations %!test %! line1 = createLine([1 3 1 1]); %! line2 = createLine([-2 -1 -1000 1000]); %! assert (lineAngle(line1, line2), pi/2, 1e-6); %! assert (lineAngle(line2, line1), 3*pi/2, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/edgeToLine.m0000644000000000000000000000013213066736044017455 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/edgeToLine.m0000644000175000017500000000412413066736044017632 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line} = } edgeToLine (@var{edge}) ## Convert an edge to a straight line ## ## LINE = edgeToLine(EDGE); ## Returns the line containing the edge EDGE. ## ## Example ## edge = [2 3 4 5]; ## line = edgeToLine(edge); ## figure(1); hold on; axis([0 10 0 10]); ## drawLine(line, 'color', 'g') ## drawEdge(edge, 'linewidth', 2) ## ## @seealso{edges2d, lines2d} ## @end deftypefn function line = edgeToLine(edge) line = [edge(:, 1:2) edge(:, 3:4)-edge(:, 1:2)]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawPoint.m0000644000000000000000000000013213066736044017405 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawPoint.m0000644000175000017500000000577113066736044017573 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawPoint (@var{x}, @var{y}) ## @deftypefnx {Function File} {@var{h} = } drawPoint (@var{coord}) ## @deftypefnx {Function File} {@var{h} = } drawPoint (@dots{}, @var{opt}) ## Draw the point on the axis. # # Draws points defined by coordinates @var{x} and @var{y}. # @var{x} and @var{y} should be array the same size. Coordinates can be # packed coordinates in a single [N*2] array @var{coord}. Options @var{opt} # are passed to the @code{plot} function. # # @seealso{points2d, clipPoints} # ## @end deftypefn function varargout = drawPoint(varargin) # process input arguments var = varargin{1}; if size(var, 2)==1 # points stored in separate arrays px = varargin{1}; py = varargin{2}; varargin(1:2) = []; else # points packed in one array px = var(:, 1); py = var(:, 2); varargin(1) = []; end # ensure we have column vectors px = px(:); py = py(:); # default drawing options, but keep specified options if it has the form of # a bundled string if length(varargin)~=1 varargin = [{'linestyle', 'none', 'marker', 'o', 'color', 'b'}, varargin]; end # plot the points, using specified drawing options h = plot(px(:), py(:), varargin{:}); # process output arguments if nargout>0 varargout{1}=h; end endfunction %!demo %! drawPoint(10, 10); %!demo %! t = linspace(0, 2*pi, 20)'; %! drawPoint([5*cos(t)+10 3*sin(t)+10], 'r+'); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawCenteredEdge.m0000644000000000000000000000013213066736044020632 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawCenteredEdge.m0000644000175000017500000001065713066736044021017 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawCenteredEdge (@var{center}, @var{L}, @var{theta}) ## @deftypefnx {Function File} {@var{h} =} drawCenteredEdge (@var{edge}) ## @deftypefnx {Function File} {@var{h} =} drawCenteredEdge (@dots{}, @var{name},@var{value}) ## Draw an edge centered on a point. ## ## drawCenteredEdge(CENTER, L, THETA) ## Draws an edge centered on point CENTER, with length L, and orientation ## THETA (given in degrees). Input arguments can also be arrays, that must ## all have the same number odf rows. ## ## drawCenteredEdge(EDGE) ## Concatenates edge parameters into a single N-by-4 array, containing: ## [XC YV L THETA]. ## ## drawCenteredEdge(..., NAME, VALUE) ## Also specifies drawing options by using one or several parameter name - ## value pairs (see doc of plot function for details). ## ## H = drawCenteredEdge(...) ## Returns handle(s) to the created edges(s). ## ## @example ## # Draw an ellipse with its two axes ## figure(1); clf; ## center = [50 40]; ## r1 = 30; r2 = 10; ## theta = 20; ## elli = [center r1 r2 theta]; ## drawEllipse(elli, 'linewidth', 2); ## axis([0 100 0 100]); axis equal; ## hold on; ## edges = [center 2*r1 theta ; center 2*r2 theta+90]; ## drawCenteredEdge(edges, 'linewidth', 2, 'color', 'g'); ## @end example ## ## @seealso{edges2d, drawEdge} ## @end deftypefn function varargout = drawCenteredEdge(center, len, theta, varargin) ## process input variables if size(center, 2) == 4 # manage edge in single parameter varargin = [{len, theta}, varargin]; len = center(:, 3); theta = center(:, 4); center = center(:, 1:2); N = size(center, 1); else # parameters given in different arguments # size of data NP = size(center, 1); NL = size(len, 1); ND = size(theta, 1); N = max([NP NL ND]); # ensure all data have same size if N > 1 if NP == 1, center = repmat(center, [N 1]); end if NL == 1, len = repmat(len, [N 1]); end if ND == 1, theta = repmat(theta, [N 1]); end end end # extract drawing options options = varargin(:); ## Draw edges # coordinates of center point xc = center(:, 1); yc = center(:, 2); # convert angle to radians theta = theta * pi / 180; # computation shortcuts cot = cos(theta); sit = sin(theta); # compute starting and ending points x1 = xc - len .* cot / 2; x2 = xc + len .* cot / 2; y1 = yc - len .* sit / 2; y2 = yc + len .* sit / 2; # draw the edges h = zeros(N, 1); for i = 1:N h(i) = plot([x1(i) x2(i)], [y1(i) y2(i)]); end # apply style to edges if ~isempty(options) > 0 for i = 1:N set(h(i), options{:}); end end ## Format output # process output arguments if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/edgePosition.m0000644000000000000000000000013213066736044020067 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/edgePosition.m0000644000175000017500000000661113066736044020247 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{d} = } edgePosition (@var{point}, @var{edge}) ## Return position of a point on an edge ## ## POS = edgePosition(POINT, EDGE); ## Computes position of point POINT on the edge EDGE, relative to the ## position of edge vertices. ## EDGE has the form [x1 y1 x2 y2], ## POINT has the form [x y], and is assumed to belong to edge. ## The result POS has the following meaning: ## POS < 0: POINT is located before the first vertex ## POS = 0: POINT is located on the first vertex ## 0 < POS < 1: POINT is located between the 2 vertices (on the edge) ## POS = 1: POINT is located on the second vertex ## POS < 0: POINT is located after the second vertex ## ## POS = edgePosition(POINT, EDGES); ## If EDGES is an array of NL edges, return NE positions, corresponding to ## each edge. ## ## POS = edgePosition(POINTS, EDGE); ## If POINTS is an array of NP points, return NP positions, corresponding ## to each point. ## ## POS = edgePosition(POINTS, EDGES); ## If POINTS is an array of NP points and EDGES is an array of NE edges, ## return an array of [NP NE] position, corresponding to each couple ## point-edge. ## ## @seealso{edges2d, createEdge, onEdge} ## @end deftypefn function pos = edgePosition(point, edge) nEdges = size (edge, 1); nPoints = size (point, 1); if nPoints == nEdges dxe = (edge(:, 3) - edge(:,1))'; dye = (edge(:, 4) - edge(:,2))'; dxp = point(:, 1) - edge(:, 1); dyp = point(:, 2) - edge(:, 2); else % expand one of the arrays to have the same size dxe = (edge(:,3) - edge(:,1))'; dye = (edge(:,4) - edge(:,2))'; dxp = bsxfun (@minus, point(:,1), edge(:,1)'); dyp = bsxfun (@minus, point(:,2), edge(:,2)'); end pos = (dxp .* dxe + dyp .* dye) ./ (dxe .* dxe + dye .* dye); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawLine.m0000644000000000000000000000013213066736044017203 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawLine.m0000644000175000017500000001470613066736044017367 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} drawLine (@var{line}) ## @deftypefnx {Function File} {@var{h} =} drawLine (@var{line}, @var{param},@var{value}) ## Draw the line on the current axis. ## ## Draws the line LINE on the current axis, by using current axis to clip ## the line. Extra @var{param},@var{value} pairs are passed to the @code{line} function. ## Returns a handle to the created line object. If clipped line is not ## contained in the axis, the function returns -1. ## ## Example ## ## @example ## figure; hold on; axis equal; ## axis([0 100 0 100]); ## drawLine([30 40 10 20]); ## drawLine([30 40 20 -10], 'color', 'm', 'linewidth', 2); ## @end example ## ## @seealso{lines2d, createLine, drawEdge} ## @end deftypefn function varargout = drawLine(lin, varargin) # default style for drawing lines varargin = [{'color', 'b'}, varargin]; # extract bounding box of the current axis xlim = get(gca, 'xlim'); ylim = get(gca, 'ylim'); # clip lines with current axis box clip = clipLine(lin, [xlim ylim]); ok = isfinite(clip(:,1)); # initialize result array to invalide handles h = -1*ones(size(lin, 1), 1); # draw valid lines h(ok) = line(clip(ok, [1 3])', clip(ok, [2 4])', varargin{:}); # return line handle if needed if nargout>0 varargout{1}=h; end endfunction %!demo %! figure; hold on; axis equal; %! axis([0 100 0 100]); %! drawLine([30 40 10 20]); %! drawLine([30 40 20 -10], 'color', 'm', 'linewidth', 2); %!shared privpath %! privpath = [fileparts(which('geom2d_Contents')) filesep() 'private']; %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [30 40 10 0]; %! edge = [0 40 100 40]; %! hl = drawLine(line); %! assertElementsAlmostEqual(edge([1 3]), get(hl, 'xdata')); %! assertElementsAlmostEqual(edge([2 4]), get(hl, 'ydata')); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [30 40 -10 0]; %! edge = [100 40 0 40]; %! hl = drawLine(line); %! assertElementsAlmostEqual(edge([1 3]), get(hl, 'xdata')); %! assertElementsAlmostEqual(edge([2 4]), get(hl, 'ydata')); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [30 140 10 0]; %! hl = drawLine(line); %! assertEqual(-1, hl); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [30 40 0 10]; %! edge = [30 0 30 100]; %! hl = drawLine(line); %! assertElementsAlmostEqual(edge([1 3]), get(hl, 'xdata')); %! assertElementsAlmostEqual(edge([2 4]), get(hl, 'ydata')); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [30 40 0 -10]; %! edge = [30 100 30 0]; %! hl = drawLine(line); %! assertElementsAlmostEqual(edge([1 3]), get(hl, 'xdata')); %! assertElementsAlmostEqual(edge([2 4]), get(hl, 'ydata')); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [140 30 0 10]; %! hl = drawLine(line); %! assertEqual(-1, hl); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [80 30 10 10]; %! edge = [50 0 100 50]; %! hl = drawLine(line); %! assertElementsAlmostEqual(edge([1 3]), get(hl, 'xdata')); %! assertElementsAlmostEqual(edge([2 4]), get(hl, 'ydata')); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [20 70 10 10]; %! edge = [0 50 50 100]; %! hl = drawLine(line); %! assertElementsAlmostEqual(edge([1 3]), get(hl, 'xdata')); %! assertElementsAlmostEqual(edge([2 4]), get(hl, 'ydata')); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [140 -30 10 10]; %! hl = drawLine(line); %! assertEqual(-1, hl); %! line = [-40 130 10 10]; %! hl = drawLine(line); %! assertEqual(-1, hl); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! box = [0 100 0 100]; %! hf = figure('visible','off'); %! axis(box); %! line = [... %! 80 30 10 10; ... %! 20 70 10 10; ... %! 140 -30 10 10; ... %! -40 130 10 10]; %! edge = [... %! 50 0 100 50; ... %! 0 50 50 100]; %! hl = drawLine(line); %! assertEqual(4, length(hl)); %! assertElementsAlmostEqual(edge(1, [1 3]), get(hl(1), 'xdata')); %! assertElementsAlmostEqual(edge(1, [2 4]), get(hl(1), 'ydata')); %! assertElementsAlmostEqual(edge(2, [1 3]), get(hl(2), 'xdata')); %! assertElementsAlmostEqual(edge(2, [2 4]), get(hl(2), 'ydata')); %! assertEqual(-1, hl(3)); %! assertEqual(-1, hl(4)); %! rmpath (privpath); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/triangleGrid.m0000644000000000000000000000013213066736044020051 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/triangleGrid.m0000644000175000017500000000474613066736044020240 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pts} = } triangleGrid (@var{bounds}, @var{origin}, @var{size}) ## Generate triangular grid of points in the plane. ## ## usage ## PTS = triangleGrid(BOUNDS, ORIGIN, SIZE) ## generate points, lying in the window defined by BOUNDS, given in form ## [xmin ymin xmax ymax], starting from origin with a constant step equal ## to size. ## SIZE is constant and is equals to the length of the sides of each ## triangles. ## ## TODO: add possibility to use rotated grid ## ## @end deftypefn function varargout = triangleGrid(bounds, origin, size, varargin) dx = size(1); dy = size(1)*sqrt(3); # consider two square grids with different centers pts1 = squareGrid(bounds, origin, [dx dy], varargin{:}); pts2 = squareGrid(bounds, origin + [dx dy]/2, [dx dy], varargin{:}); # gather points pts = [pts1;pts2]; # process output if nargout>0 varargout{1} = pts; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createScaling.m0000644000000000000000000000013213066736044020202 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createScaling.m0000644000175000017500000000667513066736044020374 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } createScaling (@var{s}) ## @deftypefnx {Function File} {@var{T} = } createScaling (@var{sx}, @var{sy}) ## Create the 3x3 matrix of a scaling in 2 dimensions. # # Assume scaling @var{s} is equal n all directions unless @var{sx} and @var{sy} are given. # Returns the matrix corresponding to scaling in the 2 main directions. # The returned matrix has the form: # [SX 0 0] # [0 SY 0] # [0 0 1] # # @seealso{transforms2d, transformPoint, createTranslation, createRotation} ## @end deftypefn function trans = createScaling(varargin) # defined default arguments sx = 1; sy = 1; cx = 0; cy = 0; # process input arguments if length(varargin)==1 # the argument is either the scaling factor in both direction, # or a 1x2 array containing scaling factor in each direction var = varargin{1}; sx = var(1); sy = var(1); if length(var)>1 sy = var(2); end elseif length(varargin)==2 # the 2 arguments are the scaling factors in each dimension sx = varargin{1}; sy = varargin{2}; elseif length(varargin)==3 # first argument is center, 2nd and 3d are scaling factors center = varargin{1}; cx = center(1); cy = center(2); sx = varargin{2}; sy = varargin{3}; end # create result matrix trans = [sx 0 cx*(1-sx); 0 sy cy*(1-sy); 0 0 1]; endfunction %!test %! trans = createScaling(2); %! assert (trans, [2 0 0;0 2 0;0 0 1], 1e-6); %!test %! trans = createScaling(2, 3); %! assert (trans, [2 0 0;0 3 0;0 0 1], 1e-6); %!test %! trans = createScaling([2 3]); %! assert (trans, [2 0 0;0 3 0;0 0 1], 1e-6); %!test %! sx = 2; %! sy = 3; %! p0 = [4 5]; %! trans1 = createScaling(p0, sx, sy); %! t1 = createTranslation(-p0); %! sca = createScaling(sx, sy); %! t2 = createTranslation(p0); %! trans2 = t2*sca*t1; %! assert (trans1, trans2, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/angleAbsDiff.m0000644000000000000000000000013213066736044017743 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/angleAbsDiff.m0000644000175000017500000000460313066736044020122 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dif} =} angleAbsDiff (@var{angle1}, @var{angle2}) ## Computes the absolute angular difference between two angles in radians. ## The result is comprised between 0 and pi. ## ## @example ## A = angleAbsDiff(pi/2, pi/3) ## A = ## 0.5236 # equal to pi/6 ## @end example ## ## @seealso{angles2d, angleDiff} ## @end deftypefn function dif = angleAbsDiff(angle1, angle2) # first, normalization angle1 = normalizeAngle(angle1); angle2 = normalizeAngle(angle2); # compute difference and normalize dif = normalizeAngle(angle1 - angle2); dif = min(dif, 2*pi - dif); endfunction %!shared xp %! xp = pi/2; %!assert (xp, angleAbsDiff (pi/2, 0), 1e-6); %!assert (xp, angleAbsDiff (0, pi/2), 1e-6); %!assert (xp, angleAbsDiff (0, 3*pi/2), 1e-6); %!assert (xp, angleAbsDiff (3*pi/2, 0), 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/radicalAxis.m0000644000000000000000000000013213066736044017662 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/radicalAxis.m0000644000175000017500000000553713066736044020050 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line} = } radicalAxis (@var{circle1}, @var{circle2}) ## Compute the radical axis (or radical line) of 2 circles ## ## L = radicalAxis(C1, C2) ## Computes the radical axis of 2 circles. ## ## Example ## C1 = [10 10 5]; ## C2 = [60 50 30]; ## L = radicalAxis(C1, C2); ## hold on; axis equal;axis([0 100 0 100]); ## drawCircle(C1);drawCircle(C2);drawLine(L); ## ## Ref: ## http://mathworld.wolfram.com/RadicalLine.html ## http://en.wikipedia.org/wiki/Radical_axis ## ## @seealso{lines2d, circles2d, createCircle} ## ## @end deftypefn function line = radicalAxis(circle1, circle2) # extract circles parameters x1 = circle1(:,1); x2 = circle2(:,1); y1 = circle1(:,2); y2 = circle2(:,2); r1 = circle1(:,3); r2 = circle2(:,3); # distance between each couple of centers dist = sqrt((x2-x1).^2 + (y2-y1).^2); # relative position of intersection point of # the radical line with the line joining circle centers d = (dist.^2 + r1.^2 - r2.^2) * .5 ./ dist; # compute angle of radical axis angle = lineAngle(createLine([x1 y1], [x2 y2])); cot = cos(angle); sit = sin(angle); # parameters of the line x0 = x1 + d*cot; y0 = y1 + d*sit; dx = -sit; dy = cot; # concatenate into one structure line = [x0 y0 dx dy]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/fitAffineTransform2d.m0000644000000000000000000000013213066736044021453 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/fitAffineTransform2d.m0000644000175000017500000000464313066736044021636 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } fitAffineTransform2d (@var{pts1}, @var{pts2}) ## Fit an affine transform using two point sets. ## ## Example ## ## @example ## N = 10; ## pts = rand(N, 2)*10; ## trans = createRotation(3, 4, pi/4); ## pts2 = transformPoint(pts, trans); ## pts3 = pts2 + randn(N, 2)*2; ## fitted = fitAffineTransform2d(pts, pts2) ##@end example ## ## @seealso{transforms2d} ## @end deftypefn function trans = fitAffineTransform2d(pts1, pts2) # number of points N = size(pts1, 1); # main matrix of the problem A = [... pts1(:,1) pts1(:,2) ones(N,1) zeros(N, 3) ; ... zeros(N, 3) pts1(:,1) pts1(:,2) ones(N,1) ]; # conditions initialisations B = [pts2(:,1) ; pts2(:,2)]; # compute coefficients using least square coefs = A\B; # format to a matrix trans = [coefs(1:3)' ; coefs(4:6)'; 0 0 1]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawParabola.m0000644000000000000000000000013213066736044020035 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawParabola.m0000644000175000017500000001155213066736044020215 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawParabola (@var{parabola}) ## @deftypefnx {Function File} {@var{h} = } drawParabola (@var{parabola}, @var{t}) ## @deftypefnx {Function File} {@var{h} = } drawParabola (@dots{}, @var{param}, @var{value}) ## Draw a parabola on the current axis. ## ## drawParabola(PARABOLA); ## Draws a vertical parabola, defined by its vertex and its parameter. ## Such a parabola admits a vertical axis of symetry. ## ## The algebraic equation of parabola is given by: ## (Y - YV) = A * (X - VX)^2 ## Where XV and YV are vertex coordinates and A is parabola parameter. ## ## A parametric equation of parabola is given by: ## x(t) = t + VX; ## y(t) = A * t^2 + VY; ## ## PARABOLA can also be defined by [XV YV A THETA], with theta being the ## angle of rotation of the parabola (in degrees and Counter-Clockwise). ## ## drawParabola(PARABOLA, T); ## Specifies which range of 't' are used for drawing parabola. If T is an ## array with only two values, the first and the last values are used as ## interval bounds, and several values are distributed within this ## interval. ## ## drawParabola(..., NAME, VALUE); ## Can specify one or several graphical options using parameter name-value ## pairs. ## ## H = drawParabola(...); ## Returns an handle to the created graphical object. ## ## ## Example: ## @example ## figure(1); clf; hold on; ## axis equal; axis([0 100 0 100]) ## % draw parabola with default parameterization bounds ## drawParabola([50 50 .2 30]); ## % draw parabola with more specific bounds and drawing style ## drawParabola([50 50 .2 30], [-3 3], 'color', 'r', 'linewidth', 2); ## @end example ## ## @seealso{drawCircle, drawEllipse} ## @end deftypefn function varargout = drawParabola(varargin) # Extract parabola if nargin<1 error('geom2d:IllegalArgument', ... 'Please specify parabola representation'); end # input parabola is given as a packed array parabola = varargin{1}; varargin(1) = []; x0 = parabola(:,1); y0 = parabola(:,2); a = parabola(:,3); if size(parabola, 2)>3 theta = parabola(:, 4); else theta = zeros(length(a), 1); end # extract parametrisation bounds bounds = [-100 100]; if ~isempty(varargin) var = varargin{1}; if isnumeric(var) bounds = var; varargin(1) = []; end end # create parametrisation if length(bounds)>2 t = bounds; else t = linspace(bounds(1), bounds(end), 100); end # create handle array (in the case of several parabola) h = zeros(size(x0)); # draw each parabola for i=1:length(x0) # compute transformation trans = ... createTranslation(x0(i), y0(i)) * ... createRotation(deg2rad(theta(i))) * ... createScaling(1, a); # compute points on the parabola [xt yt] = transformPoint(t(:), t(:).^2, trans); # draw it h(i) = plot(xt, yt, varargin{:}); end # process output arguments if nargout>0 varargout{1}=h; end endfunction %!demo %! figure(1); clf; hold on; %! axis equal; axis([0 100 0 100]) %! % draw parabola with default parameterization bounds %! drawParabola([50 50 .2 30]); %! % draw parabola with more specific bounds and drawing style %! drawParabola([50 50 .2 30], [-3 3], 'color', 'r', 'linewidth', 2); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/linePosition.m0000644000000000000000000000013213066736044020112 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/linePosition.m0000644000175000017500000001053213066736044020267 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pos} =} linePosition (@var{point}, @var{line}) ## Position of a point on a line. ## ## Computes position of point @var{point} on the line @var{line}, relative to origin ## point and direction vector of the line. ## @var{line} has the form [x0 y0 dx dy], ## @var{point} has the form [x y], and is assumed to belong to line. ## ## If @var{line} is an array of NL lines, return NL positions, corresponding to ## each line. ## ## If @var{point} is an array of NP points, return NP positions, corresponding ## to each point. ## ## If @var{point} is an array of NP points and @var{line}S is an array of NL lines, ## return an array of [NP NL] position, corresponding to each couple ## point-line. ## ## Example ## ## @example ## line = createLine([10 30], [30 90]); ## linePosition([20 60], line) ## ans = ## .5 ## @end example ## ## @seealso{lines2d, createLine, projPointOnLine, isPointOnLine} ## @end deftypefn function d = linePosition(point, lin) # number of inputs Nl = size(lin, 1); Np = size(point, 1); if Np == Nl # if both inputs have the same size, no problem dxl = lin(:, 3); dyl = lin(:, 4); dxp = point(:, 1) - lin(:, 1); dyp = point(:, 2) - lin(:, 2); elseif Np == 1 # one point, several lines dxl = lin(:, 3); dyl = lin(:, 4); dxp = point(ones(Nl, 1), 1) - lin(:, 1); dyp = point(ones(Nl, 1), 2) - lin(:, 2); elseif Nl == 1 # one lin, several points dxl = lin(ones(Np, 1), 3); dyl = lin(ones(Np, 1), 4); dxp = point(:, 1) - lin(1); dyp = point(:, 2) - lin(2); else # expand one of the array to have the same size dxl = repmat(lin(:,3)', Np, 1); dyl = repmat(lin(:,4)', Np, 1); dxp = repmat(point(:,1), 1, Nl) - repmat(lin(:,1)', Np, 1); dyp = repmat(point(:,2), 1, Nl) - repmat(lin(:,2)', Np, 1); end # compute position d = (dxp.*dxl + dyp.*dyl) ./ (dxl.^2 + dyl.^2); endfunction %!demo %! point = [20 60;10 30;25 75]; %! lin = createLine([10 30], [30 90]); %! pos = linePosition(point, lin) %! %! plot(point(:,1),point(:,2),'ok'); %! hold on %! drawLine(lin,'color','r'); %! plot(lin(1)+lin(3)*pos,lin(2)+lin(4)*pos,'xb') %! hold off %!test %! point = [20 60]; %! lin = createLine([10 30], [30 90]); %! res = .5; %! pos = linePosition(point, lin); %! assert (res, pos); %!test %! point = [20 60;10 30;25 75]; %! lin = createLine([10 30], [30 90]); %! res = [.5; 0; .75]; %! pos = linePosition(point, lin); %! assert (res, pos); %!test %! point = [20 60]; %! lin1 = createLine([10 30], [30 90]); %! lin2 = createLine([0 0], [20 60]); %! lin3 = createLine([20 60], [40 120]); %! lines = [lin1;lin2;lin3]; %! res = [.5; 1; 0]; %! pos = linePosition(point, lines); %! assert (res, pos); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/cartesianLine.m0000644000000000000000000000013213066736044020217 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/cartesianLine.m0000644000175000017500000000442613066736044020401 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{line} = } cartesianLine (@var{A}, @var{B},@var{C}) ## Create a straight line from cartesian equation coefficients. ## ## Create a line verifying the Cartesian equation: ## @var{A}*x + @var{B}*x + @var{C} = 0; ## ## @seealso{lines2d, createLine} ## @end deftypefn function line = cartesianLine(varargin) if length(varargin)==1 var = varargin{1}; a = var(:,1); b = var(:,2); c = var(:,3); elseif length(varargin)==3 a = varargin{1}; b = varargin{2}; c = varargin{3}; end # normalisation factor d = a.*a + b.*b; x0 = -a.*c./d; y0 = -b.*c./d; theta = atan2(-a, b); dx = cos(theta); dy = sin(theta); line = [x0 y0 dx dy]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createCircle.m0000644000000000000000000000013213066736044020023 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createCircle.m0000644000175000017500000001016113066736044020176 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{circle} = } createCircle (@var{p1}, @var{p2}, @var{p3}) ## @deftypefnx {Function File} {@var{circle} = } createCircle (@var{p1}, @var{p2}) ## Create a circle from 2 or 3 points. ## ## Creates the circle passing through the 3 given points. ## C is a 1x3 array of the form: [XC YX R]. ## ## When two points are given, creates the circle whith center @var{p1} and passing ## throuh the point @var{p2}. ## ## Works also when input are point arrays the same size, in this case the ## result has as many lines as the point arrays. ## ## Example ## ## @example ## # Draw a circle passing through 3 points. ## p1 = [10 15]; ## p2 = [15 20]; ## p3 = [10 25]; ## circle = createCircle(p1, p2, p3); ## figure; hold on; axis equal; axis([0 50 0 50]); ## drawPoint([p1 ; p2; p3]); ## drawCircle(circle); ## @end example ## ## @seealso{circles2d, createDirectedCircle} ## @end deftypefn function circle = createCircle(varargin) if nargin == 2 # inputs are the center and a point on the circle p1 = varargin{1}; p2 = varargin{2}; x0 = p1(:,1); y0 = p1(:,2); r = hypot((p2(:,1)-x0), (p2(:,2)-y0)); elseif nargin == 3 # inputs are three points on the circle p1 = varargin{1}; p2 = varargin{2}; p3 = varargin{3}; # compute circle center line1 = medianLine(p1, p2); line2 = medianLine(p1, p3); point = intersectLines(line1, line2); x0 = point(:, 1); y0 = point(:, 2); # circle radius r = hypot((p1(:,1)-x0), (p1(:,2)-y0)); end # create array for returning result circle = [x0 y0 r]; endfunction %!shared privpath %! privpath = [fileparts(which('geom2d_Contents')) filesep() 'private']; %!test %! addpath (privpath,'-end') %! p1 = [10 15]; %! p2 = [15 20]; %! p3 = [10 25]; %! exp = [10 20 5]; %! circle = createCircle(p1, p2, p3); %! assertEqual(exp, circle); %! circle = createCircle(p3, p1, p2); %! assertEqual(exp, circle); %! circle = createCircle(p2, p3, p1); %! assertEqual(exp, circle); %! rmpath (privpath); %!test %! addpath (privpath,'-end') %! p1 = [10 15]; %! p2 = [15 20]; %! p3 = [10 25]; %! exp = [10 20 5]; %! p1 = [p1; p1+10; p1+20; p1-5]; %! p2 = [p2; p2+10; p2+20; p2-5]; %! p3 = [p3; p3+10; p3+20; p3-5]; %! exp = repmat(exp, 4, 1) + [0 0 0;10 10 0;20 20 0;-5 -5 0]; %! circle = createCircle(p1, p2, p3); %! assertEqual(exp, circle); %! circle = createCircle(p3, p1, p2); %! assertEqual(exp, circle); %! circle = createCircle(p2, p3, p1); %! assertEqual(exp, circle); %! rmpath (privpath); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawBezierCurve.m0000644000000000000000000000013213066736044020541 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawBezierCurve.m0000644000175000017500000000777313066736044020733 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawBezierCurve (@var{points}) ## @deftypefnx {Function File} drawBezierCurve (@var{pp}) ## @deftypefnx {Function File} drawBezierCurve (@dots{}, @var{param}, @var{value}, @dots{}) ## @deftypefnx {Function File} {@var{h} =}drawBezierCurve (@dots{}) ## Draw a cubic bezier curve defined by the control points @var{points}. ## ## With only one input argument, draws the Bezier curve defined by the 4 control ## points stored in @var{points}. @var{points} is either a 4-by-2 array ## (vertical concatenation of point coordinates), or a 1-by-8 array (horizotnal ## concatenation of point coordinates). The curve could be described by its ## polynomial (output of @code{cbezier2poly}) @var{pp}, which should be a 2-by-4 ## array. ## ## The optional @var{param}, @var{value} pairs specify additional drawing ## parameters, see the @code{plot} function for details. The specific parameter ## 'discretization' with an integer associated value defines the amount of ## points used to plot the curve. If the output is requiered, the function ## returns the handle to the created graphic object. ## ## @seealso{cbezier2poly, plot} ## @end deftypefn function varargout = drawBezierCurve(points, varargin) # default number of discretization steps N = 64; # check if discretization step is specified if ~isempty(varargin) [tf idx] = ismember ({'discretization'},{varargin{1:2:end}}); if ~isempty(idx) N = varargin{idx+1}; varargin(idx:idx+1) = []; end end # parametrization variable for bezier (use N+1 points to have N edges) t = linspace(0, 1, N+1); if any(size(points) ~= [2 4]) [x y] = cbezier2poly(points,t); else # Got a polynomial description x = polyval(points(1,:),t); y = polyval(points(2,:),t); end # draw the curve h = plot(x, y, varargin{:}); # eventually return a handle to the created object if nargout > 0 varargout = {h}; end endfunction %!demo %! points = [0 0; 3 1; -2 1; 1 0]; %! drawBezierCurve(points); %! hold on %! plot(points([1 4],1),points([1 4],2),'go'); %! plot(points([2 3],1),points([2 3],2),'rs'); %! line(points([1 2],1),points([1 2],2),'color','k'); %! line(points([3 4],1),points([3 4],2),'color','k'); %! h = drawBezierCurve(points, 'discretization', 6, 'color','r'); %! hold off %!shared p %! p = [0 0; 3 1; -2 1; 1 0]; %!error(drawBezier()) %!error(drawBezier ('discretization')) %!error(drawBezier (p, 'discretization', 'a')) %!error(drawBezier (p(:))) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createHomothecy.m0000644000000000000000000000013213066736044020561 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createHomothecy.m0000644000175000017500000000426413066736044020743 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } createHomothecy (@var{point}, @var{ratio}) ## Create the the 3x3 matrix of an homothetic transform. # # @var{point} is the center of the homothecy, @var{ratio} is its factor. # # @seealso{transforms2d, transformPoint, createTranslation} ## @end deftypefn function trans = createHomothecy(point, ratio) # extract coordinate of center x0 = point(:,1); y0 = point(:,2); # compute coefficients of the matrix m00 = ratio; m01 = 0; m02 = x0*(1-ratio); m10 = 0; m11 = ratio; m12 = y0*(1-ratio); # create transformation trans = [m00 m01 m02; m10 m11 m12; 0 0 1]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/clipRay.m0000644000000000000000000000013213066736044017041 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/clipRay.m0000644000175000017500000001325013066736044017216 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{edge} @var{inside}] =} clipRay (@var{ray}, @var{box}) ## Clip a ray with a box. ## ## @var{ray} is a straight ray given as a 4 element row vector: [x0 y0 dx dy], ## with (x0 y0) being the origin of the ray and (dx dy) its direction ## vector, @var{box} is the clipping box, given by its extreme coordinates: ## [xmin xmax ymin ymax]. ## The result is given as an edge, defined by the coordinates of its 2 ## extreme points: [x1 y1 x2 y2]. ## If the ray does not intersect the box, [NaN NaN NaN NaN] is returned. ## ## Function works also if @var{ray} is a Nx4 array, if @var{box} is a Nx4 array, or ## if both @var{ray} and @var{box} are Nx4 arrays. In these cases, @var{edge} is a Nx4 ## array. ## ## @seealso{rays2d, boxes2d, edges2d, clipLine, drawRay} ## @end deftypefn function [edge isInside] = clipRay(ray, bb) # adjust size of two input arguments if size(ray, 1)==1 ray = repmat(ray, size(bb, 1), 1); elseif size(bb, 1)==1 bb = repmat(bb, size(ray, 1), 1); elseif size(ray, 1) != size(bb, 1) error('bad sizes for input'); end # first compute clipping of supporting line edge = clipLine(ray, bb); # detectes valid edges (edges outside box are all NaN) inds = find(isfinite(edge(:, 1))); # compute position of edge extremities relative to the ray pos1 = linePosition(edge(inds,1:2), ray(inds,:)); pos2 = linePosition(edge(inds,3:4), ray(inds,:)); # if first point is before ray origin, replace by origin edge(inds(pos1<0), 1:2) = ray(inds(pos1<0), 1:2); # if last point of edge is before origin, set all edge to NaN edge(inds(pos2<0), :) = NaN; # eventually returns result about inside or outside if nargout>1 isInside = isfinite(edge(:,1)); end endfunction %!shared bb %! bb = [0 100 0 100]; %!test # inside %! origin = [30 40]; %! direction = [10 0]; %! ray = [origin direction]; %! expected = [30 40 100 40]; %! assert (expected, clipRay(ray, bb), 1e-6); %!test # outside %! origin = [30 140]; %! direction = [10 0]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # line inside, but ray outside %! origin = [130 40]; %! direction = [10 0]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # inside %! origin = [30 40]; %! direction = [-10 0]; %! ray = [origin direction]; %! expected = [30 40 0 40]; %! assert (expected, clipRay(ray, bb), 1e-6); %!test # outside %! origin = [30 140]; %! direction = [-10 0]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # line inside, but ray outside %! origin = [-30 40]; %! direction = [-10 0]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # inside %! origin = [30 40]; %! direction = [0 10]; %! ray = [origin direction]; %! expected = [30 40 30 100]; %! assert (expected, clipRay(ray, bb), 1e-6); %!test # outside %! origin = [130 40]; %! direction = [0 10]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # line inside, but ray outside %! origin = [30 140]; %! direction = [0 10]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # inside %! origin = [30 40]; %! direction = [0 -10]; %! ray = [origin direction]; %! expected = [30 40 30 0]; %! assert (expected, clipRay(ray, bb), 1e-6); %!test # outside %! origin = [130 40]; %! direction = [0 -10]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test # line inside, but ray outside %! origin = [30 -40]; %! direction = [0 -10]; %! ray = [origin direction]; %! assert (sum(isnan(clipRay(ray, bb)))==4); %!test %! origins = [30 40;30 40;30 140;130 40]; %! directions = [10 0;0 10;10 0;0 10]; %! rays = [origins directions]; %! expected = [30 40 100 40;30 40 30 100;NaN NaN NaN NaN;NaN NaN NaN NaN]; %! clipped = clipRay(rays, bb); %! assert (expected, clipped, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawShape.m0000644000000000000000000000013213066736044017354 xustar0030 mtime=1490795556.584869322 30 atime=1490795556.584869322 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawShape.m0000644000175000017500000000723413066736044017536 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012-2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawShape (@var{type}, @var{param}) ## @deftypefnx {Function File} drawShape (@dots{}, @var{option}) ## Draw various types of shapes (circles, polygons...). ## ## Draw the shape of type @var{type}, specified by given parameter @var{param}. ## @var{type} can be one of 'circle', 'ellipse', 'rect', 'polygon', 'curve' ## @var{param} depend on the type. For example, if @var{type} is 'circle', ## @var{param} will contain [x0 y0 R]. ## ## If @var{option} is 'fill', the shape will be filled. ## ## Examples : ## @example ## drawShape('circle', [20 10 30]); ## Draw circle centered on [20 10] with radius 10. ## drawShape('rect', [20 20 40 10 pi/3],'fill'); ## Draw rectangle centered on [20 20] with length 40 and width 10, and ## oriented pi/3 wrt axis Ox. ## @end example ## ## @end deftypefn function varargout = drawShape(type, param, option='draw') if ~iscell (type) type = {type}; end if ~iscell (param) tmp = cell (1, size (param, 1)); for i = 1:size (param, 1) tmp{i} = param(i,:); end param = tmp; end # transform each shape into a polygon shape = cell (1,length (type)); for i = 1:length (type) if strcmpi (type{i}, 'circle') shape{i} = circleAsPolygon (param{i}, 128); elseif strcmpi (type{i}, 'rect') shape{i} = rectAsPolygon (param{i}); elseif strcmpi (type{i}, 'polygon') shape{i} = param{i}; end end holded = false; if ~ishold (gca) hold on; holded = true; end h = zeros (length (shape), 1); if strcmp (option, 'draw') for i = 1:length (shape) h(i) = drawPolygon (shape{i}); end else for i = 1:length (shape) h(i) = fillPolygon (shape{i}); end end if holded hold off end if nargout>0 varargout{1}=h; end endfunction %!demo %! ## Draw circle centered on [20 10] with radius 10. %! drawShape ('circle', [20 10 30]); %! hold on %! ## Draw rectangle centered on [20 20] with length 40 and width 10, and %! ## oriented pi/3 wrt axis Ox. %! drawShape ('rect', [20 20 40 10 pi/3], "fill"); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createVector.m0000644000000000000000000000013213066736044020064 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createVector.m0000644000175000017500000000434113066736044020242 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{vect} = } createVector (@var{p1}, @var{p2}) ## Create a vector from two points. ## ## V12 = createVector(P1, P2) ## Creates the vector V12, defined as the difference between coordinates ## of points P1 and P2. ## P1 and P2 are row vectors with ND elements, ND being the space ## dimension. ## ## If one of the inputs is a N-by-Nd array, the other input is ## automatically repeated, and the result is N-by-Nd. ## ## If both inputs have the same size, the result also have the same size. ## ## @seealso{vectors2d, vectors3d, points2d} ## @end deftypefn function vect = createVector(p1, p2) vect = bsxfun(@minus, p2, p1); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawLabels.m0000644000000000000000000000013213066736044017516 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawLabels.m0000644000175000017500000000673113066736044017701 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawLabels (@var{x}, @var{y}, @var{lbl}) ## @deftypefnx {Function File} drawLabels (@var{pos}, @var{lbl}) ## @deftypefnx {Function File} drawLabels (@dots{}, @var{numbers}, @var{format}) ## Draw labels at specified positions. ## ## DRAWLABELS(X, Y, LBL) draw labels LBL at position X and Y. ## LBL can be either a string array, or a number array. In this case, ## string are created by using sprintf function, with '#.2f' mask. ## ## DRAWLABELS(POS, LBL) draw labels LBL at position specified by POS, ## where POS is a N*2 int array. ## ## DRAWLABELS(..., NUMBERS, FORMAT) create labels using sprintf function, ## with the mask given by FORMAT (e. g. '#03d' or '5.3f'), and the ## corresponding values. ## @end deftypefn function varargout = drawLabels(varargin) # check if enough inputs are given if isempty(varargin) error('wrong number of arguments in drawLabels'); end # process input parameters var = varargin{1}; if size(var, 2)==1 if length(varargin)<3 error('wrong number of arguments in drawLabels'); end px = var; py = varargin{2}; lbl = varargin{3}; varargin(1:3) = []; else if length(varargin)<2 error('wrong number of arguments in drawLabels'); end px = var(:,1); py = var(:,2); lbl = varargin{2}; varargin(1:2) = []; end format = '%.2f'; if ~isempty(varargin) format = varargin{1}; end if size(format, 1)==1 && size(px, 1)>1 format = repmat(format, size(px, 1), 1); end labels = cell(length(px), 1); if isnumeric(lbl) for i=1:length(px) labels{i} = sprintf(format(i,:), lbl(i)); end elseif ischar(lbl) for i=1:length(px) labels{i} = lbl(i,:); end elseif iscell(lbl) labels = lbl; end labels = char(labels); h = text(px, py, labels); if nargout>0 varargout{1}=h; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/angles2d.m0000644000000000000000000000013213066736044017135 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/angles2d.m0000644000175000017500000000436113066736044017315 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} angles2d () ## Description of functions for manipulating angles ## ## Angles are normalized in an interval of width 2*PI. Most geom2d ## functions return results in the [0 2*pi] interval, but it can be ## convenient to consider the [-pi pi] interval as well. See the ## normalizeAngle function to switch between conventions. ## ## Angles are usually oriented. The default orientation is the CCW ## (Counter-Clockwise) orientation. ## ## @seealso{angle2Points, angle3Points, angleAbsDiff, normalizeAngle, vectorAngle, ## angleDiff, angleSort, lineAngle, edgeAngle, deg2rad, rad2deg} ## @end deftypefn function angles2d help('angles2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPointOnRay.m0000644000000000000000000000013213066736044020034 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPointOnRay.m0000644000175000017500000000656213066736044020221 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPointOnRay (@var{point}, @var{ray}) ## @deftypefnx {Function File} {@var{b} = } isPointOnRay (@var{point}, @var{ray}, @var{tol}) ## Test if a point belongs to a ray ## ## @var{b} = isPointOnRay(@var{point}, @var{ray}); ## Returns @code{true} if point @var{point} belongs to the ray @var{ray}. ## @var{point} is given by [x y] and RAY by [x0 y0 dx dy]. @var{tol} gives the ## tolerance for the calculations. ## ## @seealso{rays2d, points2d, isPointOnLine} ## @end deftypefn function b = isPointOnRay(point, ray, varargin) # extract computation tolerance tol = 1e-14; if ~isempty(varargin) tol = varargin{1}; end # number of rays and points Nr = size(ray, 1); Np = size(point, 1); # if several rays or several points, adapt sizes of arrays x0 = repmat(ray(:,1)', Np, 1); y0 = repmat(ray(:,2)', Np, 1); dx = repmat(ray(:,3)', Np, 1); dy = repmat(ray(:,4)', Np, 1); xp = repmat(point(:,1), 1, Nr); yp = repmat(point(:,2), 1, Nr); # test if points belongs to the supporting line b1 = abs ( (xp-x0).*dy - (yp-y0).*dx ) ./ hypot(dx, dy) < tol; # check if points lie the good direction on the rays ind = abs (dx) > abs (dy); t = zeros (size (b1)); t(ind) = (xp(ind)-x0(ind))./dx(ind); t(~ind) = (yp(~ind)-y0(~ind))./dy(~ind); # combine the two tests b = b1 & (t >= 0); endfunction %!shared ray %! p1 = [10 20]; %! p2 = [80 20]; %! ray = createRay (p1, p2); %!assert (isPointOnRay([10 20], ray)); %!assert (isPointOnRay([80 20], ray)); %!assert (isPointOnRay([50 20], ray)); %!assert (isPointOnRay([50 20+1e-3], ray,1e-2)); %!assert ( !isPointOnRay([50 20+1e-3], ray,1e-4)); %!assert ( !isPointOnRay([9.99 20], ray)); %!assert ( !isPointOnRay([80 20.01], ray)); %!assert ( !isPointOnRay([50 21], ray)); %!assert ( !isPointOnRay([79 19], ray)); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/closedPath.m0000644000000000000000000000013213066736044017524 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/closedPath.m0000644000175000017500000000731113066736044017702 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012-2017 Simeon Simeonov ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{y} =} polygon (@var{x}) ## Returns a simple closed path that passes through all the points in @var{x}. ## @var{x} is a vector containing 2D coordinates of the points. ## ## @end deftypefn ## Author: Simeon Simeonov function y = closedPath(x) if(size(x,1) > 1 && size(x,1) < size(x,2)) x = x'; end N = size(x,1); # Number of points idx = zeros(N, 1); # ind contains the indices of the sorted coordinates a = find(x(:,2)==min(x(:,2))); if(size(a,1) > 1) [~, i] = sort(x(a,1)); a = a(i(1)); end x_1 = x(x(:,2)==x(a,2),:); # find all x with the same y coordinate if(x(a,1) == min(x(:,1))) x_2 = x(x(:,1)==x(a,1),:); # find all x with the same x coordinate else x_2 = x(a,:); end if(size(x_1,1) > 1 || size(x_2,1) > 1) if(size(x_1,1) > 1) x_1 = sort(x_1); # Sort by x coordinate y(1,:) = x(a,:); # original starting point end if (size(x_2,1) > 1) x_2 = sort(x_2, 'descend'); end x_not = [x_1; x_2]; i = ismember(x,x_not,'rows'); x(i, :) = []; x = [x_1(size(x_1,1),:); x]; x_1(size(x_1, 1),:) = []; N = size(x,1); a = 1; else x_1 = []; x_2 = x(a,:); end d = x - repmat(x(a,:), N, 1); th = d(:,2)./(d(:,1) + d(:,2)); [~, idx0] = ismember(sort(th(th==0)), th); [~, idx1] = ismember(sort(th(th>0)), th); [~, idx2] = ismember(sort(th(th<0)), th); idx = [a; idx0; idx1; idx2]; # I contains the indices of idx in a sorted order. [v i] = sort(idx) then # i==I. [~,I,J]= unique(idx); if(size(I,1) ~= size(J,1)) R = histc(J, 1:size(I,1)); # R(1) will always be 1? idx_sorted = idx(I); r = find(R>1); for ri = r' idx_repeated = idx_sorted(ri); idx(idx==idx_repeated) = find(th==th(idx_sorted(ri))); end end y = [x_1; x(idx,:); x_2;]; endfunction %!demo %! maxInt = 100; %! N = 25; %! figure (); %! for i = 1:4 %! subplot (2,2,i); %! x = randi(maxInt, N, 2); %! y = closedPath(x); %! plot(y(:,1), y(:,2), '-*'); %! end geometry-3.0.0/inst/geom2d/PaxHeaders.28738/squareGrid.m0000644000000000000000000000013213066736044017544 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/squareGrid.m0000644000175000017500000000545413066736044017730 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pts} = } squaregrid (@var{bounds}, @var{origin}, @var{size}) ## Generate equally spaces points in plane. ## ## usage ## PTS = squareGrid(BOUNDS, ORIGIN, SIZE) ## generate points, lying in the window defined by BOUNDS (=[xmin ymin ## xmax ymax]), starting from origin with a constant step equal to size. ## ## Example ## PTS = squareGrid([0 0 10 10], [3 3], [4 2]) ## will return points : ## [3 1;7 1;3 3;7 3;3 5;7 5;3 7;7 7;3 9;7 9]; ## ## TODO: add possibility to use rotated grid ## ## @end deftypefn function varargout = squareGrid(bounds, origin, size) # find all x coordinate x1 = bounds(1) + mod(origin(1)-bounds(1), size(1)); x2 = bounds(3) - mod(bounds(3)-origin(1), size(1)); lx = (x1:size(1):x2)'; # find all y coordinate y1 = bounds(2) + mod(origin(2)-bounds(2), size(2)); y2 = bounds(4) - mod(bounds(4)-origin(2), size(2)); ly = (y1:size(2):y2)'; # number of points in each coord, and total number of points ny = length(ly); nx = length(lx); np = nx*ny; # create points pts = zeros(np, 2); for i=1:ny pts( (1:nx)'+(i-1)*nx, 1) = lx; pts( (1:nx)'+(i-1)*nx, 2) = ly(i); end # process output if nargout>0 varargout{1} = pts; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/private0000644000000000000000000000013213066736044016655 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/private/0002755000175000017500000000000013066736044017110 5ustar00olafolaf00000000000000geometry-3.0.0/inst/geom2d/private/PaxHeaders.28738/assertElementsAlmostEqual.m0000644000000000000000000000013213066736044024256 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/private/assertElementsAlmostEqual.m0000644000175000017500000000335213066736044024435 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} assertElementsAlmostEqual () ## Wrapper. Not documented. ## ## @end deftypefn function assertElementsAlmostEqual(a,b) assert(b,a,1e-6); endfunction geometry-3.0.0/inst/geom2d/private/PaxHeaders.28738/assertTrue.m0000644000000000000000000000013213066736044021251 xustar0030 mtime=1490795556.604869691 30 atime=1490795556.604869691 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/private/assertTrue.m0000644000175000017500000000330313066736044021424 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} assertTrue () ## Wrapper. Not documented. ## ## @end deftypefn function assertTrue(a) assert(a); endfunction geometry-3.0.0/inst/geom2d/private/PaxHeaders.28738/assertAlmostEqual.m0000644000000000000000000000013213066736044022561 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/private/assertAlmostEqual.m0000644000175000017500000000333213066736044022736 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} assertAlmostEqual () ## Wrapper. Not documented. ## ## @end deftypefn function assertAlmostEqual(a,b) assert(b,a,1e-6); endfunction geometry-3.0.0/inst/geom2d/private/PaxHeaders.28738/assertEqual.m0000644000000000000000000000013213066736044021401 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/private/assertEqual.m0000644000175000017500000000331113066736044021553 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} assertEqual () ## Wrapper. Not documented. ## ## @end deftypefn function assertEqual(a,b) assert(b,a); endfunction geometry-3.0.0/inst/geom2d/private/PaxHeaders.28738/assertFalse.m0000644000000000000000000000013213066736044021364 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/private/assertFalse.m0000644000175000017500000000330613066736044021542 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {} assertFalse () ## Wrapper. Not documented. ## ## @end deftypefn function assertFalse(a) assert(!a); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/pointOnLine.m0000644000000000000000000000013213066736044017674 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/pointOnLine.m0000644000175000017500000000432213066736044020051 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{point} = } pointOnLine (@var{line}, @var{d}) ## Create a point on a line at a given position on the line. ## ## Creates the point belonging to the line @var{line}, and located at the ## distance @var{d} from the line origin. ## @var{line} has the form [x0 y0 dx dy]. ## @var{line} and @var{d} should have the same number N of rows. The result will have ## N rows and 2 column (x and y positions). ## ## @seealso{lines2d, points2d, onLine, onLine, linePosition} ## @end deftypefn function point = pointOnLine(lin, pos) ang = lineAngle(lin); point = [lin(:,1) + pos .* cos(ang), lin(:,2) + pos .* sin(ang)]; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/centroid.m0000644000000000000000000000013213066736044017245 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/centroid.m0000644000175000017500000001010013066736044017411 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{c} = } centroid (@var{points}) ## @deftypefnx {Function File} {@var{c} = } centroid (@var{px}, @var{py}) ## @deftypefnx {Function File} {@var{c} = } centroid (@dots{}, @var{mass}) ## Compute centroid (center of mass) of a set of points. ## ## Computes the ND-dimensional centroid of a set of points. ## @var{points} is an array with as many rows as the number of points, and as ## many columns as the number of dimensions. ## @var{px} and @var{py} are two column vectors containing coordinates of the ## 2-dimensional points. ## The result @var{c} is a row vector with ND columns. ## ## If @var{mass} is given, computes center of mass of @var{points}, weighted by coefficient @var{mass}. ## @var{points} is a Np-by-Nd array, @var{mass} is Np-by-1 array, and @var{px} and @var{py} are ## also both Np-by-1 arrays. ## ## Example: ## ## @example ## pts = [2 2;6 1;6 5;2 4]; ## centroid(pts) ## ans = ## 4 3 ##@end example ## ## @seealso{points2d, polygonCentroid} ## @end deftypefn function center = centroid(varargin) ## extract input arguments # use empty mass by default mass = []; if nargin==1 # give only array of points pts = varargin{1}; elseif nargin==2 # either POINTS+MASS or PX+PY var = varargin{1}; if size(var, 2)>1 # arguments are POINTS, and MASS pts = var; mass = varargin{2}; else # arguments are PX and PY pts = [var varargin{2}]; end elseif nargin==3 # arguments are PX, PY, and MASS pts = [varargin{1} varargin{2}]; mass = varargin{3}; end ## compute centroid if isempty(mass) # no weight center = mean(pts); else # format mass to have sum equal to 1, and column format mass = mass(:)/sum(mass(:)); # compute weighted centroid center = sum(bsxfun(@times, pts, mass), 1); # equivalent to: # center = sum(pts .* mass(:, ones(1, size(pts, 2)))); end endfunction %!test %! points = [0 0;10 0;10 10;0 10]; %! centro = centroid(points); %! assert ([5 5], centro, 1e-6); %!test %! points = [0 0;10 0;10 10;0 10]; %! centro = centroid(points(:,1), points(:,2)); %! assert ([5 5], centro, 1e-6); %!test %! points = [0 0;30 0;30 30;0 30]; %! centro = centroid(points, [1;1;1;3]); %! assert ([10 20], centro, 1e-6); %!test %! points = [0 0;30 0;30 30;0 30]; %! centro = centroid(points(:,1), points(:,2), [1;1;1;3]); %! assert ([10 20], centro, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/intersectCircles.m0000644000000000000000000000013213066736044020743 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/intersectCircles.m0000644000175000017500000001054213066736044021121 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{points} = } intersectCircles (@var{circle1}, @var{circle2}) ## Intersection points of two circles. ## ## POINTS = intersectCircles(CIRCLE1, CIRCLE2) ## Computes the intersetion point of the two circles CIRCLE1 and CIRCLE1. ## Both circles are given with format: [XC YC R], with (XC,YC) being the ## coordinates of the center and R being the radius. ## POINTS is a 2-by-2 array, containing coordinate of an intersection ## point on each row. ## In the case of tangent circles, the intersection is returned twice. It ## can be simplified by using the 'unique' function. ## ## Example ## # intersection points of two distant circles ## c1 = [0 0 10]; ## c2 = [10 0 10]; ## pts = intersectCircles(c1, c2) ## pts = ## 5 -8.6603 ## 5 8.6603 ## ## # intersection points of two tangent circles ## c1 = [0 0 10]; ## c2 = [20 0 10]; ## pts = intersectCircles(c1, c2) ## pts = ## 10 0 ## 10 0 ## pts2 = unique(pts, 'rows') ## pts2 = ## 10 0 ## ## References ## http://local.wasp.uwa.edu.au/~pbourke/geometry/2circle/ ## http://mathworld.wolfram.com/Circle-CircleIntersection.html ## ## @seealso{circles2d, intersectLineCircle, radicalAxis} ## @end deftypefn function points = intersectCircles(circle1, circle2) # adapt sizes of inputs n1 = size(circle1, 1); n2 = size(circle2, 1); if n1 ~= n2 if n1 > 1 && n2 == 1 circle2 = repmat(circle2, n1, 1); elseif n2 > 1 && n1 == 1 circle1 = repmat(circle1, n2, 1); else error('Both input should have same number of rows'); end end # extract center and radius of each circle center1 = circle1(:, 1:2); center2 = circle2(:, 1:2); r1 = circle1(:,3); r2 = circle2(:,3); # allocate memory for result nPoints = length(r1); points = NaN * ones(2*nPoints, 2); # distance between circle centers d12 = distancePoints(center1, center2, 'diag'); # get indices of circle couples with intersections inds = d12 >= abs(r1 - r2) & d12 <= (r1 + r2); if sum(inds) == 0 return; end # angle of line from center1 to center2 angle = angle2Points(center1(inds,:), center2(inds,:)); # position of intermediate point, located at the intersection of the # radical axis with the line joining circle centers d1m = d12(inds) / 2 + (r1(inds).^2 - r2(inds).^2) ./ (2 * d12(inds)); tmp = polarPoint(center1(inds, :), d1m, angle); # distance between intermediate point and each intersection point h = sqrt(r1(inds).^2 - d1m.^2); # indices of valid intersections inds2 = find(inds)*2; inds1 = inds2 - 1; # create intersection points points(inds1, :) = polarPoint(tmp, h, angle - pi/2); points(inds2, :) = polarPoint(tmp, h, angle + pi/2); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPointInEllipse.m0000644000000000000000000000013213066736044020670 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPointInEllipse.m0000644000175000017500000000540413066736044021047 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPointInellipse (@var{point}, @var{ellipse}) ## Check if a point is located inside a given ellipse ## ## B = isPointInEllipse(POINT, ELLIPSE) ## Returns true if point is located inside the given ellipse. ## ## B = isPointInEllipse(POINT, ELLIPSE, TOL) ## Specifies the tolerance value ## ## Example: ## isPointInEllipse([1 0], [0 0 2 1 0]) ## ans = ## 1 ## isPointInEllipse([0 0], [0 0 2 1 0]) ## ans = ## 1 ## isPointInEllipse([1 1], [0 0 2 1 0]) ## ans = ## 0 ## isPointInEllipse([1 1], [0 0 2 1 30]) ## ans = ## 1 ## ## @seealso{ellipses2d, isPointInCircle} ## @end deftypefn function b = isPointInEllipse(point, ellipse, varargin) # extract computation tolerance tol = 1e-14; if ~isempty(varargin) tol = varargin{1}; end # compute ellipse to unit circle transform rot = createRotation(-deg2rad(ellipse(5))); sca = createScaling(1./ellipse(3:4)); trans = sca * rot; # transform points to unit circle basis pTrans = bsxfun(@minus, point, ellipse(:,1:2)); pTrans = transformPoint(pTrans, trans); # test if distance to origin smaller than 1 b = sqrt(sum(power(pTrans, 2), 2)) - 1 <= tol; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPointInCircle.m0000644000000000000000000000013213066736044020474 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPointInCircle.m0000644000175000017500000000464613066736044020662 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPointInCircle (@var{point}, @var{circle}) ## Test if a point is located inside a given circle ## ## B = isPointInCircle(POINT, CIRCLE) ## Returns true if point is located inside the circle, i.e. if distance to ## circle center is lower than the circle radius. ## ## B = isPointInCircle(POINT, CIRCLE, TOL) ## Specifies the tolerance value ## ## Example: ## isPointInCircle([1 0], [0 0 1]) ## isPointInCircle([0 0], [0 0 1]) ## returns true, whereas ## isPointInCircle([1 1], [0 0 1]) ## return false ## ## @seealso{circles2d, isPointOnCircle} ## @end deftypefn function b = isPointInCircle(point, circle, varargin) # extract computation tolerance tol = 1e-14; if ~isempty(varargin) tol = varargin{1}; end d = sqrt(sum(power(point - circle(:,1:2), 2), 2)); b = d-circle(:,3)<=tol; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/clipLine.m0000644000000000000000000000013213066736044017175 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/clipLine.m0000644000175000017500000001541613066736044017360 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{edge} =} clipLine (@var{line}, @var{box}) ## Clip a line with a box. ## ## @var{line} is a straight line given as a 4 element row vector: [x0 y0 dx dy], ## with (x0 y0) being a point of the line and (dx dy) a direction vector, ## @var{box} is the clipping box, given by its extreme coordinates: ## [xmin xmax ymin ymax]. ## The result is given as an edge, defined by the coordinates of its 2 ## extreme points: [x1 y1 x2 y2]. ## If line does not intersect the box, [NaN NaN NaN NaN] is returned. ## ## Function works also if @var{line} is a Nx4 array, if @var{box} is a Nx4 array, or ## if both @var{line} and @var{box} are Nx4 arrays. In these cases, @var{edge} is a Nx4 ## array. ## ## Example: ## ## @example ## line = [30 40 10 0]; ## box = [0 100 0 100]; ## res = clipLine(line, box) ## res = ## 0 40 100 40 ## @end example ## ## @seealso{lines2d, boxes2d, edges2d, clipEdge, clipRay} ## @end deftypefn function edge = clipLine(lin, bb, varargin) # adjust size of two input arguments if size(lin, 1)==1 lin = repmat(lin, size(bb, 1), 1); elseif size(bb, 1)==1 bb = repmat(bb, size(lin, 1), 1); elseif size(lin, 1) ~= size(bb, 1) error('bad sizes for input'); end # allocate memory nbLines = size(lin, 1); edge = zeros(nbLines, 4); # main loop on lines for i=1:nbLines # extract limits of the box xmin = bb(i, 1); xmax = bb(i, 2); ymin = bb(i, 3); ymax = bb(i, 4); # use direction vector for box edges similar to direction vector of the # line in order to reduce computation errors delta = hypot(lin(i,3), lin(i,4)); # compute intersection with each edge of the box # lower edge px1 = intersectLines(lin(i,:), [xmin ymin delta 0]); # right edge px2 = intersectLines(lin(i,:), [xmax ymin 0 delta]); # upper edge py1 = intersectLines(lin(i,:), [xmax ymax -delta 0]); # left edge py2 = intersectLines(lin(i,:), [xmin ymax 0 -delta]); # remove undefined intersections (case of lines parallel to box edges) points = [px1 ; px2 ; py1 ; py2]; points = points(isfinite(points(:,1)), :); # sort points according to their position on the line pos = linePosition(points, lin(i,:)); [pos inds] = sort(pos); ##ok points = points(inds, :); # create clipped edge by using the two points in the middle ind = size(points, 1)/2; inter1 = points(ind,:); inter2 = points(ind+1,:); edge(i, 1:4) = [inter1 inter2]; # check that middle point of the edge is contained in the box midX = mean(edge(i, [1 3])); xOk = xmin <= midX && midX <= xmax; midY = mean(edge(i, [2 4])); yOk = ymin <= midY && midY <= ymax; # if one of the bounding condition is not met, set edge to NaN if ~(xOk && yOk) edge (i,:) = NaN; end end endfunction %!demo %! lin = [30 40 10 0]; %! bb = [0 100 0 100]; %! res = clipLine(lin, bb) %! %! drawBox(bb,'color','k'); %! line(lin([1 3]),lin([2 4]),'color','b'); %! line(res([1 3]),res([2 4]),'color','r','linewidth',2); %! axis tight %! v = axis (); %! axis(v+[0 10 -10 0]) %!test # inside, to the right # inside, to the left# outside %! bb = [0 100 0 100]; %! lin = [30 40 10 0]; %! edge = [0 40 100 40]; %! assert (edge, clipLine(lin, bb), 1e-6); %! lin = [30 40 -10 0]; %! edge = [100 40 0 40]; %! assert (edge, clipLine(lin, bb), 1e-6); %! lin = [30 140 10 0]; %! assert (sum(isnan(clipLine(lin, bb)))==4); %!test # inside, upward # inside, downward # outside %! bb = [0 100 0 100]; %! lin = [30 40 0 10]; %! edge = [30 0 30 100]; %! assert (edge, clipLine(lin, bb), 1e-6); %! lin = [30 40 0 -10]; %! edge = [30 100 30 0]; %! assert (edge, clipLine(lin, bb), 1e-6); %! lin = [140 30 0 10]; %! assert (sum(isnan(clipLine(lin, bb)))==4); %!test # inside, top right corner# inside, down right corner # outside %! bb = [0 100 0 100]; %! lin = [80 30 10 10]; %! edge = [50 0 100 50]; %! assert (edge, clipLine(lin, bb), 1e-6); %! lin = [20 70 10 10]; %! edge = [0 50 50 100]; %! assert (edge, clipLine(lin, bb), 1e-6); %! lin = [140 -30 10 10]; %! assert (sum(isnan(clipLine(lin, bb)))==4); %! lin = [-40 130 10 10]; %! assert (sum(isnan(clipLine(lin, bb)))==4); %!test #multilines # inside, top right corner %! bb = [0 100 0 100]; %! lin = [... %! 80 30 10 10; ... %! 20 70 10 10; ... %! 140 -30 10 10; ... %! -40 130 10 10]; %! edge = [... %! 50 0 100 50; ... %! 0 50 50 100; ... %! NaN NaN NaN NaN; ... %! NaN NaN NaN NaN; ... %! ]; %! clipped = clipLine(lin, bb); %! assert (4, size(clipped, 1)); %! assert (edge(1:2, :), clipped(1:2, :), 1e-6); %! assert (sum(isnan(clipped(3,:)))==4); %! assert (sum(isnan(clipped(4,:)))==4); %!test # test clipping of horizontal lines # inside, to the right %! bb = [-1 1 -1 1]*1e10; %! lin = [3 0 1 2]; %! D = 1e10; %! edge = [3-D/2 -D 3+D/2 D]; %! clipped = clipLine(lin, bb); %! assert (edge, clipped); %!test # inside, to the right %! bb = [-1 1 -1 1]*100; %! lin = [3 0 1*1e10 2*1e10]; %! D = 100; %! edge = [3-D/2 -D 3+D/2 D]; %! clipped = clipLine(lin, bb); %! assert (edge, clipped, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/clipPoints.m0000644000000000000000000000013213066736044017562 xustar0030 mtime=1490795556.568869026 30 atime=1490795556.568869026 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/clipPoints.m0000644000175000017500000000641413066736044017743 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{points2} =} clipPoints (@var{points}, @var{box}) ## Clip a set of points by a box. ## ## Returns the set @var{points2} which are located inside of the box @var{box}. ## ## @seealso{points2d, boxes2d, clipLine, drawPoint} ## @end deftypefn function points = clipPoints(points, bb) # get bounding box limits xmin = bb(1); xmax = bb(2); ymin = bb(3); ymax = bb(4); # compute indices of points inside visible area xOk = points(:,1)>=xmin & points(:,1)<=xmax; yOk = points(:,2)>=ymin & points(:,2)<=ymax; # keep only points inside box points = points(xOk & yOk, :); endfunction %!demo %! points = 2*rand(100,2)-1; %! bb = [-0.5 0.5 -0.25 0.25]; %! cpo = clipPoints (points, bb); %! %! plot(points(:,1),points(:,2),'xr') %! hold on %! drawBox(bb,'color','k') %! plot(cpo(:,1),cpo(:,2),'*g') %! hold off %!shared bb %! bb = [0 10 0 20]; %!test %! corners = [0 0;10 0;0 20;10 20]; %! cornersClipped = clipPoints(corners, bb); %! assert (4, size(cornersClipped, 1)); %! assert (corners, cornersClipped, 1e-6); %!test %! borders = [0 5;10 5;5 0;5 20]; %! bordersClipped = clipPoints(borders, bb); %! assert (4, size(bordersClipped, 1)); %! assert (borders, bordersClipped, 1e-6); %!test %! inside = [5 5;5 10;5 15]; %! insideClipped = clipPoints(inside, bb); %! assert (size(inside, 1), size(insideClipped, 1)); %! assert (inside, insideClipped); %!test %! points = [-1 0;11 0;-1 20;11 20;0 -1;0 21;10 -1;10 21]; %! pointsClipped = clipPoints(points, bb); %! assert (0, size(pointsClipped, 1)); %!test %! points = [-5 10;0 10;5 10;10 10; 15 10]; %! pointsClipped = clipPoints(points, bb); %! assert (3, size(pointsClipped, 1)); %! assert (points(2:4,:), pointsClipped, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createRotation.m0000644000000000000000000000013213066736044020421 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createRotation.m0000644000175000017500000000717213066736044020604 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } createRotation (@var{theta}) ## @deftypefnx {Function File} {@var{T} = } createRotation (@var{point}, @var{theta}) ## @deftypefnx {Function File} {@var{T} = } createRotation (@var{x0}, @var{y0}, @var{theta}) ## Create the 3*3 matrix of a rotation. ## ## Returns the rotation corresponding to angle @var{theta} (in radians) ## The returned matrix has the form : ## [cos(theta) -sin(theta) 0] ## [sin(theta) cos(theta) 0] ## [0 0 1] ## ## @var{point} or (@var{x0},@var{y0}), specifies origin of rotation. The result is similar as performing ## translation(-@var{x0},-@var{y0}), rotation(@var{theta}), and translation(@var{x0},@var{y0}). ## ## ## @seealso{transforms2d, transformPoint, createTranslation, createScaling} ## @end deftypefn function trans = createRotation(varargin) # default values cx = 0; cy = 0; theta = 0; # get input values if length(varargin)==1 # only angle theta = varargin{1}; elseif length(varargin)==2 # origin point (as array) and angle var = varargin{1}; cx = var(1); cy = var(2); theta = varargin{2}; elseif length(varargin)==3 # origin (x and y) and angle cx = varargin{1}; cy = varargin{2}; theta = varargin{3}; end # compute coefs cot = cos(theta); sit = sin(theta); tx = cy*sit - cx*cot + cx; ty = -cy*cot - cx*sit + cy; # create transformation matrix trans = [cot -sit tx; sit cot ty; 0 0 1]; endfunction %!test %! trans = createRotation(0); %! assert (trans, [1 0 0;0 1 0;0 0 1], 1e-6); %!test %! trans = createRotation(pi/2); %! assert (trans, [0 -1 0; 1 0 0; 0 0 1], 1e-6); %!test %! trans = createRotation(pi); %! assert (trans, [-1 0 0;0 -1 0;0 0 1], 1e-6); %!test %! trans = createRotation(3*pi/2); %! assert (trans, [0 1 0; -1 0 0; 0 0 1], 1e-6); %!test %! p0 = [3 5]; %! theta = pi/3; %! trans1 = createRotation(p0, theta); %! t1 = createTranslation(-p0); %! rot = createRotation(theta); %! t2 = createTranslation(p0); %! trans2 = t2*rot*t1; %! assert (trans1, trans2, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/hexagonalGrid.m0000644000000000000000000000013213066736044020212 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/hexagonalGrid.m0000644000175000017500000000757513066736044020404 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pts} = } hexagonalGrid (@var{bounds}, @var{origin}, @var{size}) ## Generate hexagonal grid of points in the plane. ## ## usage ## PTS = hexagonalGrid(BOUNDS, ORIGIN, SIZE) ## generate points, lying in the window defined by BOUNDS (=[xmin ymin ## xmax ymax]), starting from origin with a constant step equal to size. ## SIZE is constant and is equals to the length of the sides of each ## hexagon. ## ## TODO: add possibility to use rotated grid ## @end deftypefn function varargout = hexagonalGrid(bounds, origin, size, varargin) size = size(1); dx = 3*size; dy = size*sqrt(3); # consider two square grids with different centers pts1 = squareGrid(bounds, origin + [0 0], [dx dy], varargin{:}); pts2 = squareGrid(bounds, origin + [dx/3 0], [dx dy], varargin{:}); pts3 = squareGrid(bounds, origin + [dx/2 dy/2], [dx dy], varargin{:}); pts4 = squareGrid(bounds, origin + [-dx/6 dy/2], [dx dy], varargin{:}); # gather points pts = [pts1;pts2;pts3;pts4]; # eventually compute also edges, clipped by bounds # TODO : manage generation of edges if nargout>1 edges = zeros([0 4]); x0 = origin(1); y0 = origin(2); # find all x coordinate x1 = bounds(1) + mod(x0-bounds(1), dx); x2 = bounds(3) - mod(bounds(3)-x0, dx); lx = (x1:dx:x2)'; # horizontal edges : first find y's y1 = bounds(2) + mod(y0-bounds(2), dy); y2 = bounds(4) - mod(bounds(4)-y0, dy); ly = (y1:dy:y2)'; # number of points in each coord, and total number of points ny = length(ly); nx = length(lx); if bounds(1)-x1+dx0 varargout{1} = pts; if nargout>1 varargout{2} = edges; end end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/transformVector.m0000644000000000000000000000013213066736044020634 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/transformVector.m0000644000175000017500000000730113066736044021011 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{v2} = } transformVector (@var{v}, @var{T}) ## @deftypefnx {Function File} {[@var{x2} @var{y2}] = } transformVector (@var{x},@var{y}, @var{T}) ## Transform a vector with an affine transform ## ## @var{v} has the form [xv yv], and @var{T} is a [2x2], [2x3] or [3x3] ## matrix, returns the vector transformed with affine transform @var{T}. ## ## Format of @var{T} can be one of : ## @group ## [a b] , [a b c] , or [a b c] ## [d e] [d e f] [d e f] ## [0 0 1] ## @end group ## ## Also works when @var{v} is a [Nx2] array of double. In this case, @var{v2} has ## the same size as @var{v}. ## ## Also works when @var{x} and @var{y} are arrays the same size. The function ## transform each couple of (@var{x}, @var{y}), and return the result in ## (@var{x2}, @var{y2}), which is the same size as (@var{x}, @var{y}). ## ## @seealso{vectors2d, transforms2d, rotateVector, transformPoint} ## @end deftypefn function varargout = transformVector(varargin) if length(varargin)==2 var = varargin{1}; vx = var(:,1); vy = var(:,2); trans = varargin{2}; elseif length(varargin)==3 vx = varargin{1}; vy = varargin{2}; trans = varargin{3}; else error('wrong number of arguments in "transformVector"'); end # compute new position of vector vx2 = vx*trans(1,1) + vy*trans(1,2); vy2 = vx*trans(2,1) + vy*trans(2,2); if size(trans, 2) == 3 vx2 = vx2 + trans(1,3); vy2 = vy2 + trans(2,3); end # format output if nargout==0 || nargout==1 varargout{1} = [vx2 vy2]; elseif nargout==2 varargout{1} = vx2; varargout{2} = vy2; end endfunction %!demo %! t1 = [2 0 0; 0 2 0]; %! t2 = [1 0 1; 0 1 1]; %! t3 = [0.5 0 1; 0 0.5 1; 0 0 1]; %! %! triangle = [-0.5 -1/3; 0.5 -1/3; 0 2/3; -0.5 -1/3]; %! tr1 = transformVector(triangle,t1); %! tr2 = transformVector(triangle,t2); %! tr3 = transformVector(triangle,t3); %! %! plot(triangle(:,1),triangle(:,2),'k-', ... %! tr1(:,1),tr1(:,2),'g-;scaled up;', ... %! tr2(:,1),tr2(:,2),'m-;translated;', ... %! tr3(:,1),tr3(:,2),'b-;scaled down and translated;') geometry-3.0.0/inst/geom2d/PaxHeaders.28738/vectorNorm.m0000644000000000000000000000013213066736044017574 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/vectorNorm.m0000644000175000017500000000661413066736044017757 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{nm} = } vectorNorm (@var{v}) ## @deftypefnx {Function File} {@var{nm} = } vectorNorm (@var{v},@var{n}) ## Compute norm of a vector, or of a set of vectors ## ## Without extra arguments, returns the euclidean norm of vector V. ## Optional argument @var{n} specifies the norm to use. N can be any value ## greater than 0. ## @table @samp ## @item N=1 ## City lock norm. ## @item N=2 ## Euclidean norm. ## @item N=inf ## Compute max coord. ## @end table ## ## When @var{v} is a MxN array, compute norm for each vector of the array. ## Vector are given as rows. Result is then a Mx1 array. ## ## Example ## ## @example ## n1 = vectorNorm([3 4]) ## n1 = ## 5 ## ## n2 = vectorNorm([1, 10], inf) ## n2 = ## 10 ## @end example ## ## @seealso{vectors2d, vectorAngle} ## @end deftypefn function n = vectorNorm(v, varargin) # size of vector dim = size (v); # extract the type of norm to compute d = 2; if ~isempty (varargin) d = varargin{1}; end if d==2 # euclidean norm: sum of squared coordinates, and take square root if dim(1)==1 || dim(2)==1 n = sqrt (sumsq (v)); else n = sqrt (sumsq (v, 2)); end elseif d==1 # absolute norm: sum of absolute coordinates if dim(1)==1 || dim(2)==1 n = sum (abs (v)); else n = sum (abs (v), 2); end elseif d==inf # infinite norm: uses the maximal corodinate if dim(1)==1 || dim(2)==1 n = max (v); else n = max (v, [], 2); end else # Other norms, use explicit but slower expression if dim(1)==1 || dim(2)==1 n = power (sum (power(v, d)), 1/d); else n = power (sum (power(v, d), 2), 1/d); end end endfunction %!assert (5, vectorNorm ([3 4])) %!assert(10, vectorNorm ([1, 10], inf)) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawCircleArc.m0000644000000000000000000000013213066736044020143 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawCircleArc.m0000644000175000017500000000745713066736044020334 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawCircleArc (@var{xc}, @var{yc}, @var{r}, @var{start}, @var{end}) ## @deftypefnx {Function File} {@var{h} = } drawCircleArc (@var{arc}) ## @deftypefnx {Function File} {@var{h} = } drawCircleArc (@dots{}, @var{param}, @var{value}) ## Draw a circle arc on the current axis ## ## drawCircleArc(XC, YC, R, START, EXTENT); ## Draws circle with center (XC, YC), with radius R, starting from angle ## START, and with angular extent given by EXTENT. START and EXTENT angles ## are given in degrees. ## ## drawCircleArc(ARC); ## Puts all parameters into one single array. ## ## drawCircleArc(..., PARAM, VALUE); ## specifies plot properties by using one or several parameter name-value ## pairs. ## ## H = drawCircleArc(...); ## Returns a handle to the created line object. ## ## @example ## # Draw a red thick circle arc ## arc = [10 20 30 -120 240]; ## figure; ## axis([-50 100 -50 100]); ## hold on ## drawCircleArc(arc, 'LineWidth', 3, 'Color', 'r') ## @end example ## ## @seealso{circles2d, drawCircle, drawEllipse} ## @end deftypefn function varargout = drawCircleArc(varargin) if nargin == 0 error('Need to specify circle arc'); end circle = varargin{1}; if size(circle, 2) == 5 x0 = circle(:,1); y0 = circle(:,2); r = circle(:,3); start = circle(:,4); extent = circle(:,5); varargin(1) = []; elseif length(varargin) >= 5 x0 = varargin{1}; y0 = varargin{2}; r = varargin{3}; start = varargin{4}; extent = varargin{5}; varargin(1:5) = []; else error('drawCircleArc: please specify center, radius and angles of circle arc'); end # convert angles in radians t0 = deg2rad(start); t1 = t0 + deg2rad(extent); # number of line segments N = 60; # initialize handles vector h = zeros(length(x0), 1); # draw each circle arc individually for i = 1:length(x0) # compute basis t = linspace(t0(i), t1(i), N+1)'; # compute vertices coordinates xt = x0(i) + r(i)*cos(t); yt = y0(i) + r(i)*sin(t); # draw the circle arc h(i) = plot(xt, yt, varargin{:}); end if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createTranslation.m0000644000000000000000000000013213066736044021120 xustar0030 mtime=1490795556.576869173 30 atime=1490795556.576869173 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createTranslation.m0000644000175000017500000000502613066736044021277 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{T} = } createTranslation (@var{vector}) ## @deftypefnx {Function File} {@var{T} = } createTranslation (@var{dx},@var{dy}) ## Create the 3*3 matrix of a translation. ## ## Returns the matrix corresponding to a translation by the vector [@var{dx} @var{dy}]. ## The components can be given as two arguments. ## The returned matrix has the form : ## [1 0 TX] ## [0 1 TY] ## [0 0 1] ## ## @seealso{transforms2d, transformPoint, createRotation, createScaling} ## @end deftypefn function trans = createTranslation(varargin) # process input arguments if isempty(varargin) tx = 0; ty = 0; elseif length(varargin)==1 var = varargin{1}; tx = var(1); ty = var(2); else tx = varargin{1}; ty = varargin{2}; end # create the matrix representing the translation trans = [1 0 tx ; 0 1 ty ; 0 0 1]; endfunction %!test %! trans = createTranslation(2, 3); %! assert (trans, [1 0 2;0 1 3;0 0 1], 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/points2d.m0000644000000000000000000000013213066736044017200 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/points2d.m0000644000175000017500000000433013066736044017354 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} points2d () ## Description of functions operating on points. ## ## A point is defined by its two cartesian coordinate, put into a row ## vector of 2 elements: ## P = [x y]; ## ## Several points are stores in a matrix with two columns, one for the ## x-coordinate, one for the y-coordinate. ## PTS = [x1 y1 ; x2 y2 ; x3 y3]; ## ## Example ## P = [5 6]; ## ## @seealso{centroid, midPoint, polarPoint, pointOnLine ## isCounterClockwise, angle2Points, angle3Points, angleSort ## distancePoints, minDistancePoints ## transformPoint, clipPoints, drawPoint} ## @end deftypefn function points2d help('points2d'); endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawEllipseArc.m0000644000000000000000000000013213066736044020337 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawEllipseArc.m0000644000175000017500000001147313066736044020521 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawEllipseArc (@var{arc}) ## Draw an ellipse arc on the current axis. ## ## drawEllipseArc(ARC) ## draw ellipse arc specified by ARC. ARC has the format: ## ARC = [XC YC A B THETA T1 T2] ## or: ## ARC = [XC YC A B T1 T2] (isothetic ellipse) ## with center (XC, YC), main axis of half-length A, second axis of ## half-length B, and ellipse arc running from t1 to t2 (both in degrees, ## in Counter-Clockwise orientation). ## ## Parameters can also be arrays. In this case, all arrays are suposed to ## have the same size... ## ## @example ## # draw an ellipse arc: center = [10 20], radii = 50 and 30, theta = 45 ## arc = [10 20 50 30 45 -90 270]; ## figure; ## axis([-50 100 -50 100]); axis equal; ## hold on ## drawEllipseArc(arc, 'color', 'r') ## ## # draw another ellipse arc, between angles -60 and 70 ## arc = [10 20 50 30 45 -60 (60+70)]; ## figure; ## axis([-50 100 -50 100]); axis equal; ## hold on ## drawEllipseArc(arc, 'LineWidth', 2); ## ray1 = createRay([10 20], deg2rad(-60+45)); ## drawRay(ray1) ## ray2 = createRay([10 20], deg2rad(70+45)); ## drawRay(ray2) ## @end example ## ## @seealso{ellipses2d, drawEllipse, drawCircleArc} ## @end deftypefn function varargout = drawEllipseArc(varargin) ## Extract input arguments # extract dawing style strings styles = {}; for i = 1:length(varargin) if ischar(varargin{i}) styles = varargin(i:end); varargin(i:end) = []; break; end end if length(varargin)==1 ellipse = varargin{1}; x0 = ellipse(1); y0 = ellipse(2); a = ellipse(3); b = ellipse(4); if size(ellipse, 2)>6 theta = ellipse(5); start = ellipse(6); extent = ellipse(7); else theta = zeros(size(x0)); start = ellipse(5); extent = ellipse(6); end elseif length(varargin)>=6 x0 = varargin{1}; y0 = varargin{2}; a = varargin{3}; b = varargin{4}; if length(varargin)>6 theta = varargin{5}; start = varargin{6}; extent = varargin{7}; else theta = zeros(size(x0)); start = varargin{5}; extent = varargin{6}; end else error('drawellipse: please specify center x, center y and radii a and b'); end ## Drawing # allocate memory for handles h = zeros(size(x0)); for i = 1:length(x0) # start and end angles t1 = deg2rad(start); t2 = t1 + deg2rad(extent); # vertices of ellipse t = linspace(t1, t2, 60); # convert angles to ellipse parametrisation sup = cos(t) > 0; t(sup) = atan(a(i) / b(i) * tan(t(sup))); t(~sup) = atan2(a(i) / b(i) * tan(2*pi - t(~sup)), -1); t = mod(t, 2*pi); # precompute cos and sin of theta (given in degrees) cot = cosd(theta(i)); sit = sind(theta(i)); # compute position of points xt = x0(i) + a(i)*cos(t)*cot - b(i)*sin(t)*sit; yt = y0(i) + a(i)*cos(t)*sit + b(i)*sin(t)*cot; h(i) = plot(xt, yt, styles{:}); end ## Process output arguments if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/mergeBoxes.m0000644000000000000000000000013213066736044017536 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/mergeBoxes.m0000644000175000017500000000506113066736044017714 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{box} =} mergeBoxes (@var{box1}, @var{box2}) ## Merge two boxes, by computing their greatest extent. ## # Example ## ## @example ## box1 = [5 20 5 30]; ## box2 = [0 15 0 15]; ## mergeBoxes(box1, box2) ## ans = ## 0 20 0 30 ## @end example ## ## @seealso{boxes2d, drawBox, intersectBoxes} ## @end deftypefn function bb = mergeBoxes(box1, box2) # unify sizes of data if size(box1,1) == 1 box1 = repmat(box1, size(box2,1), 1); elseif size(box2, 1) == 1 box2 = repmat(box2, size(box1,1), 1); elseif size(box1,1) != size(box2,1) error('geom2d:Error', 'Bad size for inputs'); end # compute extreme coords mini = min(box1(:,[1 3]), box2(:,[1 3])); maxi = max(box1(:,[2 4]), box2(:,[2 4])); # concatenate result into a new box structure bb = [mini(:,1) maxi(:,1) mini(:,2) maxi(:,2)]; endfunction %!test %! box1 = [5 20 10 25]; %! box2 = [0 15 15 20]; %! res = [0 20 10 25]; %! bb = mergeBoxes(box1, box2); %! assert (res, bb, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/orthogonalLine.m0000644000000000000000000000013213066736044020422 xustar0030 mtime=1490795556.600869618 30 atime=1490795556.600869618 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/orthogonalLine.m0000644000175000017500000000446413066736044020606 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{perp} = } orthogonalLine (@var{line}, @var{point}) ## Create a line orthogonal to another one. # # Returns the line orthogonal to the line @var{line} and going through the # point given by @var{point}. Directed angle from @var{line} to @var{perp} is pi/2. # @var{line} is given as [x0 y0 dx dy] and @var{point} is [xp yp]. # # @seealso{lines2d, parallelLine} ## @end deftypefn function res = orthogonalLine(line, point) N = max(size(point, 1), size(line, 1)); if size(point, 1)>1 res = point; else res = ones(N, 1)*point; end if size(line, 1)>1 res(:,3) = -line(:,4); res(:,4) = line(:,3); else res(:,3) = -ones(N,1)*line(4); res(:,4) = ones(N,1)*line(3); end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/angleDiff.m0000644000000000000000000000013213066736044017315 xustar0030 mtime=1490795556.564868952 30 atime=1490795556.564868952 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/angleDiff.m0000644000175000017500000000502713066736044017475 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{dif} =} angleDiff (@var{angle1}, @var{angle2}) ## Difference between two angles ## ## Computes the signed angular difference between two angles in radians. ## The result is comprised between -PI and +PI. ## ## Example ## A = angleDiff(-pi/4, pi/4) ## A = ## 1.5708 # equal to pi/2 ## A = angleDiff(pi/4, -pi/4) ## A = ## -1.5708 # equal to -pi/2 ## ## @seealso{angles2d, angleAbsDiff} ## @end deftypefn function dif = angleDiff(angle1, angle2) # first, normalization angle1 = normalizeAngle(angle1); angle2 = normalizeAngle(angle2); # compute difference and normalize in [-pi pi] dif = normalizeAngle(angle2 - angle1, 0); endfunction %!test %! dif = angleDiff(0, pi/2); %! assert (pi/2, dif, 1e-6); %!test %! dif = angleDiff(pi/2, 0); %! assert (-pi/2, dif, 1e-6); %!test %! dif = angleDiff(0, 3*pi/2); %! assert (-pi/2, dif, 1e-6); %!test %! dif = angleDiff(3*pi/2, 0); %! assert (pi/2, dif, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isParallel.m0000644000000000000000000000013213066736044017526 xustar0030 mtime=1490795556.592869469 30 atime=1490795556.592869469 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isParallel.m0000644000175000017500000000634113066736044017706 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isParallel (@var{v1}, @var{v2}) ## @deftypefnx {Function File} {@var{b} = } isParallel (@var{v1}, @var{v2},@var{tol}) ## Check parallelism of two vectors ## ## @var{v1} and @var{v2} are 2 row vectors of length Nd, Nd being the dimension, ## returns @code{true} if the vectors are parallel, and @code{false} otherwise. ## ## Also works when @var{v1} and @var{v2} are two [NxNd] arrays with same number of ## rows. In this case, return a [Nx1] array containing @code{true} at the positions ## of parallel vectors. ## ## @var{tol} specifies the accuracy of numerical computation. Default value is 1e-14. ## ## Example ## ## @example ## isParallel([1 2], [2 4]) ## ans = ## 1 ## isParallel([1 2], [1 3]) ## ans = ## 0 ## @end example ## ## @seealso{vectors2d, isPerpendicular, lines2d} ## @end deftypefn ## FIXME or erase me ## Also works when one of @var{v1} or @var{v2} is scalar and the other one is [NxNd] ## array, in this case return [Nx1] results. function b = isParallel(v1, v2, varargin) # default accuracy acc = 1e-14; if ~isempty(varargin) acc = abs(varargin{1}); end # adapt size of inputs if needed n1 = size(v1, 1); n2 = size(v2, 1); if n1 ~= n2 if n1 == 1 v1 = v1(ones(n2,1), :); elseif n2 == 1 v2 = v2(ones(n1,1), :); end end # performs computation if size(v1, 2) == 2 b = abs(v1(:, 1) .* v2(:, 2) - v1(:, 2) .* v2(:, 1)) < acc; else # computation in space b = vectorNorm(cross(v1, v2, 2)) < acc; end endfunction %!assert (isParallel ([1 2], [2 4])) %!assert (!isParallel ([1 2], [1 3])) %!error (isParallel (3, rand(4,2))) geometry-3.0.0/inst/geom2d/PaxHeaders.28738/createRay.m0000644000000000000000000000013213066736044017355 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/createRay.m0000644000175000017500000000666113066736044017542 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} { @var{ray} = } createRay (@var{point}, @var{angle}) ## @deftypefnx {Function File} { @var{ray} = } createRay (@var{x0},@var{y0}, @var{angle}) ## @deftypefnx {Function File} { @var{ray} = } createRay (@var{p1}, @var{p2}) ## Create a ray (half-line), from various inputs. ## ## A Ray is represented in a parametric form: [x0 y0 dx dy]. ## x = x0 + t*dx ## y = y0 + t*dy; ## for all t>0. ## ## @var{point} is a Nx2 array giving the starting point of the ray, and @var{angle} is the ## orientation of the ray respect to the positive x-axis. The ray origin can be specified with 2 input arguments @var{x0},@var{y0}. ## ## If two points @var{p1}, @var{p2} are given, creates a ray starting from point @var{p1} and going in the direction of point ## @var{p2}. ## ## Example ## @example ## origin = [3 4]; ## theta = pi/6; ## ray = createRay(origin, theta); ## axis([0 10 0 10]); ## drawRay(ray); ## @end example ## ## @seealso{rays2d, createLine, points2d} ## @end deftypefn function ray = createRay(varargin) if length(varargin)==2 p0 = varargin{1}; arg = varargin{2}; if size(arg, 2)==1 # second input is the ray angle ray = [p0 cos(arg) sin(arg)]; else # second input is another point ray = [p0 arg-p0]; end elseif length(varargin)==3 x = varargin{1}; y = varargin{2}; theta = varargin{3}; ray = [x y cos(theta) sin(theta)]; else error("Wrong number of arguments in 'createRay'. "); end endfunction %!shared p1,p2,ray %! p1 = [1 1]; %! p2 = [2 3]; %! ray = createRay(p1, p2); %!assert (p1, ray(1,1:2), 1e-6); %!assert (p2-p1, ray(1,3:4), 1e-6); %!shared p1,p2,ray %! p1 = [1 1;1 1]; %! p2 = [2 3;2 4]; %! ray = createRay(p1, p2); %!assert (2, size(ray, 1)); %!assert (p1, ray(:,1:2), 1e-6); %!assert (p2-p1, ray(:,3:4), 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/crackPattern2.m0000644000000000000000000000013213066736044020141 xustar0030 mtime=1490795556.572869099 30 atime=1490795556.572869099 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/crackPattern2.m0000644000175000017500000001261713066736044020324 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{e} = } crackPattern2 (@var{box}, @var{points}, @var{alpha}) ## Create a (bounded) crack pattern tessellation ## ## E = crackPattern2(BOX, POINTS, ALPHA) ## create a crack propagation pattern wit following parameters : ## - pattern is bounded by area BOX which is a polygon. ## - each crack originates from points given in POINTS ## - directions of each crack is given by a [NxM] array ALPHA, where M is ## the number of rays emanating from each seed/ ## - a crack stop when it reaches another already created crack. ## - all cracks stop when they reach the border of the frame, given by box ## (a serie of 4 points). ## The result is a collection of edges, in the form [x1 y1 x2 y2]. ## ## E = crackPattern2(BOX, POINTS, ALPHA, SPEED) ## Also specify speed of propagation of each crack. ## ## ## See the result with : ## figure; ## drawEdge(E); ## ## @seealso{drawEdge} ## @end deftypefn function edges = crackPattern2(box, points, alpha, varargin) if ~isempty(varargin) speed = varargin{1}; else speed = ones(size(points, 1), 1); end # Compute line equations for each initial crack. # The 'Inf' at the end correspond to the position of the limit. # If an intersection point is found with another line, but whose position # is after this value, this means that another crack stopped it before it # reach the intersection point. NP = size(points, 1); lines = zeros(0, 5); for i=1:size(alpha, 2) lines = [lines; points speed.*cos(alpha(:,i)) speed.*sin(alpha(:,i)) Inf*ones(NP, 1)]; end NL = size(lines, 1); # initialize lines for borders, but assign a very high speed, to be sure # borders will stop all cracks. dx = (box([2 3 4 1],1)-box([1 2 3 4],1))*max(speed)*5; dy = (box([2 3 4 1],2)-box([1 2 3 4],2))*max(speed)*5; # add borders to the lines set lines = [lines ; createLine(box, dx, dy) Inf*ones(4,1)]; edges = zeros(0, 4); while true modif = 0; # try to update each line for i=1:NL # initialize first point of edge edges(i, 1:2) = lines(i, 1:2); # compute intersections with all other lines pi = intersectLines(lines(i,:), lines); # compute position of all intersection points on the current line pos = linePosition(pi, lines(i,:)); # consider points to the right (positive position), and sort them indr = find(pos>1e-12 & pos~=Inf); [posr, indr2] = sort(pos(indr)); # look for the closest intersection to the right for i2=1:length(indr2) # index of intersected line il = indr(indr2(i2)); # position of point relative to intersected line pos2 = linePosition(pi(il, :), lines(il, :)); # depending on the sign of position, tests if the line2 can # stop the current line, or if it was stopped before if pos2>0 if pos2 ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawEdge (@var{x1}, @var{y1}, @var{x2}, @var{y2}) ## @deftypefnx {Function File} {@var{h} = } drawEdge ([@var{x1} @var{y1} @var{x2} @var{y2}]) ## @deftypefnx {Function File} {@var{h} = } drawEdge ([@var{x1} @var{y1}], [@var{x2} @var{y2}]) ## @deftypefnx {Function File} {@var{h} = } drawEdge (@var{x1}, @var{y1}, @var{z1}, @var{x2}, @var{y2}, @var{z2}) ## @deftypefnx {Function File} {@var{h} = } drawEdge ([@var{x1} @var{y1} @var{z1} @var{x2} @var{y2} @var{z2}]) ## @deftypefnx {Function File} {@var{h} = } drawEdge ([@var{x1} @var{y1} @var{z1}], [@var{x2} @var{y2} @var{z2}]) ## @deftypefnx {Function File} {@var{h} = } drawEdge (@dots{}, @var{opt}) ## Draw an edge given by 2 points. ## ## Draw an edge between the points (x1 y1) and (x2 y2). Data can be bundled as an edge. ## The function supports 3D edges. ## Arguments can be single values or array of size [Nx1]. In this case, ## the function draws multiple edges. ## @var{opt}, being a set of pairwise options, can ## specify color, line width and so on. These are passed to function @code{line}. ## The function returns handle(s) to created edges(s). ## ## @seealso{edges2d, drawCenteredEdge, drawLine, line} ## @end deftypefn function varargout = drawEdge(varargin) # separate edge and optional arguments [edge options] = parseInputArguments(varargin{:}); # draw the edges if size(edge, 2)==4 h = drawEdge_2d(edge, options); else h = drawEdge_3d(edge, options); end # eventually return handle to created edges if nargout>0 varargout{1}=h; end endfunction function h = drawEdge_2d(edge, options) h = -1*ones(size(edge, 1), 1); for i=1:size(edge, 1) if isnan(edge(i,1)) continue; end h(i) = line(... [edge(i, 1) edge(i, 3)], ... [edge(i, 2) edge(i, 4)], options{:}); end endfunction function h = drawEdge_3d(edge, options) h = -1*ones(size(edge, 1), 1); for i=1:size(edge, 1) if isnan(edge(i,1)) continue; end h(i) = line( ... [edge(i, 1) edge(i, 4)], ... [edge(i, 2) edge(i, 5)], ... [edge(i, 3) edge(i, 6)], options{:}); end endfunction function [edge options] = parseInputArguments(varargin) # default values for parameters edge = []; # find the number of arguments defining edges nbVal=0; for i=1:nargin if isnumeric(varargin{i}) nbVal = nbVal+1; else # stop at the first non-numeric value break; end end # extract drawing options options = varargin(nbVal+1:end); # ensure drawing options have correct format if length(options)==1 options = [{'color'}, options]; end # extract edges characteristics if nbVal==1 # all parameters in a single array edge = varargin{1}; elseif nbVal==2 # parameters are two points, or two arrays of points, of size N*2. p1 = varargin{1}; p2 = varargin{2}; edge = [p1 p2]; elseif nbVal==4 # parameters are 4 parameters of the edge : x1 y1 x2 and y2 edge = [varargin{1} varargin{2} varargin{3} varargin{4}]; elseif nbVal==6 # parameters are 6 parameters of the edge : x1 y1 z1 x2 y2 and z2 edge = [varargin{1} varargin{2} varargin{3} varargin{4} varargin{5} varargin{6}]; end endfunction %!demo %! close %! points = rand(4,4); %! colorstr = 'rgbm'; %! for i=1:4 %! drawEdge (points(i,:),'color',colorstr(i),'linewidth',2); %! end %! axis tight; %!demo %! close %! drawEdge (rand(10,4),'linewidth',2); %! axis tight; geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawEllipse.m0000644000000000000000000000013213066736044017711 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawEllipse.m0000644000175000017500000001123313066736044020065 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } drawEllipse (@var{elli}) ## @deftypefnx {Function File} {@var{h} = } drawEllipse (@var{xc}, @var{yc}, @var{ra}, @var{rb}) ## @deftypefnx {Function File} {@var{h} = } drawEllipse (@var{xc}, @var{yc}, @var{ra}, @var{rb}, @var{theta}) ## @deftypefnx {Function File} {@var{h} = } drawEllipse (@dots{}, @var{param}, @var{value}) ## Draw an ellipse on the current axis. ## ## drawEllipse(ELLI); ## Draws the ellipse ELLI in the form [XC YC RA RB THETA], with center ## (XC, YC), with main axis of half-length RA and RB, and orientation ## THETA in degrees counted counter-clockwise. ## Puts all parameters into one single array. ## ## drawEllipse(XC, YC, RA, RB); ## drawEllipse(XC, YC, RA, RB, THETA); ## Specifies ellipse parameters as separate arguments (old syntax). ## ## drawEllipse(..., NAME, VALUE); ## Specifies drawing style of ellipse, see the help of plot function. ## ## H = drawEllipse(...); ## Also returns handles to the created line objects. ## ## -> Parameters can also be arrays. In this case, all arrays are supposed ## to have the same size. ## ## Example: ## @example ## # Draw an ellipse centered in [50 50], with semi major axis length of ## # 40, semi minor axis length of 20, and rotated by 30 degrees. ## figure(1); clf; hold on; ## drawEllipse([50 50 40 20 30]); ## axis equal; ## @end example ## ## @seealso{ellipses2d, drawCircle, drawEllipseArc, ellipseAsPolygon} ## @end deftypefn function varargout = drawEllipse(varargin) # extract dawing style strings styles = {}; for i = 1:length(varargin) if ischar(varargin{i}) styles = varargin(i:end); varargin(i:end) = []; break; end end # extract ellipse parameters if length(varargin)==1 # ellipse is given in a single array ellipse = varargin{1}; x0 = ellipse(:, 1); y0 = ellipse(:, 2); a = ellipse(:, 3); b = ellipse(:, 4); if length(ellipse)>4 theta = ellipse(:, 5); else theta = zeros(size(x0)); end elseif length(varargin)>=4 # ellipse parameters given as separate arrays x0 = varargin{1}; y0 = varargin{2}; a = varargin{3}; b = varargin{4}; if length(varargin)>4 theta = varargin{5}; else theta = zeros(size(x0)); end else error('drawEllipse: incorrect input arguments'); end ## Process drawing of a set of ellipses # angular positions of vertices t = linspace(0, 2*pi, 145); # compute position of points to draw each ellipse h = zeros(length(x0), 1); for i = 1:length(x0) # pre-compute rotation angles (given in degrees) cot = cosd(theta(i)); sit = sind(theta(i)); # compute position of points used to draw current ellipse xt = x0(i) + a(i) * cos(t) * cot - b(i) * sin(t) * sit; yt = y0(i) + a(i) * cos(t) * sit + b(i) * sin(t) * cot; # stores handle to graphic object h(i) = plot(xt, yt, styles{:}); end # return handles if required if nargout > 0 varargout = {h}; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/transformPoint.m0000644000000000000000000000013213066736044020463 xustar0030 mtime=1490795556.608869765 30 atime=1490795556.608869765 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/transformPoint.m0000644000175000017500000000641613066736044020646 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pt2} = } transformPoint (@var{pt1}, @var{Trans}) ## @deftypefnx {Function File} {[@var{px2} @var{py2}]= } transformPoint (@var{px1}, @var{py1}, @var{Trans}) ## Transform a point with an affine transform. ## ## where @var{pt1} has the form [xp yp], and @var{Trans} is a [2x2], [2x3] or [3x3] ## matrix, returns the point transformed with affine transform @var{Trans}. ## ## Format of @var{Trans} can be one of : ## [a b] , [a b c] , or [a b c] ## [d e] [d e f] [d e f] ## [0 0 1] ## ## Also works when @var{pt1} is a [Nx2] array of double. In this case, @var{pt2} has ## the same size as @var{pt1}. ## ## Also works when @var{px1} and @var{py1} are arrays the same size. The function ## transform each couple of (@var{px1}, @var{py1}), and return the result in ## (@var{px2}, @var{py2}), which is the same size as (@var{px1} @var{py1}). ## ## @seealso{points2d, transforms2d, createTranslation, createRotation} ## @end deftypefn function varargout = transformPoint(varargin) if length(varargin)==2 var = varargin{1}; px = var(:,1); py = var(:,2); trans = varargin{2}; elseif length(varargin)==3 px = varargin{1}; py = varargin{2}; trans = varargin{3}; else error('wrong number of arguments in "transformPoint"'); end # compute position px2 = px*trans(1,1) + py*trans(1,2); py2 = px*trans(2,1) + py*trans(2,2); # add translation vector, if exist if size(trans, 2)>2 px2 = px2 + trans(1,3); py2 = py2 + trans(2,3); end if nargout==0 || nargout==1 varargout{1} = [px2 py2]; elseif nargout==2 varargout{1} = px2; varargout{2} = py2; end endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/intersectBoxes.m0000644000000000000000000000013213066736044020437 xustar0030 mtime=1490795556.588869395 30 atime=1490795556.588869395 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/intersectBoxes.m0000644000175000017500000000506013066736044020614 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{box} =} intersectBoxes (@var{box1}, @var{box2}) ## Intersection of two bounding boxes. ## ## Example ## ## @example ## box1 = [5 20 5 30]; ## box2 = [0 15 0 15]; ## intersectBoxes(box1, box2) ## ans = ## 5 15 5 15 ## @end example ## ## @seealso{boxes2d, drawBox, mergeBoxes} ## @end deftypefn function bb = intersectBoxes(box1, box2) # unify sizes of data if size(box1,1) == 1 box1 = repmat(box1, size(box2,1), 1); elseif size(box2, 1) == 1 box2 = repmat(box2, size(box1,1), 1); elseif size(box1,1) != size(box2,1) error('geom2d:Error',"Bad size for inputs.\n"); end # compute extreme coords mini = min(box1(:,[2 4]), box2(:,[2 4])); maxi = max(box1(:,[1 3]), box2(:,[1 3])); # concatenate result into a new box structure bb = [maxi(:,1) mini(:,1) maxi(:,2) mini(:,2)]; endfunction %!test %! box1 = [5 20 10 25]; %! box2 = [0 15 15 20]; %! res = [5 15 15 20]; %! bb = intersectBoxes(box1, box2); %! assert (res, bb, 1e-6); geometry-3.0.0/inst/geom2d/PaxHeaders.28738/isPointOnLine.m0000644000000000000000000000013213066736044020170 xustar0030 mtime=1490795556.596869544 30 atime=1490795556.596869544 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/isPointOnLine.m0000644000175000017500000000516213066736044020350 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{b} = } isPointOnLine (@var{point}, @var{line}) ## Test if a point belongs to a line ## ## B = isPointOnLine(POINT, LINE) ## with POINT being [xp yp], and LINE being [x0 y0 dx dy]. ## Returns 1 if point lies on the line, 0 otherwise. ## ## If POINT is an N*2 array of points, B is a N*1 array of booleans. ## ## If LINE is a N*4 array of line, B is a 1*N array of booleans. ## ## @seealso {lines2d, points2d, isPointOnEdge, isPointOnRay, angle3Points} ## @end deftypefn function b = isPointOnLine(point, line, varargin) # extract computation tolerance tol = 1e-14; if ~isempty(varargin) tol = varargin{1}; end # number of lines and of points Nl = size(line, 1); Np = size(point, 1); # adapt the size of inputs x0 = repmat(line(:,1)', Np, 1); y0 = repmat(line(:,2)', Np, 1); dx = repmat(line(:,3)', Np, 1); dy = repmat(line(:,4)', Np, 1); xp = repmat(point(:,1), 1, Nl); yp = repmat(point(:,2), 1, Nl); # test if lines are colinear b = abs((xp-x0).*dy-(yp-y0).*dx)./hypot(dx, dy) < tol; endfunction geometry-3.0.0/inst/geom2d/PaxHeaders.28738/drawOrientedBox.m0000644000000000000000000000013213066736044020536 xustar0030 mtime=1490795556.580869248 30 atime=1490795556.580869248 30 ctime=1490795556.716871764 geometry-3.0.0/inst/geom2d/drawOrientedBox.m0000644000175000017500000000706213066736044020717 0ustar00olafolaf00000000000000## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{hb} = } drawOrientedBox (@var{box}) ## @deftypefnx {Function File} {@var{hb} = } drawOrientedBox (@dots{}, @var{param}, @var{value}) ## Draw centered oriented rectangle. ## ## Syntax ## drawOrientedBox(BOX) ## drawOrientedBox(BOX, 'PropertyName', propertyvalue, ...) ## ## Description ## drawOrientedBox(OBOX) ## Draws an oriented rectangle (or bounding box) on the current axis. ## OBOX is a 1-by-5 row vector containing box center, dimension (length ## and width) and orientation (in degrees): ## OBOX = [CX CY LENGTH WIDTH THETA]. ## ## When OBOX is a N-by-5 array, the N boxes are drawn. ## ## HB = drawOrientedBox(...) ## Returns a handle to the created graphic object(s). Object style can be ## modified using syntaw like: ## set(HB, 'color', 'g', 'linewidth', 2); ## ## @seealso{drawPolygon, drawRect, drawBox} ## @end deftypefn function varargout = drawOrientedBox(box, varargin) ## Parses input arguments if nargin > 4 && sum(cellfun(@isnumeric, varargin(1:4))) == 4 cx = box; cy = varargin{1}; hl = varargin{2} / 2; hw = varargin{3} / 2; theta = varargin{4}; varargin = varargin(5:end); else cx = box(:,1); cy = box(:,2); hl = box(:,3) / 2; hw = box(:,4) / 2; theta = box(:,5); end ## Draw each box # allocate memory for graphical handle hr = zeros(length(cx), 1); # iterate on oriented boxes for i = 1:length(cx) # pre-compute angle data cot = cosd(theta(i)); sit = sind(theta(i)); # x and y shifts lc = hl(i) * cot; ls = hl(i) * sit; wc = hw(i) * cot; ws = hw(i) * sit; # coordinates of box vertices vx = cx(i) + [-lc + ws; lc + ws ; lc - ws ; -lc - ws ; -lc + ws]; vy = cy(i) + [-ls - wc; ls - wc ; ls + wc ; -ls + wc ; -ls - wc]; # draw polygons hr(i) = line(vx, vy, varargin{:}); end ## Format output if nargout > 0 varargout = {hr}; end endfunction geometry-3.0.0/inst/PaxHeaders.28738/io0000644000000000000000000000013213066736044014435 xustar0030 mtime=1490795556.648870505 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/0002755000175000017500000000000013066736044014670 5ustar00olafolaf00000000000000geometry-3.0.0/inst/io/PaxHeaders.28738/@svg0000644000000000000000000000013213066736044015334 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/0002755000175000017500000000000013066736044015567 5ustar00olafolaf00000000000000geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/getpath.m0000644000000000000000000000013213066736044017223 xustar0030 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/getpath.m0000644000175000017500000000376213066736044017407 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{paths} = } getpath (@var{ids}) ## Returns paths in @var{ids}. ## ## @end deftypefn function paths = getpath(obj, varargin) if !isempty(varargin) ids = varargin; if iscell (ids) && numel(ids) == 1 && iscell(ids{1}) # dealing with ids given as cell ids = ids{1}; if !all ( cellfun (@ischar, ids) ) print_usage end elseif !all ( cellfun (@ischar, ids) ) print_usage end else paths = obj.Path; return end tf = ismember (ids, fieldnames (obj.Path)); cellfun (@(s) printf("'#s' is not a valid path id.\n", s) , {ids{!tf}}); paths = []; if any (tf) stuff = {ids{tf}}; for i = 1: numel(stuff) paths{i} = obj.Path.(ids{i}).data; endfor # Variation # paths = cellfun(@(s) obj.Path.(s).data, stuff,'UniformOutput',false); # Another variation # paths = cellfun(@(s) getfield(obj,'Path').(s).data, stuff,'UniformOutput',false); # Yet another # paths = cellfun(@(s) getfield(obj.Path,s).data, stuff,'UniformOutput',false); # Yet yet another # dummy = @(s) obj.Path.(s).data; # paths = cellfun(dummy, stuff,'UniformOutput',false); if numel(paths) == 1 paths = paths{1}; end end endfunction geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/normalize.m0000644000000000000000000000013213066736044017567 xustar0030 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/normalize.m0000644000175000017500000000567113066736044017754 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{SVGn} = normalize (@var{SVG}) ## normalizes and SVG. ## @end deftypefn function [SVGn bb] = normalize (obj) SVGn = obj; bb = []; if ! obj.Data.normalized ids = fieldnames (obj.Path); npath = numel(ids); v = zeros(npath,2); bb = zeros(1,4); for ip = 1:npath v(ip,:) = shapeCentroid(obj.Path.(ids{ip}).data); p = shape2polygon(obj.Path.(ids{ip}).data); bb = mergeBoxes(bb, [min(p) max(p)]([1 3 2 4])); end if npath > 1 v = mean(v)(:); else v = v.'; end ## check whether document and bounding box agree. bbHeight = bb(2)-bb(1); bbWidth = bb(4)-bb(2); if obj.Data.height != bbHeight warning("svg:normalize:Sanitycheck",... ["Height of SVG #g and height boundingbox #g don't match.\n" ... "Using bounding box.\n"],obj.Data.height,bbHeight) end if obj.Data.width != bbWidth warning("svg:normalize:Sanitycheck",... ["Width of SVG #g and width boundingbox #g don't match.\n" ... "Using bounding box.\n"],obj.Data.width,bbWidth) end ## Move paths such that center of SVG is at 0,0 ## Put coordinates in the usual frame ## Scale such that diagonal of bounding box is 1 Dnorm = sqrt (bbWidth ^ 2 + bbHeight ^ 2); S = (1 / Dnorm) * eye (2); bb = zeros(1,4); for ip = 1:npath SVGn.Path.(ids{ip}).data = shapetransform(obj.Path.(ids{ip}).data,-v); # Put to middle SVGn.Path.(ids{ip}).data = ... shapetransform(SVGn.Path.(ids{ip}).data,[0; -bbHeight/2]); # Reflect y SVGn.Path.(ids{ip}).data = ... shapetransform(SVGn.Path.(ids{ip}).data,[1 0;0 -1]); # Put to bottom SVGn.Path.(ids{ip}).data = ... shapetransform(SVGn.Path.(ids{ip}).data,[0; bbHeight/2]); # Scale SVGn.Path.(ids{ip}).data = ... shapetransform(SVGn.Path.(ids{ip}).data,S); p = shape2polygon(SVGn.Path.(ids{ip}).data); bb = mergeBoxes(bb, [min(p) max(p)]([1 3 2 4])); end bbHeight = bb(2)-bb(1); bbWidth = bb(4)-bb(2); SVGn.Data.height = bbHeight; SVGn.Data.width = bbWidth; SVGn.Data.normalized = true; end end geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/parseSVGData.py0000644000000000000000000000013213066736044020247 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/parseSVGData.py0000644000175000017500000000232413066736044020424 0ustar00olafolaf00000000000000#!/usr/bin/env python ## Copyright (c) 2012 Juan Pablo Carbajal ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . import inkex import sys #import getopt def parseSVGData (filen=None): svg = inkex.Effect () svg.parse (filen) root = svg.document.xpath ('//svg:svg', namespaces=inkex.NSS) print 'data = struct("height",{0},"width",{1},"id","{2}");' \ .format(root[0].attrib['height'],root[0].attrib['width'], root[0].attrib['id']) # ---------------------------- if __name__=="__main__": svg = sys.argv[1] parseSVGData(svg) geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/pathid.m0000644000000000000000000000013213066736044017040 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/pathid.m0000644000175000017500000000156213066736044017220 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function ids = pathid(obj,varargin) ids = fieldnames (obj.Path); endfunction geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/path2polygon.m0000644000000000000000000000013213066736044020215 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/path2polygon.m0000644000175000017500000000325513066736044020376 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{P} = path2polygon (@var{id}) ## Converts the SVG path to an array of polygons. ## ## @end deftypefn function P = path2polygon (obj,varargin) narg = numel(varargin); if narg == 1 id = varargin{1}; n = 32; elseif narg == 2 id = varargin{1}; n = varargin{2}; else error("svg:path2polygon:InvalidArgument", "Wrong number of arguments."); end P = shape2polygon(getpath(obj, id)); endfunction #{ pd = obj.Path.(id).data; P = cellfun(@(x)convertpath(x,n),pd,'UniformOutput',false); P = cell2mat(P); end function p = convertpath(x,np) n = size(x,2); switch n case 2 p = zeros(2,2); # Straight segment p(:,1) = polyval (x(1,:), [0; 1]); p(:,2) = polyval (x(2,:), [0; 1]); case 4 p = zeros(np,2); # Cubic bezier t = linspace (0, 1, np).'; p(:,1) = polyval (x(1,:),t); p(:,2) = polyval (x(2,:),t); end end #} geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/loadpaths.m0000644000000000000000000000013213066736044017546 xustar0030 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/loadpaths.m0000644000175000017500000000532713066736044017731 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . function Paths = loadpaths (obj, svg, varargin) here = which ("@svg/loadpaths"); here = fileparts (here); script = fullfile (here, 'parsePath.py'); ## Call python script if exist (svg,'file') # read from file [st str]=system (sprintf ('python %s %s', script, svg)); else # inline SVG [st str]=system (sprintf ('python %s < %s', script, svg)); end ## Parse ouput strpath = strsplit (str(1:end-1), '$', true); npaths = numel (strpath); ## Convert path data to polynoms for ip = 1:npaths eval (strpath{ip}); ## FIXME: intialize struct with cell field svgpath2.cmd = svgpath(1).cmd; svgpath2.data = {svgpath.data}; nD = length(svgpath2.cmd); pathdata = cell (nD-1,1); point_end=[]; ## If the path is closed, last command is Z and we set initial point == final if svgpath2.cmd(end) == 'Z' nD -= 1; point_end = svgpath2.data{1}; svgpath2.data(end) = []; end ## Initial point points(1,:) = svgpath2.data{1}; for jp = 2:nD switch svgpath2.cmd(jp) case 'L' ## Straigth segment to polygon points(2,:) = svgpath2.data{jp}; pp = [(points(2,:)-points(1,:))' points(1,:)']; clear points points(1,:) = [polyval(pp(1,:),1) polyval(pp(2,:),1)]; case 'C' ## Cubic bezier to polygon points(2:4,:) = reshape (svgpath2.data{jp}, 2, 3).'; pp = cbezier2poly (points); clear points points(1,:) = [polyval(pp(1,:),1) polyval(pp(2,:),1)]; end pathdata{jp-1} = pp; end if ~isempty(point_end) ## Straight segment to close the path points(2,:) = point_end; pp = [(points(2,:)-points(1,:))' points(1,:)']; if all ( abs(pp(:,1)) < sqrt(eps) ) # Final point of last segment is already initial point pathdata(end) = []; else pathdata{end} = pp; end end ## TODO # pathdata = shapetransform(pathdata); Paths.(svgpathid).data = pathdata; end endfunction geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/simplepath.py0000644000000000000000000000013213066736044020131 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/simplepath.py0000644000175000017500000001546113066736044020314 0ustar00olafolaf00000000000000#!/usr/bin/env python """ simplepath.py functions for digesting paths into a simple list structure Copyright (C) 2005 Aaron Spike, aaron@ekips.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see . """ import re, math def lexPath(d): """ returns and iterator that breaks path data identifies command and parameter tokens """ offset = 0 length = len(d) delim = re.compile(r'[ \t\r\n,]+') command = re.compile(r'[MLHVCSQTAZmlhvcsqtaz]') parameter = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)') while 1: m = delim.match(d, offset) if m: offset = m.end() if offset >= length: break m = command.match(d, offset) if m: yield [d[offset:m.end()], True] offset = m.end() continue m = parameter.match(d, offset) if m: yield [d[offset:m.end()], False] offset = m.end() continue #TODO: create new exception raise Exception, 'Invalid path data!' ''' pathdefs = {commandfamily: [ implicitnext, #params, [casts,cast,cast], [coord type,x,y,0] ]} ''' pathdefs = { 'M':['L', 2, [float, float], ['x','y']], 'L':['L', 2, [float, float], ['x','y']], 'H':['H', 1, [float], ['x']], 'V':['V', 1, [float], ['y']], 'C':['C', 6, [float, float, float, float, float, float], ['x','y','x','y','x','y']], 'S':['S', 4, [float, float, float, float], ['x','y','x','y']], 'Q':['Q', 4, [float, float, float, float], ['x','y','x','y']], 'T':['T', 2, [float, float], ['x','y']], 'A':['A', 7, [float, float, float, int, int, float, float], ['r','r','a',0,'s','x','y']], 'Z':['L', 0, [], []] } def parsePath(d): """ Parse SVG path and return an array of segments. Removes all shorthand notation. Converts coordinates to absolute. """ retval = [] lexer = lexPath(d) pen = (0.0,0.0) subPathStart = pen lastControl = pen lastCommand = '' while 1: try: token, isCommand = lexer.next() except StopIteration: break params = [] needParam = True if isCommand: if not lastCommand and token.upper() != 'M': raise Exception, 'Invalid path, must begin with moveto.' else: command = token else: #command was omited #use last command's implicit next command needParam = False if lastCommand: if lastCommand.isupper(): command = pathdefs[lastCommand][0] else: command = pathdefs[lastCommand.upper()][0].lower() else: raise Exception, 'Invalid path, no initial command.' numParams = pathdefs[command.upper()][1] while numParams > 0: if needParam: try: token, isCommand = lexer.next() if isCommand: raise Exception, 'Invalid number of parameters' except StopIteration: raise Exception, 'Unexpected end of path' cast = pathdefs[command.upper()][2][-numParams] param = cast(token) if command.islower(): if pathdefs[command.upper()][3][-numParams]=='x': param += pen[0] elif pathdefs[command.upper()][3][-numParams]=='y': param += pen[1] params.append(param) needParam = True numParams -= 1 #segment is now absolute so outputCommand = command.upper() #Flesh out shortcut notation if outputCommand in ('H','V'): if outputCommand == 'H': params.append(pen[1]) if outputCommand == 'V': params.insert(0,pen[0]) outputCommand = 'L' if outputCommand in ('S','T'): params.insert(0,pen[1]+(pen[1]-lastControl[1])) params.insert(0,pen[0]+(pen[0]-lastControl[0])) if outputCommand == 'S': outputCommand = 'C' if outputCommand == 'T': outputCommand = 'Q' #current values become "last" values if outputCommand == 'M': subPathStart = tuple(params[0:2]) pen = subPathStart if outputCommand == 'Z': pen = subPathStart else: pen = tuple(params[-2:]) if outputCommand in ('Q','C'): lastControl = tuple(params[-4:-2]) else: lastControl = pen lastCommand = command retval.append([outputCommand,params]) return retval def formatPath(a): """Format SVG path data from an array""" return "".join([cmd + " ".join([str(p) for p in params]) for cmd, params in a]) def translatePath(p, x, y): for cmd,params in p: defs = pathdefs[cmd] for i in range(defs[1]): if defs[3][i] == 'x': params[i] += x elif defs[3][i] == 'y': params[i] += y def scalePath(p, x, y): for cmd,params in p: defs = pathdefs[cmd] for i in range(defs[1]): if defs[3][i] == 'x': params[i] *= x elif defs[3][i] == 'y': params[i] *= y elif defs[3][i] == 'r': # radius parameter params[i] *= x elif defs[3][i] == 's': # sweep-flag parameter if x*y < 0: params[i] = 1 - params[i] elif defs[3][i] == 'a': # x-axis-rotation angle if y < 0: params[i] = - params[i] def rotatePath(p, a, cx = 0, cy = 0): if a == 0: return p for cmd,params in p: defs = pathdefs[cmd] for i in range(defs[1]): if defs[3][i] == 'x': x = params[i] - cx y = params[i + 1] - cy r = math.sqrt((x**2) + (y**2)) if r != 0: theta = math.atan2(y, x) + a params[i] = (r * math.cos(theta)) + cx params[i + 1] = (r * math.sin(theta)) + cy # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99 geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/inkex.py0000644000000000000000000000013213066736044017101 xustar0030 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/inkex.py0000644000175000017500000002004413066736044017255 0ustar00olafolaf00000000000000#!/usr/bin/env python """ inkex.py A helper module for creating Inkscape extensions Copyright (C) 2005,2007 Aaron Spike, aaron@ekips.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see . """ import sys, copy, optparse, random, re import gettext from math import * _ = gettext.gettext #a dictionary of all of the xmlns prefixes in a standard inkscape doc NSS = { u'sodipodi' :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd', u'cc' :u'http://creativecommons.org/ns#', u'ccOLD' :u'http://web.resource.org/cc/', u'svg' :u'http://www.w3.org/2000/svg', u'dc' :u'http://purl.org/dc/elements/1.1/', u'rdf' :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#', u'inkscape' :u'http://www.inkscape.org/namespaces/inkscape', u'xlink' :u'http://www.w3.org/1999/xlink', u'xml' :u'http://www.w3.org/XML/1998/namespace' } #a dictionary of unit to user unit conversion factors uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'm':3543.3070866, 'km':3543307.0866, 'pc':15.0, 'yd':3240 , 'ft':1080} def unittouu(string): '''Returns userunits given a string representation of units in another system''' unit = re.compile('(%s)$' % '|'.join(uuconv.keys())) param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)') p = param.match(string) u = unit.search(string) if p: retval = float(p.string[p.start():p.end()]) else: retval = 0.0 if u: try: return retval * uuconv[u.string[u.start():u.end()]] except KeyError: pass return retval def uutounit(val, unit): return val/uuconv[unit] try: from lxml import etree except: sys.exit(_('The fantastic lxml wrapper for libxml2 is required by inkex.py and therefore this extension. Please download and install the latest version from http://cheeseshop.python.org/pypi/lxml/, or install it through your package manager by a command like: sudo apt-get install python-lxml')) def debug(what): sys.stderr.write(str(what) + "\n") return what def errormsg(msg): """Intended for end-user-visible error messages. (Currently just writes to stderr with an appended newline, but could do something better in future: e.g. could add markup to distinguish error messages from status messages or debugging output.) Note that this should always be combined with translation: import gettext _ = gettext.gettext ... inkex.errormsg(_("This extension requires two selected paths.")) """ sys.stderr.write((unicode(msg) + "\n").encode("UTF-8")) def check_inkbool(option, opt, value): if str(value).capitalize() == 'True': return True elif str(value).capitalize() == 'False': return False else: raise optparse.OptionValueError("option %s: invalid inkbool value: %s" % (opt, value)) def addNS(tag, ns=None): val = tag if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{': val = "{%s}%s" % (NSS[ns], tag) return val class InkOption(optparse.Option): TYPES = optparse.Option.TYPES + ("inkbool",) TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER) TYPE_CHECKER["inkbool"] = check_inkbool class Effect: """A class for creating Inkscape SVG Effects""" def __init__(self, *args, **kwargs): self.document=None self.ctx=None self.selected={} self.doc_ids={} self.options=None self.args=None self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption) self.OptionParser.add_option("--id", action="append", type="string", dest="ids", default=[], help="id attribute of object to manipulate") def effect(self): pass def getoptions(self,args=sys.argv[1:]): """Collect command line arguments""" self.options, self.args = self.OptionParser.parse_args(args) def parse(self,file=None): """Parse document in specified file or on stdin""" try: try: stream = open(file,'r') except: stream = open(self.svg_file,'r') except: stream = sys.stdin self.document = etree.parse(stream) stream.close() def getposinlayer(self): #defaults self.current_layer = self.document.getroot() self.view_center = (0.0,0.0) layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', namespaces=NSS) if layerattr: layername = layerattr[0] layer = self.document.xpath('//svg:g[@id="%s"]' % layername, namespaces=NSS) if layer: self.current_layer = layer[0] xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', namespaces=NSS) yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', namespaces=NSS) doc_height = unittouu(self.document.getroot().get('height')) if xattr and yattr: x = xattr[0] y = yattr[0] if x and y: self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape def getselected(self): """Collect selected nodes""" for i in self.options.ids: path = '//*[@id="%s"]' % i for node in self.document.xpath(path, namespaces=NSS): self.selected[i] = node def getElementById(self, id): path = '//*[@id="%s"]' % id el_list = self.document.xpath(path, namespaces=NSS) if el_list: return el_list[0] else: return None def getParentNode(self, node): for parent in self.document.getiterator(): if node in parent.getchildren(): return parent break def getdocids(self): docIdNodes = self.document.xpath('//@id', namespaces=NSS) for m in docIdNodes: self.doc_ids[m] = 1 def getNamedView(self): return self.document.xpath('//sodipodi:namedview', namespaces=NSS)[0] def createGuide(self, posX, posY, angle): atts = { 'position': str(posX)+','+str(posY), 'orientation': str(sin(radians(angle)))+','+str(-cos(radians(angle))) } guide = etree.SubElement( self.getNamedView(), addNS('guide','sodipodi'), atts ) return guide def output(self): """Serialize document into XML on stdout""" self.document.write(sys.stdout) def affect(self, args=sys.argv[1:], output=True): """Affect an SVG document with a callback effect""" self.svg_file = args[-1] self.getoptions(args) self.parse() self.getposinlayer() self.getselected() self.getdocids() self.effect() if output: self.output() def uniqueId(self, old_id, make_new_id = True): new_id = old_id if make_new_id: while new_id in self.doc_ids: new_id += random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') self.doc_ids[new_id] = 1 return new_id def xpathSingle(self, path): try: retval = self.document.xpath(path, namespaces=NSS)[0] except: errormsg(_("No matching node for expression: %s") % path) retval = None return retval # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99 geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/loadsvgdata.m0000644000000000000000000000013213066736044020060 xustar0030 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/loadsvgdata.m0000644000175000017500000000225613066736044020241 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . function data = loadsvgdata (obj, svg, varargin) here = which ("@svg/loadsvgdata"); here = fileparts (here); script = fullfile (here, 'parseSVGData.py'); ## Call python script if exist (svg,'file') # read from file [st str]=system (sprintf ('python %s %s', script, svg)); else # inline SVG [st str]=system (sprintf ('python %s < %s', script, svg)); end ## Parse ouput strdata = strsplit (str(1:end-1), '$', true); eval (strdata{1}); endfunction geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/parsePath.py0000644000000000000000000000013213066736044017712 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/parsePath.py0000644000175000017500000000421213066736044020065 0ustar00olafolaf00000000000000#!/usr/bin/env python ## Copyright (c) 2012 Juan Pablo Carbajal ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . import inkex, simplepath import sys #import getopt def parsePaths (filen=None): svg = inkex.Effect () svg.parse (filen) paths = svg.document.xpath ('//svg:path', namespaces=inkex.NSS) for path in paths: D = simplepath.parsePath (path.attrib['d']) cmdlst = []; parlst = []; for cmd,params in D: cmdlst.append(cmd) parlst.append(params) print 'svgpath = struct("cmd","{0}","data",{{{1}}});' \ .format(''.join(cmdlst),str(parlst).replace('[[','[').replace(']]',']')) print 'svgpathid = "{0}"; $'.format(path.attrib['id']) # ---------------------------- if __name__=="__main__": ''' try: optlist,args = getopt.getopt(sys.argv[1:],"thdp") except getopt.GetoptError: usage() sys.exit(2) doHelp = 0 c = Context() c.doPrint = 1 for opt in optlist: if opt[0] == "-d": c.debug = 1 if opt[0] == "-p": c.plot = 1 if opt[0] == "-t": c.triangulate = 1 if opt[0] == "-h": doHelp = 1 if not doHelp: pts = [] fp = sys.stdin if len(args) > 0: fp = open(args[0],'r') for line in fp: fld = line.split() x = float(fld[0]) y = float(fld[1]) pts.append(Site(x,y)) if len(args) > 0: fp.close() if doHelp or len(pts) == 0: usage() sys.exit(2) ''' svg = sys.argv[1] parsePaths(svg) geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/svg.m0000644000000000000000000000013213066736044016366 xustar0030 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 geometry-3.0.0/inst/io/@svg/svg.m0000644000175000017500000000475313066736044016553 0ustar00olafolaf00000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{obj} =} svg () ## @deftypefnx {Function File} {@var{obj} =} svg (@var{str}) ## Create object of the svg class. ## ## If no input argument is provided the object is empty. @var{str} can be a filename ## or a string defining an inline SVG. ## ## @end deftypefn function svg = svg(name='') svg = struct; ## SVG data. All the attributes of the node. ## The field unparsed contains all the attributes that are not being parsed. svg.Data = struct('height',[],'width',[],'id','null','normalized',false); ## SVG metadata. All the attributes of the node. ## The field unparsed contains all the attributes that are not being parsed. svg.Metadata = struct('unparsed',' '); ## SVG paths. It is a vector of path structs. Maybe path can be a object too? ## Order of Path.Data is important so we store in a cell (could be a matrix padded with zeros). ## All the paths stored in polyval compatible format. Straigth segments are also stored as a polynomial. svg.Path = struct(); svg = class (svg, 'svg'); if !isempty (name) if exist(name,"file") == 2 name = file_in_path(path(), name); else error("svg:BadArguemnt", "File %s doesn't exist",name); end svg.Path = loadpaths(svg, name); svg.Data = loadsvgdata(svg, name); svg.Data.normalized = false; elseif !ischar(name) print_usage ; endif endfunction %!test %! dc = svg('drawing5.svg'); %! dc.getpath(); %! dc.pathid(); %! dc.getpath('path3756'); %! %! dc = svg('drawing.svg'); %! ids = dc.pathid(); %! dc.getpath({ids{[1 3]}}); %!test %! dc = svg('drawing6.svg'); %! ids = dc.pathid(); %! P = dc.path2polygon(ids{1}); %!test %! dc = svg('drawing6.svg'); %! dc.plot(); %! dc.plot('color','r','linewidth',2); ���������������������geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/height.m�����������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017037� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/height.m����������������������������������������������������������������0000644�0001750�0001750�00000001550�13066736044�017214� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function o = height(obj,varargin) o = obj.Data.height; endfunction ��������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/display.m����������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017234� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/display.m���������������������������������������������������������������0000644�0001750�0001750�00000001543�13066736044�017413� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . function display (obj) fields = fieldnames (obj); for i = 1 : numel(fields) printf ("#s\n", fields{i}); obj.(fields{i}) end endfunction �������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/width.m������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016706� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/width.m�����������������������������������������������������������������0000644�0001750�0001750�00000001546�13066736044�017070� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function o = width(obj,varargin) o = obj.Data.width; endfunction ����������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/plot.m�������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016545� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/plot.m������������������������������������������������������������������0000644�0001750�0001750�00000002601�13066736044�016720� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } plot () ## Plots and SVG object. ## ## @end deftypefn function h = plot(obj, varargin) # Get path ids ids = fieldnames(obj.Path); npath = numel(ids); t = linspace (0, 1, 64); args={}; if !isempty (varargin) args = varargin; end holded = false; if ~ishold(gca) hold on; holded = true; end for i = 1:npath x = []; y = []; data = obj.Path.(ids{i}).data; for j = 1:numel(data) x = cat (2, x, polyval (data{j}(1,:),t)); y = cat (2, y, polyval (data{j}(2,:),t)); end h = plot(x,y,args{:}); end if holded hold off end axis tight axis equal endfunction �������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/PaxHeaders.28738/subsref.m����������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017240� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/@svg/subsref.m���������������������������������������������������������������0000644�0001750�0001750�00000004717�13066736044�017425� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function varargout = subsref (obj, idx) persistent __method__ method4field typeNotImplemented if isempty(__method__) __method__ = struct(); __method__.plot = @(o,varargin) plot (o, varargin{:}); __method__.getpath = @(o,varargin) getpath (o, varargin{:}); __method__.pathid = @(o,varargin) pathid(o,varargin{:}); __method__.path2polygon = @(o,varargin) path2polygon (o, varargin{:}); __method__.normalize = @(o,varargin) normalize (o, varargin{:}); __method__.height = @(o,varargin) height(o, varargin{:}); __method__.width = @(o,varargin) width(o,varargin{:}); # Error strings method4field = "Class #s has no field #s. Use #s() for the method."; typeNotImplemented = "#s no implemented for class #s."; end if ( !strcmp (class (obj), 'svg') ) error ("Object must be of the svg class but '#s' was used", class (obj) ); elseif ( idx(1).type != '.' ) error ("Invalid index for class #s", class (obj) ); endif method = idx(1).subs; if ~isfield(__method__, method) error('Unknown method #s.',method); else fhandle = __method__.(method); end if strcmp(method,'normalize') warning("svg:Devel",["Not returning second output argument of #s" ... " use method(obj) API to get it"],method); end if numel (idx) == 1 # can't access properties, only methods error (method4field, class (obj), method, method); end if strcmp (idx(2).type, '()') args = idx(2).subs; if isempty(args) out = fhandle (obj); else out = fhandle (obj, args{:}); end varargout{1} = out; else error (typeNotImplemented,[method idx(2).type], class (obj)); end endfunction �������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/drawing4.svg������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016752� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/drawing4.svg�����������������������������������������������������������������0000644�0001750�0001750�00000004070�13066736044�017127� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/drawing3.svg������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016751� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/drawing3.svg�����������������������������������������������������������������0000644�0001750�0001750�00000002052�13066736044�017124� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/data2geo.m��������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016356� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/data2geo.m�������������������������������������������������������������������0000644�0001750�0001750�00000007043�13066736044�016536� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 - Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {Function File} {@var{fileStr} =} data2geo (@var{data}, @var{lc}) ## @deftypefnx {Function File} {@var{fileStr} =} data2geo (@dots{}, @var{param}, @var{value}) ## Uses data to build a file compatible with Gmsh. ## ## @var{data} is assumed to describe a polygon in @code{polygon2d} format. ## The argument @var{lc} specifies the edge size. ## ## The optional parameters can be 'output' followed with a string specifying a file ## to write, and 'spherical' followed by a real number @var{r} indicating that the ## polygon describes a spherical surface of radious @var{r}. ## ## @seealso{polygon2d, @@svg/path2polygon} ## @end deftypefn function strFile = data2geo(data,lc,varargin) nl = @()sprintf('\n'); ## Parse options filegiven = []; spherical = []; if nargin > 2 filegiven = find(cellfun(@(x)strcmpi(x,'output'),varargin)); spherical = find(cellfun(@(x)strcmpi(x,'spherical'),varargin)); end [n dim] = size(data); if dim == 2 data(:,3) = zeros(n,1); end header = ' // File created with Octave'; strFile = [header nl()]; # Points strFile = [strFile '// Points' nl()]; for i=1:n strFile = [strFile pointGeo(i,data(i,:),lc)]; end # Lines strFile = [strFile '// Lines' nl()]; for i=1:n-1 strFile = [strFile lineGeo(i,i,i+1)]; end strFile = [strFile lineGeo(n,n,1)]; # Loop strFile = [strFile lineLoopGeo(n+1,n,1:n)]; # Surface if spherical sphr = varargin{spherical+1}; if dim ==2 sphr(1,3) = 0; end strFile = [strFile pointGeo(n+1,sphr,lc)]; strFile = [strFile ruledSurfGeo(n+3,1,n+1,n+1)]; else strFile = [strFile planeSurfGeo(n+2,1,n+1)]; end if filegiven outfile = varargin{filegiven+1}; fid = fopen(outfile,'w'); fprintf(fid,'%s',strFile); fclose(fid); disp(['DATA2GEO: Geometry file saved to ' outfile]) end endfunction %!demo %! points = [0 0 0; 0.1 0 0; 0.1 .3 0; 0 0.3 0]; %! strFile = data2geo(points,0.009); %! disp(strFile) %!demo %! dc = svg('drawing6.svg'); %! ids = dc.pathid(); %! P = dc.path2polygon(ids{1},12)(1:end-1,:); %! P = bsxfun(@minus, P, centroid(P)); %! P = simplifyPolygon(P,'tol',5e-1); %! filename = tmpnam (); %! meshsize = sqrt(mean(sumsq(diff(P,1,1),2)))/2; %! data2geo (P, meshsize, 'output', [filename '.geo']); %! %! pkg load msh fpl %! T = msh2m_gmsh(filename); %! pdemesh(T.p,T.e,T.t) %! view(2) %! axis tight %! # -------------------------------------------------------------------------- %! # We load the drawing6.svg file into Octave and transform it into a polygon. %! # Then we create a temporary file where the .geo mesh will be written. %! # If the packages msh and fpl are available, a mesh is created from the .geo %! # file. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/drawing.svg�������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016666� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.644870432 30 atime=1490795556.644870432 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/drawing.svg������������������������������������������������������������������0000644�0001750�0001750�00000003401�13066736044�017040� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/drawing2.svg������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016750� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/drawing2.svg�����������������������������������������������������������������0000644�0001750�0001750�00000003717�13066736044�017134� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml �������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/private�����������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016107� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/���������������������������������������������������������������������0002755�0001750�0001750�00000000000�13066736044�016342� 5����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/PaxHeaders.28738/ruledSurfGeo.m��������������������������������������0000644�0000000�0000000�00000000132�13066736044�020750� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/ruledSurfGeo.m�������������������������������������������������������0000644�0001750�0001750�00000003331�13066736044�021124� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{str} = ruledSurfGeo (@var{id}, @var{nloop}, @var{loops}, @var{centerid}) ## Generates a string for Gmsh Ruled Surface format. ## ## Creates a ruled surface with identifier @var{id}, i.e., a surface that can be ## interpolated using transfinite interpolation. @var{nloop} indicates the number ## of loops that define the surface. @var{loops} should contain the identification ## number of a line loop composed of either three or four elementary lines. ## @var{centerid} is the identification number of the center of the sphere, this ## forces the surface to be a spherical patch. ## ## @end deftypefn function str = ruledSurfGeo(id,nloop,loops,centerid) substr = repmat(',%d',1,nloop-1); if ~isempty(centerid) str = sprintf(['Ruled Surface(%d) = {%d' substr '} In Sphere {%d};\n'], ... id,loops,centerid); else error('data2geo:Error',"The id of the centers shouldn't be empty"); end end �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/PaxHeaders.28738/planeSurfGeo.m��������������������������������������0000644�0000000�0000000�00000000132�13066736044�020734� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/planeSurfGeo.m�������������������������������������������������������0000644�0001750�0001750�00000003354�13066736044�021115� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{str} = planeSurfGeo (@var{id}, @var{nloop},@var{loops}) ## Generates a string for Gmsh Plane Surface format. ## ## @var{id} is the plane surface's identification number. ## @var{nloop} is the number of loops defining the surface. ## @var{loops} contain the identification numbers of all the line loops defining ## the surface. The first line loop defines the exterior boundary of the surface; ## all other line loops define holes in the surface. A line loop defining a hole ## should not have any lines in common with the exterior line loop (in which case ## it is not a hole, and the two surfaces should be defined separately). ## Likewise, a line loop defining a hole should not have any lines in common with ## another line loop defining a hole in the same surface (in which case the two ## line loops should be combined). ## ## @end deftypefn function str = planeSurfGeo(id,nloop,loops) substr = repmat(',%d',1,nloop-1); str = sprintf(['Plane Surface(%d) = {%d' substr '};\n'],id,loops); end ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/PaxHeaders.28738/lineGeo.m�������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017724� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/lineGeo.m������������������������������������������������������������0000644�0001750�0001750�00000002320�13066736044�020075� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{str} = lineGeo (@var{n}, @var{pi}, @var{pj}) ## Generates a string for Gmsh Line format. ## ## Curves are Gmsh's second type of elementery entities, and, ## amongst curves, straight lines are the simplest. A straight line is ## defined by a list of point numbers. The initial point @var{pi}, the final ## point @var{pj}. @var{n} is an indetifier for the line. ## ## @end deftypefn function str = lineGeo(n,i,j) str = sprintf('Line(%d) = {%d,%d};\n',n,i,j); end ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/PaxHeaders.28738/lineLoopGeo.m���������������������������������������0000644�0000000�0000000�00000000132�13066736044�020556� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/lineLoopGeo.m��������������������������������������������������������0000644�0001750�0001750�00000002644�13066736044�020740� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{str} = lineLoopGeo (@var{id}, @var{nl}, @var{lns}) ## Generates a string for Gmsh Line Loop format. ## ## The third elementary entity is the surface. In order to define a ## simple rectangular surface from defined lines, a ## line loop has first to be defined. A line loop is a list of ## connected lines, a sign being associated with each line (depending ## on the orientation of the line). @var{id} is an indentifier for the loop. ## @var{nl} is the number of lines in the loop. @var{lns} is the list of lines. ## ## @end deftypefn function str = lineLoopGeo(id,nl,lns) substr = repmat(',%d',1,nl-1); str = sprintf(['Line Loop(%d) = {%d' substr '};\n'],id,lns); end ��������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/PaxHeaders.28738/pointGeo.m������������������������������������������0000644�0000000�0000000�00000000132�13066736044�020126� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/private/pointGeo.m�����������������������������������������������������������0000644�0001750�0001750�00000002562�13066736044�020307� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} @var{str} = poointGeo (@var{n}, @var{xyz}, @var{l}) ## Generates a string for Gmsh Point format. ## ## Gmsh's simplest `elementary entity', a `Point'. A Point is defined by a list ## of five numbers: @var{n} the identificator, @var{xyz} three coordinates (X, Y ## and Z), and a characteristic length @var{l} that sets the target element size ## at the point: ## The distribution of the mesh element sizes is then obtained by ## interpolation of these characteristic lengths throughout the ## geometry. ## ## @end deftypefn function str = pointGeo(n,xyz,l) str = sprintf('Point(%d) = {%.16g,%.16g,%.16g,%.16g};\n',n,xyz,l); end ����������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/drawing6.svg������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016754� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/drawing6.svg�����������������������������������������������������������������0000644�0001750�0001750�00000002604�13066736044�017132� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ����������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/PaxHeaders.28738/drawing5.svg������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016753� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.648870505 30 atime=1490795556.648870505 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/io/drawing5.svg�����������������������������������������������������������������0000644�0001750�0001750�00000003746�13066736044�017141� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ��������������������������geometry-3.0.0/inst/PaxHeaders.28738/graphs���������������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�015312� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/�������������������������������������������������������������������������0002755�0001750�0001750�00000000000�13066736044�015545� 5����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/grEdgeLengths.m�����������������������������������������0000644�0000000�0000000�00000000132�13066736044�020267� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/grEdgeLengths.m����������������������������������������������������������0000644�0001750�0001750�00000005613�13066736044�020450� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %GREDGELENGTHS Compute length of edges in a geometric graph % % LENGTHS = grEdgeLengths(NODES, EDGES) % % Example % % create a basic graph and display it % nodes = [10 10;20 10;10 20;20 20;27 15]; % edges = [1 2;1 3;2 4;2 5;3 4;4 5]; % figure; drawGraph(nodes, edges); % hold on; drawNodeLabels(nodes, 1:5) % axis equal; axis([0 40 0 30]); % % compute list of nodes adjacent to node with index 2 % grEdgeLengths(nodes, edges)' % ans = % 10.0000 10.0000 10.0000 8.6023 10.0000 8.6023 % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2014-01-13, using Matlab 7.9.0.529 (R2009b) % Copyright 2014 INRA - Cepia Software Platform. function lengths = grEdgeLengths(nodes, edges, varargin) nEdges = size (edges, 1); lengths = zeros (nEdges, 1); for iEdge = 1:nEdges ed = edges(iEdge, :); node1 = nodes(ed(1),:); node2 = nodes(ed(2),:); lengths(iEdge) = sqrt (sumsq (node1 - node2)); end endfunction %!demo %! % create a basic graph and display it %! nodes = [10 10;20 10;10 20;20 20;27 15]; %! edges = [1 2;1 3;2 4;2 5;3 4;4 5]; %! figure; drawGraph(nodes, edges); %! hold on; drawNodeLabels(nodes, 1:5) %! axis equal; axis([0 40 0 30]); %! % compute list of nodes adjacent to node with index 2 %! grEdgeLengths(nodes, edges)' ���������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/grShortestPath.m����������������������������������������0000644�0000000�0000000�00000000132�13066736044�020526� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/grShortestPath.m���������������������������������������������������������0000644�0001750�0001750�00000017007�13066736044�020707� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %GRSHORTESTPATH Find a shortest path between two nodes in the graph % % PATH = grShortestPath(NODES, EDGES, NODE1, NODE2, WEIGHTS) % NODES and EDGES defines the graph, NODE1 and NODE2 are indices of the % node extremities, and WEIGHTS is the set of weights associated to each % edge. % The function returns a set of node indices. % % PATH = grShortestPath(NODES, EDGES, NODEINDS, WEIGHTS) % Specifies two or more points that must be traversed by the path, in the % specified order. % % % Create a simple tree graph, and compute shortest path % [x y] = meshgrid([10 20 30], [10 20 30]); % nodes = [x(:) y(:)]; % edges = [1 2;2 3;2 5;3 6; 4 5;4 7;5 8; 8 9]; % drawGraph(nodes, edges) % axis equal; axis([0 40 0 40]); % drawNodeLabels(nodes, 1:9) % path = grShortestPath(nodes, edges, 1, 9); % % same as: % path = grShortestPath(nodes, edges, [1 9]); % % See also % graphs, grFindMaximalLengthPath % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2011-05-22, using Matlab 7.9.0.529 (R2009b) % Copyright 2011 INRA - Cepia Software Platform. function [nodePath, edgePath] = grShortestPath(nodes, edges, ind0, ind1, edgeWeights) % process the case where several node indices are specified in first arg. if length(ind0) > 1 % following optional argument is edge values if exist('ind1', 'var') edgeWeights = ind1; else edgeWeights = ones(size(edges, 1), 1); end % concatenate path pieces nodePath = ind0(1); edgePath = []; for i = 2:length(ind0) [node0, edge0] = grShortestPath(nodes, edges, ind0(i-1), ind0(i), edgeWeights); nodePath = [nodePath ; node0(2:end)]; %#ok edgePath = [edgePath ; edge0]; %#ok end return; end % ensure weights are defined if ~exist('edgeWeights', 'var') edgeWeights = ones(size(edges, 1), 1); end % check indices limits nNodes = size(nodes, 1); if max(ind0) > nNodes error('Start index exceed number of nodes in the graph'); end if max(ind1) > nNodes error('End index exceed number of nodes in the graph'); end %% Initialisations % consider infinite distance for all nodes dists = inf * ones(nNodes, 1); % initial node is at distance 0 by definition dists(ind0) = 0; % create an array of indices for the predessor of each node preds = zeros(nNodes, 1); preds(ind0) = 0; % allocate memory to store the subgraph, which is a tree edges2 = zeros(nNodes-1, 2); % create an array of node flags unprocessedNodeInds = 1:nNodes; edgeCount = 0; %% Iterate until all nodes are flagged to 1 while ~isempty(unprocessedNodeInds) % choose unprocessed node with lowest distance [tmp, ind] = min(dists(unprocessedNodeInds)); %#ok ind = unprocessedNodeInds(ind); ind = ind(1); % mark current node as processed unprocessedNodeInds(unprocessedNodeInds == ind) = []; % if the current node is the target, it is not necessary to continue... if ind == ind1 break; end % find the index list of edges incident to current node adjEdgeInds = grAdjacentEdges(edges, ind); % select edges whose opposite node has not yet been processed inds2 = sum(ismember(edges(adjEdgeInds, :), unprocessedNodeInds), 2) > 0; adjEdgeInds = adjEdgeInds(inds2); % iterate over incident edges to update adjacent nodes for iNeigh = 1:length(adjEdgeInds) % extract index of current adjacent node edge = edges(adjEdgeInds(iNeigh), :); adjNodeInd = edge(~ismember(edge, ind)); newDist = dists(ind) + edgeWeights(adjEdgeInds(iNeigh)); % dists(adjNodeInd) = min(dists(adjNodeInd), newDist); if newDist < dists(adjNodeInd) dists(adjNodeInd) = newDist; preds(adjNodeInd) = ind; end end % find the list of adjacent nodes adjNodeInds = unique(edges(adjEdgeInds, :)); adjNodeInds(adjNodeInds == ind) = []; % choose the adjacent nodes with lowest distance, and add the % corresponding edges to the subgraph if ~isempty(adjNodeInds) minDist = min(dists(adjNodeInds)); closestNodeInds = adjNodeInds(dists(adjNodeInds) <= minDist); for iCloseNode = 1:length(closestNodeInds) edgeCount = edgeCount + 1; edges2(edgeCount, :) = [ind closestNodeInds(iCloseNode)]; end end end %% Path creation % create the path: start from end index, and identify successive set of % neighbor edges and nodes nodeInd = ind1; nodePath = nodeInd; edgePath = []; % find predecessors until we reach ind0 node while nodeInd ~= ind0 newNodeInd = preds(nodeInd); nodePath = [nodePath ; newNodeInd]; %#ok % search the edge (both directions) in the list of edges e_tmp = [nodeInd newNodeInd]; [~,edgeInd] = ismember ([e_tmp; e_tmp(end:-1:1)], edges, 'rows'); edgeInd(edgeInd == 0) = []; % erase the one that isn't there edgePath = [edgePath ; edgeInd]; %#ok nodeInd = newNodeInd; end % reverse the path nodePath = nodePath(end:-1:1); edgePath = edgePath(end:-1:1); endfunction %!demo %! % Create a simple tree graph, and compute shortest path %! [x y] = meshgrid ([10 20 30], [10 20 30]); %! nodes = [x(:) y(:)]; %! edges = [1 2;2 3;2 5;3 6; 4 5;4 7;5 8; 8 9]; %! drawGraph (nodes, edges) %! drawNodeLabels (nodes, 1:9) %! [nid eid] = grShortestPath (nodes, edges, 1, 9); %! n_path = nodes(nid,:); %! [~,e_path] = ismember (edges(eid,:), nid); %! drawGraph (n_path, e_path,'none', {'color','red'}); %! hold on; %! h = plot (n_path(1,1),n_path(1,2),'o',n_path(end,1),n_path(end,2),'o'); %! set(h(1),'markeredgecolor','none', 'markerfacecolor', 'g','markersize', 10); %! set(h(2),'markeredgecolor','none', 'markerfacecolor', 'k','markersize', 10); %! hold off %! axis image �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/knnGraph.m����������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017315� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/knnGraph.m���������������������������������������������������������������0000644�0001750�0001750�00000004664�13066736044�017503� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{edges} = } knnGrpah (@var{nodes}) ## Create the k-nearest neighbors graph of a set of points ## ## EDGES = knnGraph(NODES) ## ## Example ## @example ## ## nodes = rand(10, 2); ## edges = knnGraph(nodes); ## drawGraph(nodes, edges); ## ## @end example ## ## @end deftypefn function edges = knnGraph(nodes, varargin) # get number of neighbors for each node k = 2; if ~isempty(varargin) k = varargin{1}; end # init size of arrays n = size(nodes, 1); edges = zeros(k*n, 2); # iterate on nodes for i = 1:n dists = distancePoints(nodes(i,:), nodes); [dists inds] = sort(dists); ##ok for j = 1:k edges(k*(i-1)+j, :) = [i inds(j+1)]; end end # remove double edges edges = unique(sort(edges, 2), 'rows'); endfunction %!demo %! nodes = rand(10, 2); %! edges = knnGraph(nodes); %! drawGraph(nodes, edges); %! axis tight ����������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/grAdjacentNodes.m���������������������������������������0000644�0000000�0000000�00000000132�13066736044�020600� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/grAdjacentNodes.m��������������������������������������������������������0000644�0001750�0001750�00000005547�13066736044�020767� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %GRADJACENTNODES Find list of nodes adjacent to a given node % % NEIGHS = grAdjacentNodes(EDGES, NODE) % EDGES: the complete edges list (containing indices of neighbor nodes) % NODE: index of the node % NEIGHS: the nodes adjacent to the given node. % % NODE can also be a vector of node indices, in this case the result is % the set of neighbors of any input node, excluding the input nodes. % % Example % % create a basic graph and display it % nodes = [10 10;20 10;10 20;20 20;27 15]; % edges = [1 2;1 3;2 4;2 5;3 4;4 5]; % figure; drawGraph(nodes, edges); % hold on; drawNodeLabels(nodes, 1:5) % axis equal; axis([0 40 0 30]); % % compute list of nodes adjacent to node with index 2 % grAdjacentNodes(edges, 2) % ans = % 1 % 4 % 5 % % See Also % grAdjacentEdges % ----- % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 16/08/2004. % % HISTORY % 10/02/2004 documentation % 13/07/2004 faster algorithm % 03/10/2007 can specify several input nodes % 20/01/2013 rename from grNeighborNodes to grAdjacentNodes function nodes2 = grAdjacentNodes(edges, node) [i, j] = find (ismember (edges, node)); %#ok nodes2 = edges(i,1:2); nodes2 = unique (nodes2(:)); nodes2 = sort (nodes2(~ismember (nodes2, node))); endfunction ���������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/delaunayGraph.m�����������������������������������������0000644�0000000�0000000�00000000132�13066736044�020331� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/delaunayGraph.m����������������������������������������������������������0000644�0001750�0001750�00000006564�13066736044�020520� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{points} @var{edges}]= } delaunayGraph (@var{points}) ## Graph associated to Delaunay triangulation of input points ## ## Compute the Delaunay triangulation of the set of input points, and ## convert to a set of edges. The output NODES is the same as the input ## POINTS. ## ## WARNING: 3d pltottig works correctly in Octave >= 3.6 ## ## Example ## @example ## ## # Draw a planar graph correpspionding to Delaunay triangulation ## points = rand(30, 2) * 100; ## [nodes edges] = delaunayGraph(points); ## figure; ## drawGraph(nodes, edges); ## ## # Draw a 3Dgraph corresponding to Delaunay tetrahedrisation ## points = rand(20, 3) * 100; ## [nodes edges] = delaunayGraph(points); ## figure; ## drawGraph(nodes, edges); ## view(3); ## ## @end example ## ## @seealso{delaunay, delaunayn} ## @end deftypefn function [points edges] = delaunayGraph(points, varargin) # compute triangulation tri = delaunayn(points, varargin{:}); # number of simplices (triangles), and of vertices by simplex (3 in 2D) nt = size(tri, 1); nv = size(tri, 2); # allocate memory edges = zeros(nt * nv, 2); # compute edges of each simplex for i = 1:nv-1 edges((1:nt) + (i-1)*nt, :) = sort([tri(:, i) tri(:, i+1)], 2); end edges((1:nt) + (nv-1)*nt, :) = sort([tri(:, end) tri(:, 1)], 2); # remove multiple edges edges = unique(edges, 'rows'); endfunction %!demo %! # Draw a planar graph correpspionding to Delaunay triangulation %! points = rand(30, 2) * 100; %! [nodes edges] = delaunayGraph(points); %! figure; %! drawGraph(nodes, edges); %! axis tight %!demo %! # WARNING 3d pltottig works correctly in Octave >= 3.6 %! # Draw a 3Dgraph corresponding to Delaunay tetrahedrisation %! points = rand(20, 3) * 100; %! [nodes edges] = delaunayGraph(points); %! figure; %! drawGraph(nodes, edges); %! view(3); %! axis tight ��������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/drawGraph.m���������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017464� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/drawGraph.m��������������������������������������������������������������0000644�0001750�0001750�00000021644�13066736044�017647� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} drawGraph (@var{nodes}, @var{edges}) ## @deftypefnx {Function File} drawGraph (@var{nodes}, @var{edges}, @var{faces}) ## @deftypefnx {Function File} drawGraph (@var{graph}) ## @deftypefnx {Function File} drawGraph (@dots{}, @var{snodes}) ## @deftypefnx {Function File} drawGraph (@dots{}, @var{snodes}, @var{sedges}) ## @deftypefnx {Function File} drawGraph (@dots{}, @var{snodes}, @var{sedges}, @var{sfaces}) ## @deftypefnx {Function File} {@var{h} = } drawGraph (@dots{}) ## @deftypefnx {Function File} {[@var{h} @var{he}] = } drawGraph (@dots{}) ## @deftypefnx {Function File} {[@var{h} @var{he} @var{hf}] = } drawGraph (@dots{}) ## Draw a graph, given as a set of vertices and edges ## ## DRAWGRAPH(NODES, EDGES) ## draw a graph specified by a set of nodes (array N*2 or N*3, ## corresponding to coordinate of each node), and a set of edges (an array ## Ne*2, containing for each edge the first and the second node). ## Default drawing is a red circle for nodes and a blue line for edges. ## ## DRAWGRAPH(NODES, EDGES, FACES) ## also draw faces of the graph as patches. ## ## DRAWGRAPH(GRAPH) ## passes argument in a srtucture with at least 2 fields named 'nodes' and ## 'edges', and possibly one field 'faces', corresponding to previously ## described parameters. ## GRAPH can also be a cell array, whose first element is node array, ## second element is edges array, and third element, if present, is faces ## array. ## ## ## DRAWGRAPH(..., SNODES) ## DRAWGRAPH(..., SNODES, SEDGES) ## DRAWGRAPH(..., SNODES, SEDGES, SFACES) ## specify the draw mode for each element, as in the classical 'plot' ## function. To not display some elements, uses 'none'. ## ## ## H = DRAWGRAPH(...) ## return handle to the set of edges. ## ## [HN, HE] = DRAWGRAPH(...) ## return handle to the set of nodes and to the set of edges. ## ## [HN, HE, HF] = DRAWGRAPH(...) ## Also return handle to the set of faces. ## ## @end deftypefn function varargout = drawGraph(varargin) ## initialisations he = hn = hf = []; # uses empty arrays by default for edges and faces e = []; f = []; # default styles for nodes, edges, and faces # nodes are drawn as red circles sn = {'linestyle', 'none', 'color', 'r', 'marker', 'o'}; # edges are drawn as blue lines se = {'linestyle', '-', 'color', 'b'}; # faces are cyan, their edges are not drawn sf = {'EdgeColor', 'none', 'Facecolor', 'c'}; ## Process input arguments # case of a call without arguments if nargin==0 help drawGraph; return; end # --------------------------------------------------------------- # First extract the graph structure var = varargin{1}; if iscell(var) # graph is stored as a cell array: first cell is nodes, second one is # edges, and third is faces n = var{1}; if length(var)>1 e = var{2}; end if length(var)>2 f = var{3}; end varargin(1) = []; elseif isstruct(var) # graph is stored as a structure, with fields 'nodes', 'edges', and # eventually 'faces'. n = var.nodes; e = var.edges; if isfield(var, 'faces') f = var.faces; end varargin(1) = []; else # graph is stored as set of variables: nodes, edges, and eventually # faces n = varargin{1}; e = varargin{2}; varargin(1:2) = []; if ~isempty(varargin) var = varargin{1}; if isnumeric(var) # faces are stored in a numeric array of indices f = var; varargin(1) = []; elseif iscell(var) if ~ischar(var{1}) # faces are stored in a cell array, each cell containing a # row vector of indices f = var; varargin(1) = []; end end end end # extract drawing style if ~isempty(varargin) sn = concatArguments(sn, varargin{1}); end if length(varargin)>1 se = concatArguments(se, varargin{2}); end if length(varargin)>2 sf = concatArguments(sf, varargin{3}); end ## main drawing processing # overwrites on current figure state = ishold(gca); hold on; if size(n, 2)==2 # Draw a 2 dimensional graph ---------------------- # Draw faces of the graph ------------ if ~strcmp(sf{1}, 'none') && ~isempty(f) if iscell(f) # each face is contained in a cell. hf = zeros(size(f)); for fi=1:length(f) hf(fi) = patch('Faces', f{fi}, 'Vertices', n, sf{:}); end else # process faces as an Nf*N array. Nf is the number of faces, # and all faces have the same number of vertices (nodes). hf = patch('Faces', f, 'Vertices', n, sf{:}); end end # Draw 2D Edges ---------------------- if ~strcmp(se{1}, 'none') && size(e, 1)>0 he = plot([n(e(:,1),1) n(e(:,2),1)]', [n(e(:,1),2) n(e(:,2),2)]', se{:}); end # Draw 2D nodes ---------------------- if ~strcmp(sn{1}, 'none') hn = plot(n(:,1), n(:,2), sn{:}); end elseif size(n, 2)==3 # Draw a 3 dimensional graph ---------------------- # use a zbuffer to avoid display pbms. #set(gcf, 'renderer', 'zbuffer'); # Draw 3D Faces ---------------------- if ~strcmp(sf{1}, 'none') if iscell(f) # each face is contained in a cell. hf = zeros(size(f)); for fi=1:length(f) hf(fi) = patch('Faces', f{fi}, 'Vertices', n, sf{:}); end else # process faces as an Nf*N array. Nf i the number of faces, # and all faces have the same number of vertices (nodes). hf = patch('Faces', f, 'Vertices', n, sf{:}); end end # Draw 3D edges ---------------------- if ~strcmp(se{1}, 'none') && size(e, 1)>0 # he = plot3(... # [n(e(:,1),1) n(e(:,2),1)]', ... # [n(e(:,1),2) n(e(:,2),2)]', ... # [n(e(:,1),3) n(e(:,2),3)]', ... # se{:}); he = line(... [n(e(:,1),1) n(e(:,2),1)]', ... [n(e(:,1),2) n(e(:,2),2)]', ... [n(e(:,1),3) n(e(:,2),3)]', ... se{:}); end # Draw 3D nodes ---------------------- if ~strcmp(sn{1}, 'none'); hn = plot3(n(:,1), n(:,2), n(:,3), sn{:}); end else error ("Can't handle %d-dimensional nodes", size(n,2)); end if ~state hold off end ## Format output arguments # return handle to edges if nargout==1 varargout{1} = [hn; he; hf]; end # return handle to nodes and edges if nargout==2 varargout{1} = hn; varargout{2} = he; end # return handle to nodes, edges and faces if nargout==3 varargout{1} = hn; varargout{2} = he; varargout{3} = hf; end endfunction function res = concatArguments(in1, in2) # in1 is a cell array already initialized # in2 is an argument that can be: # - empty # - the string 'none' # - another cell array if isempty(in2) res = in1; return; end if ischar(in2) if strcmp('none', in2) res = {'none'}; return; end end if iscell(in1) res = [in1(:)' in2(:)']; else res = [{in1} in2(:)]; end endfunction ��������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/clipGraph.m���������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017456� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/clipGraph.m��������������������������������������������������������������0000644�0001750�0001750�00000016222�13066736044�017635� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %CLIPGRAPH Clip a graph with a rectangular area % % [N2 E2] = clipGraph(N, E, BOX); % [N2 E2 F2] = clipGraph(N, E, F, BOX); % N is an array ov vertices, E an array of edges, containing indices of % first ans second vertices, and F (optional) is either a matrice or a % cell array containing indices of vertices for each face. % BOX is either a box given as a matrix: [XMIN XMAX;YMIN YMAX], or a row % vector following matlab axis format: [XMIN XMAX YMIN YMAX]. % % Example % clipGraph % % See also % drawGraph, clipGraphPolygon % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2007-01-18 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. function varargout = clipGraph(nodes, edges, varargin) %% Format inputs % extract input arguments faces = []; if length(varargin)==1 box = varargin{1}; elseif length(varargin)==2 faces = varargin{1}; box = varargin{2}; else error('Wrong number of arguments in clipGraph'); end % uniformization of input for box. box = box'; box = box(:); % accuracy of numeric computations ACC = eps; %% Get bounding lines % get bounds of the box xmin = box(1); xmax = box(2); ymin = box(3); ymax = box(4); % create box corners corners = [ ... xmin ymin; ... xmin ymax; ... xmax ymin; ... xmax ymax]; ... %% Clip the nodes % find nodes inside clipping window insideNodes = ... nodes(:,1)-xmin>ACC & nodes(:,1)-xmaxACC & nodes(:,2)-ymax no clip if in1 && in2 edges2 = [edges2; hashNodes(edges(e, :))']; %#ok hashEdges(e) = size(edges2, 1); continue; end % check that edge is not totally clipped -> no edge if edge(1)-xminACC && edge(3)-xmax>ACC, continue; end if edge(2)-yminACC && edge(4)-ymax>ACC, continue; end % otherwise, we have to clip the edge ! edge = clipEdge(edge, [box(1) box(2); box(3) box(4)]); % display debug info %disp(sprintf('clip edge n°%2d, from %2d to %2d', e, edges(e,1), edges(e,2))); % Node for first vertex if ~in1 nodes2 = [nodes2; edge([1 2])]; %#ok indN1 = size(nodes2, 1); else indN1 = hashNodes(edges(e, 1)); end % Node for second vertex if ~in2 nodes2 = [nodes2; edge([3 4])]; %#ok indN2 = size(nodes2, 1); else indN2 = hashNodes(edges(e, 2)); end % add clipped edge to the list edges2 = [edges2; indN1 indN2]; %#ok hashEdges(e) = size(edges2, 1); end %% Clip the faces faces2 = {}; for f = 1:length(faces) % indices of vertices of current face face = faces{f}; % if the face is not clipped, use directly new indices of nodes face2 = hashNodes(face)'; if ~ismember(0, face2) faces2 = [faces2, {face2}]; %#ok continue; end % At least one vertex is clipped. Here is some more special processing % edges of current face faceEdges = sort([face' face([2:end 1])'], 2); % indices of face edges in edges array indEdges = ismember(edges, faceEdges, 'rows'); % convert to indices of edges in clipped edges array. indEdges with % value=0 correspond to totally clipped edges, and can be removed. indEdges = hashEdges(indEdges); indEdges = indEdges(indEdges~=0); % case of face totally clipped: break and continuue with next face if isempty(indEdges) continue; end % extract indices of vertices of the clipped face face2 = edges2(indEdges, :); face2 = unique(face2(:)); % Test whether one should add one of the corner of the box. poly = [nodes(face, 1) nodes(face, 2)]; ind = inpolygon(corners(:,1), corners(:,2), poly(:,1), poly(:,2)); if sum(ind)>0 nodes2 = [nodes2; corners(ind, :)]; %#ok face2 = [face2; size(nodes2, 1)]; %#ok end % vertices of the face, as points faceNodes = nodes2(face2, :); % sort vertices according to their angle around the centroid [faceNodes, I] = angleSort(faceNodes, centroid(faceNodes)); %#ok % add current face to list of faces faces2 = [faces2, {face2(I)'}]; %#ok end %% Format output arguments % clean up nodes to ensure coord correspond to clipping box. nodes2(:,1) = min(max(nodes2(:,1), box(1)), box(2)); nodes2(:,2) = min(max(nodes2(:,2), box(3)), box(4)); if nargout==2 varargout{1} = nodes2; varargout{2} = edges2; elseif nargout==3 varargout{1} = nodes2; varargout{2} = edges2; varargout{3} = faces2; end endfunction ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/grAdjacentEdges.m���������������������������������������0000644�0000000�0000000�00000000132�13066736044�020557� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/grAdjacentEdges.m��������������������������������������������������������0000644�0001750�0001750�00000005007�13066736044�020735� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %GRADJACENTEDGES Find list of edges adjacent to a given node % % NEIGHS = grAdjacentEdges(EDGES, NODE) % EDGES the complete edges list (containing indices of neighbor nodes) % NODE index of the node % NEIGHS the indices of edges containing the node index % % See also % grAdjacentNodes % ----- % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 13/08/2003. % % HISTORY % 10/02/2004 : documentation % 13/07/2004 : faster algorithm % 17/01/2006 : rename and change implementation function neigh = grAdjacentEdges(edges, node) neigh = find(edges(:,1) == node | edges(:,2) == node); endfunction %!demo %! pos = rand (10,2); %! [~,idx] = min(sumsq(pos- mean(pos),2)); %! [nodes edges faces] = voronoi2d (pos); %! neigh = grAdjacentEdges (edges, idx); %! #drawGraph (nodes, edges); %! hold on %! drawGraphEdges (nodes, edges(neigh,:), '-r'); %! plot(nodes(idx,1),nodes(idx,2),'og','markerfacecolor','g'); %! hold off �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/voronoi2d.m���������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017466� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/voronoi2d.m��������������������������������������������������������������0000644�0001750�0001750�00000004742�13066736044�017651� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{nodes} @var{edges} @var{faces}] = } voronoi2d (@var{germs}) ## Compute a voronoi diagram as a graph structure ## ## [NODES EDGES FACES] = voronoi2d(GERMS) ## GERMS an array of points with dimension 2 ## NODES, EDGES, FACES: usual graph representation, FACES as cell array ## ## Example ## @example ## ## [n e f] = voronoi2d(rand(100, 2)*100); ## drawGraph(n, e); ## ## @end example ## ## @end deftypefn function [nodes edges faces] = voronoi2d (germs) [V C] = voronoin (germs); nodes = V(2:end, :); edges = zeros(0, 2); faces = {}; for i=1:length(C) cell_ = C{i}; if ismember (1, cell_) continue; end cell_ = cell_ - 1; edges = [edges; sort([cell_' cell_([2:end 1])'], 2)]; ##ok faces{length(faces)+1} = cell_; ##ok end edges = unique (edges, 'rows'); endfunction %!demo %! [n e f] = voronoi2d(rand(100, 2)*100); %! drawGraph(n, e); %! axis tight ������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/centroidalVoronoi2d.m�����������������������������������0000644�0000000�0000000�00000000130�13066736044�021471� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������29 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/centroidalVoronoi2d.m����������������������������������������������������0000644�0001750�0001750�00000013230�13066736044�021646� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %CENTROIDALVORONOI2D Centroidal Voronoi tesselation within a polygon % % PTS = centroidalVoronoi2d(NPTS, POLY) % Generate points in a polygon based on centroidal voronoi tesselation. % Centroidal germs can be computed by using the Llyod's algorithm: % 1) initial germs are chosen at random within polygon % 2) voronoi polygon of the germs is computed % 3) the centroid of each domain are computed, and used as germs of the % next iteration % % This version uses an approximated version of Llyod's algorithm. The % centroids are not computed explicitly, but approximated by sampling N % points within the bounding polygon. % % PTS = centroidalVoronoi2d(.., PARAM, VALUE) % Specify one or several optional arguments. PARAM can be one of: % * 'nIter' specifies the number of iterations of the algorithm % (default is 30) % * 'nPoints' number of points for updating positions of germs at each % iteration. Default is 200 times the number of germs. % * 'verbose' display iteration number. Default is false. % % Example % centroidalVoronoi2d % % See also % graphs, boundedVoronoi2d % % Rewritten from programs found in % http://people.scs.fsu.edu/~burkardt/m_src/cvt/cvt.html % % Reference: % Qiang Du, Vance Faber, and Max Gunzburger, % Centroidal Voronoi Tessellations: Applications and Algorithms, % SIAM Review, Volume 41, 1999, pages 637-676. % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-02-23, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. function [germs, germPaths] = centroidalVoronoi2d(nGerms, poly, varargin) %% Parse input arguments % Number of points nPts = 200 * nGerms; % Number of iterations nIter = 30; verbose = false; keepPaths = nargout > 1; while length(varargin) > 1 paramName = varargin{1}; switch lower(paramName) case 'verbose' verbose = varargin{2}; case 'niter' nIter = varargin{2}; case 'npoints' nPts = varargin{2}; otherwise error(['Unknown parameter name: ' paramName]); end varargin(1:2) = []; end %% Initialisations % bounding box of polygon box = polygonBounds(poly); % init germs germs = generatePointsInPoly (nGerms); germIters = cell(nIter, 1); %% Iteration of the McQueen algorithm for i = 1:nIter if verbose disp(sprintf('Iteration: %d/%d', i, nIter)); %#ok end if keepPaths germIters{i} = germs; end % random uniform points in polygon points = generatePointsInPoly(nPts); % update germs of Voronoi germs = cvtUpdate(germs, points); end %% Evenutally compute germs trajectories if nargout > 1 % init germPaths = cell (nGerms, 1); path = zeros (nIter+1, 2); % Iteration on germs for i = 1:nGerms % create path corresponding to germ for j = 1:nIter pts = germIters{j}; path(j,:) = pts(i,:); end path(nIter+1, :) = germs(i,:); germPaths{i} = path; end end function pts = generatePointsInPoly(nPts) % extreme coordinates xmin = box(1); xmax = box(2); ymin = box(3); ymax = box(4); % compute size of box dx = xmax - xmin; dy = ymax - ymin; % allocate memory for result pts = zeros(nPts, 2); % iterate until all points have been sampled within the polygon ind = (1:nPts)'; while ~isempty(ind) NI = length(ind); x = rand(NI, 1) * dx + xmin; y = rand(NI, 1) * dy + ymin; pts(ind, :) = [x y]; ind = ind(~polygonContains(poly, pts(ind, :))); end endfunction endfunction %!demo %! npts = 10; %! poly = [0 0;1 0;1 1;0 1]; %! pts = centroidalVoronoi2d (npts, poly); %! [nodes edges] = voronoi2d (pts); %! [nodes, edges] = clipGraphPolygon (nodes, edges, poly); %! drawGraph (nodes, edges); %! hold on; %! drawPolygon (poly, '-r'); %! plot(pts(:,1),pts(:,2),'ok','markerfacecolor','k'); %! hold off ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/graphs_Contents.m���������������������������������������0000644�0000000�0000000�00000000132�13066736044�020706� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.640870357 30 atime=1490795556.640870357 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/graphs_Contents.m��������������������������������������������������������0000644�0001750�0001750�00000016422�13066736044�021067� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## -*- texinfo -*- ## @deftypefn {Function File} graphs_Contents () ## GRAPHS Simple Toolbox for manipulating Geometric Graphs ## Version 0.5 11-Apr-2010 . ## ## The aim of this package is to provides functions to easily create, ## modify and display geometric graphs (geometric in a sense position ## of vertices is kept in memory). ## ## Graph structure is represented by at least two arrays: ## * NODES, which contains coordinates of each vertex ## * EDGES, which contains indices of start and end vertex. ## ## Others arrays may sometimes be used: ## * FACES, which contains indices of vertices of each face (either a ## double array, or a cell array) ## * CELLS, which contains indices of faces of each cell. ## ## An alternative representation is to use a structure, with fields: ## * edges ## * faces ## * cells ## corresponding to the data described above. ## ## Note that topological description of 2D graph is entirely contained in ## EDGES array, and that NODES array is used only to display graph ## ## Caution: this type of data structure is easy to create and to manage, ## but may be very inefficient for some algorithms. ## ## Graphs are usually considered as non-oriented in this package. ## ## ## Graph creation ## knnGraph - Create the k-nearest neighbors graph of a set of points ## delaunayGraph - Graph associated to Delaunay triangulation of input points ## euclideanMST - Build euclidean minimal spanning tree of a set of points ## prim_mst - Minimal spanning tree by Prim's algorithm ## ## Create graph from images ## imageGraph - Create equivalent graph of a binary image ## boundaryGraph - Get boundary of image as a graph ## gcontour2d - Creates contour graph of a 2D binary image. ## gcontour3d - Create contour graph of a 3D binary image. ## vectorize - Transform a binary skeleton into a graph (nodes and edges) ## ## Graph information ## grNodeDegree - Degree of a node in a (undirected) graph ## grNodeInnerDegree - Inner degree of a node in a graph ## grNodeOuterDegree - Outer degree of a node in a graph ## grNeighborNodes - Find adjacent nodes of a given node ## grNeighborEdges - Find adjacent edges of a given node ## grOppositeNode - Return opposite node in an edge ## grLabel - Associate a label to each connected component of the graph ## ## Graph management (low level operations) ## grRemoveNode - Remove a node in a graph ## grRemoveNodes - Remove several nodes in a graph ## grRemoveEdge - Remove an edge in a graph. ## grRemoveEdges - Remove several edges from a graph ## ## Graph processing (general applications) ## mergeGraphs - Merge two graphs, by adding nodes, edges and faces lists. ## grMergeNodes - Merge two (or more) nodes in a graph. ## grMergeMultipleNodes - Simplify a graph by merging multiple nodes ## grMergeMultipleEdges - Remove all edges sharing the same extremities ## grSimplifyBranches - Replace branches of a graph by single edges ## ## Filtering operations on Graph ## grMean - Compute mean from neihgbours ## grMedian - Compute median from neihgbours ## grDilate - Morphological dilation on graph ## grErode - Morphological erosion on graph ## grClose - Morphological closing on graph ## grOpen - Morphological opening on graph ## ## Geodesic operations ## grPropagateDistance - Propagates distances from a vertex to other vertices ## grVertexEccentricity - Eccentricity of vertices in the graph ## graphDiameter - Diameter of a graph ## graphPeripheralVertices - Peripheral vertices of a graph ## graphCenter - Center of a graph ## graphRadius - Radius of a graph ## grFindGeodesicPath - Find a geodesic path between two nodes in the graph ## grFindMaximalLengthPath - Find a path that maximizes sum of edge weights ## ## Operations for geometric graphs ## grMergeNodeClusters - Merge cluster of connected nodes in a graph ## grMergeNodesMedian - Replace several nodes by their median coordinate ## clipGraph - Clip a graph with a rectangular area ## addSquareFace - Add a (square) face defined from its vertices to a graph ## grFaceToPolygon - Compute the polygon corresponding to a graph face ## graph2Contours - Convert a graph to a set of contour curves ## ## Voronoi Graphs ## voronoi2d - Compute a voronoi diagram as a graph structure ## boundedVoronoi2d - Return a bounded voronoi diagram as a graph structure ## centroidalVoronoi2d - Create a 2D Centroidal Voronoi Tesselation ## cvtUpdate - Update germs of a CVT with given points ## cvtIterate - Update germs of a CVT using random points with given density ## ## Graph display ## drawGraph - Draw a graph, given as a set of vertices and edges ## drawGraphEdges - Draw edges of a graph ## drawGraphFaces - Draw faces of a graph ## drawDigraph - Draw a directed graph, given as a set of vertices and edges ## drawDirectedEdges - Draw edges with arrow indicating direction ## drawEdgeLabels - Draw values associated to graph edges ## drawNodeLabels - Draw values associated to graph nodes ## drawSquareMesh - Draw a 3D square mesh given as a graph ## patchGraph - Transform 3D graph (mesh) into a patch handle ## ## @end deftypefn function graphs_Contents() help graphs_Contents endfunction ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/cvtUpdate.m���������������������������������������������0000644�0000000�0000000�00000000132�13066736044�017504� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/cvtUpdate.m��������������������������������������������������������������0000644�0001750�0001750�00000006460�13066736044�017666� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %CVTUPDATE Update germs of a CVT with given points % % G2 = cvtUpdate(G, PTS) % G: inital germs % PTS: the points % % Example % G = randPointDiscUnif(50); % P = randPointDiscUnif(10000); % G2 = cvtUpdate(G, P); % % See also % % % Rewritten from programs found in % http://people.scs.fsu.edu/~burkardt/m_src/cvt/cvt.html % % Reference: % Qiang Du, Vance Faber, and Max Gunzburger, % Centroidal Voronoi Tessellations: Applications and Algorithms, % SIAM Review, Volume 41, 1999, pages 637-676. % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2007-10-10, using Matlab 7.4.0.287 (R2007a) % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. function varargout = cvtUpdate(germs, points) %% Init % number of germs and of points Ng = size(germs, 1); N = size(points, 1); % initialize centroids with values of germs centroids = germs; % number of updates of each centroid count = ones (Ng, 1); %% Generate random points % for each point, determines which germ is the closest ones [dist, ind] = minDistancePoints (points, germs); %#ok h = zeros(Ng, 1); for i = 1:Ng h(i) = sum(ind==i); end %% Centroids update % add coordinate of each point to closest centroid energy = 0; for j = 1:N centroids(ind(j), :) = centroids(ind(j), :) + points(j, :); energy = energy + sum ( ( centroids(ind(j), :) - points(j, :) ).^2); count(ind(j)) = count(ind(j)) + 1; end % estimate coordinate by dividing by number of counts centroids = centroids ./ repmat(count, 1, size(germs, 2)); % normalizes energy by number of sample points energy = energy / N; %% Format output varargout{1} = centroids; if nargout > 1 varargout{2} = energy; end endfunction ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/clipGraphPolygon.m��������������������������������������0000644�0000000�0000000�00000000132�13066736044�021026� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/clipGraphPolygon.m�������������������������������������������������������0000644�0001750�0001750�00000011265�13066736044�021207� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %CLIPGRAPHPOLYGON Clip a graph with a polygon % % [NODES2 EDGES2] = clipGraphPolygon(NODES, EDGES, POLY) % Clips the graph defined by nodes NODES and edges EDGES with the polygon % given in POLY. POLY is a N-by-2 array of vertices. % The result is a new graph containing nodes inside the polygon, as well % as nodes created by the intersection of edges with the polygon. % % % See also % drawGraph, clipGraph % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2012-02-24, using Matlab 7.9.0.529 (R2009b) % Copyright 2012 INRA - Cepia Software Platform. % algo: % * For each edge not outside do: % * clip edge with poly % * if no inter % * add current edge (same vertex indices) % * continue % * end % * add intersections to list, compute their indices % * create the new edge(s) function [nodes2, edges2] = clipGraphPolygon(nodes, edges, poly) %% Clip the nodes % find index of nodes inside clipping window nodeInside = isPointInPolygon(nodes, poly); indNodes = find(nodeInside); % create correspondance between original nodes and inside nodes hashNodes = zeros(size(nodes, 1), 1); for i = 1:length(indNodes) hashNodes(indNodes(i)) = i; end % select clipped nodes nodes2 = nodes(indNodes, :); %% Clip the edges insideEnds = nodeInside(edges); % allocate memory for edges with at least one vertex inside nEdges2 = sum(sum(insideEnds, 2) ~= 0); % allocate memory for at least edges inside edges2 = zeros(nEdges2, 2); nEdges = size(edges, 1); % index of next edge iEdge2 = 1; % index of next vertex iNode2 = size(nodes2, 1) + 1; % iterate over all edges for iEdge = 1:nEdges % index of edge vertices v1 = edges(iEdge, 1); v2 = edges(iEdge, 2); % compute intersection(s) of current edge with boundary edge0 = [nodes(v1,:) nodes(v2,:)]; intersects = intersectEdgePolygon(edge0, poly); % process edges that do not cross polygon boundary if isempty(intersects) if nodeInside(v1) && nodeInside(v2) % current edge is totally inside the clipping polygon edges2(iEdge2,:) = hashNodes([v1 v2]); iEdge2 = iEdge2 + 1; end continue; end % add intersection(s) to the vertex array nInters = size(intersects, 1); intersectInds = iNode2:iNode2+nInters-1; nodes2(intersectInds,:) = intersects; iNode2 = iNode2 + nInters; % concatenate vertex indices with indices of extremities inside poly if nodeInside(v1) intersectInds = [hashNodes(v1) intersectInds]; %#ok end if nodeInside(v2) intersectInds = [intersectInds hashNodes(v2)]; %#ok end % create new edge for each couple of contiguous intersection while ~isempty(intersectInds) edges2(iEdge2, :) = intersectInds(1:2); intersectInds(1:2) = []; iEdge2 = iEdge2 + 1; end if ~isempty(intersectInds) warning('graphs:AlgorithmicError', ... 'edge %d has odd number of intersectss', iEdge); end end endfunction �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/boundedVoronoi2d.m��������������������������������������0000644�0000000�0000000�00000000130�13066736044�020765� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������29 mtime=1490795556.63287021 29 atime=1490795556.63287021 30 ctime=1490795556.716871764 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/boundedVoronoi2d.m�������������������������������������������������������0000644�0001750�0001750�00000005772�13066736044�021156� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %BOUNDEDVORONOI2D Return a bounded voronoi diagram as a graph structure % % [NODES EDGES FACES] = boundedVoronoi2d(BOX, GERMS) % GERMS an array of points with dimension 2 % NODES, EDGES, FACES: usual graph representation, FACES as cell array % % Example % [n e f] = boundedVoronoi2d([0 100 0 100], rand(100, 2)*100); % drawGraph(n, e); % % See also % boundedCentroidalVoronoi2d % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2007-01-12 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. function [nodes, edges, faces] = boundedVoronoi2d(box, germs) % uniformize input for box. box = box'; box = box(:); % add points far enough width = box(2)-box(1); height = box(4)-box(3); farPoints = [... box(2)+2*width box(4)+3*height;... box(1)-3*width box(4)+2*height;... box(1)-2*width box(3)-3*height;... box(2)+3*width box(3)-2*height;... ]; % extract voronoi vertices and face structure [V, C] = voronoin([germs;farPoints]); % for each germ, determines the different lines % initialize graph structure, without edges and without faces nodes = V(2:end, :); edges = zeros(0, 2); faces = {}; for i=1:size(germs, 1) cell = C{i}; cell = cell-1; edges = [edges; sort([cell' cell([2:end 1])'], 2)]; %#ok faces{length(faces)+1} = cell; %#ok end edges = unique(edges, 'rows'); endfunction %!demo %! [n e f] = boundedVoronoi2d([0 1 0 1], rand(100, 2)); %! drawGraph(n, e); %! axis image ������geometry-3.0.0/inst/graphs/PaxHeaders.28738/grRemoveEdges.m�����������������������������������������0000644�0000000�0000000�00000000132�13066736044�020303� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/grRemoveEdges.m����������������������������������������������������������0000644�0001750�0001750�00000005702�13066736044�020463� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %GRREMOVEEDGES Remove several edges from a graph % % [NODES2 EDGES2] = grRemoveEdges(NODES, EDGES, EDGES2REMOVE) % Remove some edges in the edges list, and return the modified graph. % The NODES array is not modified. % % ----- % % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 13/08/2003. % % HISTORY : % 10/02/2004 : doc function [nodes2, edges2] = grRemoveEdges(nodes, edges, rmEdges) rmEdges = sort(rmEdges); % do not change the node list nodes2 = nodes; % number of edges N = size(edges, 1); NR = length(rmEdges); N2 = N - NR; % allocate memory for new edges list edges2 = zeros(N2, 2); % case of no edge to remove if NR == 0 nodes2 = nodes; edges2 = edges; return; end % process the first edge edges2(1:rmEdges(1)-1,:) = edges(1:rmEdges(1)-1,:); % process the classical edges for i = 2:NR %if rmEdges(i)-i < rmEdges(i-1)-i+2 % continue; %end edges2(rmEdges(i-1)-i+2:rmEdges(i)-i, :) = edges(rmEdges(i-1)+1:rmEdges(i)-1, :); end % process the last edge edges2(rmEdges(NR)-NR+1:N2, :) = edges(rmEdges(NR)+1:N, :); endfunction %!demo %! nodes = [0 0; 0 1; 1 1; 0.3 0.7]; %! edges = [1 2; 2 3; 3 1; 1 4; 2 4; 3 4]; %! [n2 e2] = grRemoveEdges (nodes, edges, 1:3); %! drawGraph (nodes,edges,{"k","markerfacecolor", "w"}, {"color","k"}); %! hold on %! drawGraph (n2,e2,'none', {"color","r"}); %! hold off ��������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/drawGraphEdges.m����������������������������������������0000644�0000000�0000000�00000000132�13066736044�020434� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/drawGraphEdges.m���������������������������������������������������������0000644�0001750�0001750�00000007635�13066736044�020623� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %DRAWGRAPHEDGES Draw edges of a graph % % drawGraphEdges(NODES, EDGES) % Draws a graph specified by a set of nodes (array N-by-2 or N-by-3, % corresponding to coordinate of each node), and a set of edges (an array % Ne-by-2, containing to the first and the second node of each edge). % % drawGraphEdges(..., SEDGES) % Specifies the draw mode for each element, as in the classical 'plot' % function. % Default drawing is a blue line for edges. % % % H = drawGraphEdges(...) % return handle to the set of edges. % % See also % drawGraph % % ------ % Author: David Legland % e-mail: david.legland@grignon.inra.fr % Created: 2005-11-24 % Copyright 2005 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas). function varargout = drawGraphEdges(varargin) %% Input argument processing % initialisations e = []; % check input arguments number if nargin == 0 help drawGraphEdges; return; end % extract handle of axis to draw on if isAxisHandle(varargin{1}) ax = varargin{1}; varargin(1) = []; else ax = gca; end % First extract the graph structure var = varargin{1}; if iscell(var) % TODO: should consider array of graph structures. % graph is stored as a cell array : first cell is nodes, second one is % edges, and third is faces n = var{1}; if length(var) > 1 e = var{2}; end varargin(1) = []; elseif isstruct(var) % graph is stored as a structure, with fields 'nodes', 'edges' n = var.nodes; e = var.edges; varargin(1) = []; else % graph is stored as set of variables: nodes + edges n = varargin{1}; e = varargin{2}; varargin(1:2) = []; end % check if there are edges to draw if size(e, 1) == 0 return; end % setup default drawing style if not specified if isempty(varargin) varargin = {'-b'}; end %% main drawing processing if size(n, 2) == 2 % Draw 2D edges x = [n(e(:,1), 1) n(e(:,2), 1)]'; y = [n(e(:,1), 2) n(e(:,2), 2)]'; he = plot(ax, x, y, varargin{:}); elseif size(n, 2) == 3 % Draw 3D edges x = [n(e(:,1), 1) n(e(:,2), 1)]'; y = [n(e(:,1), 2) n(e(:,2), 2)]'; z = [n(e(:,1), 3) n(e(:,2), 3)]'; he = plot3(ax, x, y, z, varargin{:}); end %% format output arguments if nargout == 1 varargout = {he}; end endfunction ���������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/PaxHeaders.28738/drawNodeLabels.m����������������������������������������0000644�0000000�0000000�00000000132�13066736044�020433� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.636870283 30 atime=1490795556.636870283 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/inst/graphs/drawNodeLabels.m���������������������������������������������������������0000644�0001750�0001750�00000006127�13066736044�020615� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2016 David Legland ## Copyright (C) 2004-2016 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2016 Adapted to Octave by Juan Pablo Carbajal ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1 Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## 2 Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ## ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ## DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ## CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ## OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %DRAWNODELABELS Draw values associated to graph nodes % % Usage: % drawNodeLabels(NODES, VALUES); % NODES: array of double, containing x and y values of nodes % VALUES is an array the same length of EDGES, containing values % associated to each edges of the graph. % % H = drawNodeLabels(...) % Returns array of handles to each text structure, making it possible to % change font, color, size % % ----- % author: David Legland % INRA - TPV URPOI - BIA IMASTE % created the 10/02/2003. % % HISTORY % 10/03/2004 included into lib/graph library function varargout = drawNodeLabels(nodes, value, varargin) % extract handle of axis to draw on if isAxisHandle(nodes) ax = nodes; nodes = value; value = varargin{1}; else ax = gca; end % number and dimension of nodes Nn = size(nodes, 1); Nd = size(nodes, 2); % check input size if length(value) ~= Nn error('Value array must have same length as node number'); end % allocate memory h = zeros(Nn, 1); axes(ax); if Nd == 2 % Draw labels of 2D nodes for i = 1:Nn x = nodes(i, 1); y = nodes(i, 2); h(i) = text(x, y, sprintf('%3d', floor(value(i)))); end elseif Nd == 3 % Draw labels of 3D nodes for i = 1:Nn x = nodes(i, 1); y = nodes(i, 2); z = nodes(i, 3); h(i) = text(x, y, z, sprintf('%3d', floor(value(i)))); end else error('Node dimension must be 2 or 3'); end if nargout == 1 varargout = {h}; end endfunction �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/PaxHeaders.28738/DESCRIPTION���������������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�014634� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.556868803 30 atime=1490795556.556868803 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/DESCRIPTION��������������������������������������������������������������������������0000644�0001750�0001750�00000001125�13066736044�015007� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Name: geometry Version: 3.0.0 Date: 27-03-2017 Author: Juan Pablo Carbajal , Philip Neuhius , Simeon Simeonov , David Legland , Maintainer: Juan Pablo Carbajal Title: Computational Geometry Description: Library for geometric computing extending MatGeom functions. Useful to create, transform, manipulate and display geometric primitives. Depends: octave (>= 4.0.1) Autoload: no License: GPLv3+, FreeBSD, Boost v1.0 Url: http://octave.sf.net, https://github.com/dlegland/matGeom �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/PaxHeaders.28738/COPYING�������������������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�014161� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.556868803 30 atime=1490795556.556868803 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/COPYING������������������������������������������������������������������������������0000644�0001750�0001750�00000104513�13066736044�014341� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/PaxHeaders.28738/NEWS����������������������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�013625� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.556868803 30 atime=1490795556.556868803 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/NEWS���������������������������������������������������������������������������������0000644�0001750�0001750�00000033530�13066736044�014005� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Summary of important user-visible changes for releases of the geometry package =============================================================================== geometry-3.0.0 Release Date: 27-03-2017 Release Manager: Juan Pablo Carbajal =============================================================================== This version of the package is not backward compatible for the following reasons: ** Functions have changed their name beltproblem --> beltProblem closed_path --> closedPath shapearea --> shapeArea shapecentroid --> shapeCentroid shapeplot --> plotShape shapetransform --> transformShape simplifypolygon --> simplifyPoligon simplifyPolyline --> simplifyPolyline ** Functions that are in GNU Octave core since 4.0.1 rad2deg deg2rad ** Added Functions isAxisHandle isPolygonCCW isPolygonCW_Clipper joinPolygons polygon2patch orientPolygon boundedVoronoi2d drawGraphEdges clipGraph grAdjacentEdges grAdjacentNodes grEdgeLengths centroidalVoronoi2d clipGraphPolygon cvtUpdate intersectEdgePolygon intersectLinePolygon isPointInPolygon polygonBounds polygonContains convexHull minimumCaliperDiameter grShortestPath drawNodeLabels nndist createRotation3dLineAngle drawPlane3d rotation3dAxisAndAngle boxToMesh checkMeshAdjacentFaces clipConvexPolyhedronHP clipMeshVertices createDodecahedron createDurerPolyhedron createIcosahedron createMengerSponge createOctahedron createRhombododecahedron createSoccerBall createTetrahedron createTetrakaidecahedron cylinderMesh drawFaceNormals drawPolyhedron ellipsoidMesh faceCentroids faceNormal intersectLineMesh3d intersectPlaneMesh mergeCoplanarFaces meshAdjacencyMatrix meshDihedralAngles meshEdgeFaces meshEdgeLength meshEdges meshFace meshFaceAdjacency meshFaceEdges meshFaceNumber meshFacePolygons meshSurfaceArea meshVolume minConvexHull polyhedra polyhedronCentroid polyhedronMeanBreadth polyhedronNormalAngle polyhedronSlice readMesh_off removeMeshVertices smoothMesh sphereMesh steinerPolytope subdivideMesh surfToMesh tetrahedronVolume torusMesh triangulateFaces trimMesh trimeshEdgeFaces trimeshMeanBreadth trimeshSurfaceArea vertexNormal distancePoints clipLine3d drawLine3d eulerAnglesToRotation3d intersectLineSphere linePosition3d recenterTransform3d transformLine3d transformVector3d intersectPolylines clipPolyline clipPolyline_clipper clipPolygon clipPolygon_clipper ** Improved Functions drawPolygon is more efficent when drawing polygons in cells and now it takes an axis handle as first argument (optional). Added demo and tests intersectEdges accepts tolerance as third argument polygon2patch demo fixed, missing third argument for patch. =============================================================================== geometry-2.1.1 Release Date: 2016-03-24 Release Manager: Juan Pablo Carbajal =============================================================================== ** Added Functions fillPolygon rectAsPolygon ** Improved Functions drawShape was not working due to missing functions. they have all been added now. ============================================================================== geometry-2.1.0 Release Date: 2016-02-04 Release Manager: Juan Pablo Carbajal =============================================================================== ** Added Functions projPointOnPolyline: the function is added for compatibility, but it is just a wrapper of distancePointPolyline. findClosestPoint ** Improved Functions distancePointPolyline is now updated with a spee dup of 100x. It also calculates the projections, so projPointOnPolyline is obsolete. =============================================================================== geometry-2.0.0 Release Date: 2015-04-27 Release Manager: Juan Pablo Carbajal =============================================================================== ** Geometry 2.0.0 is not compatible with versions of octave older than 4.0. Thi si due to inputParser being used in the functions curve2polyline, cov2ellipse and simplifypolyline. If you do not need this functions you should no problems using octave > 3.6.0 ** Removed functions oc_polybol is not part of geomtry anymore. This function is part of the octclip package. ** Added Functions planePoint ** Bug Fixes: - polynomialCurveSetFit had debug entries, now removed. ** Other changes: - closed_path demo code was improved. =============================================================================== geometry-1.7.0 Release Date: 2013-04-07 Release Manager: Juan Pablo Carbajal =============================================================================== ** Added Functions box3dVolume cart2cyl circle3dPoint cyl2cart drawCircle3d drawPoint3d createScaling3d drawCube createCube drawSphericalTriangle drawTorus revolutionSurface drawVector3d spheres drawPolyline drawPolynomialCurve polynomialCurveCentroid polynomialCurveDerivative polynomialCurveFit polynomialCurvePoint polynomialCurveSetFit polygonPoint polygonSubcurve ** Bug Fixes: - cov2ellipse scale and orientation of axis. =============================================================================== geometry-1.6.0 Release Date: 2012-10-12 Release Manager: Juan Pablo Carbajal =============================================================================== ** geometry doesn't autoloads anymore ** Added Functions anglePoints3d angles3d boxes3d geom3d_Contents lines3d planes3d points3d polygons3d vectors3d graphs_Contents meshes3d_Contents angleSort3d createPlane intersectLinePlane normalizePlane planeNormal planePosition projPointOnPlane sph2cart2 vectorAngle3d distancePointLine3d cart2sph2d createRotationOx createRotationOy createRotationOz createTranslation3d drawAxis3d drawCylinder drawSphere polygonArea3d transformPoint3d drawBox3d drawEdge3d drawMesh createCubeOctahedron boundingBox3d cart2sph2 circle3dOrigin circle3dPosition drawCircleArc3d drawPolygon3d drawSphericalEdge drawSphericalPolygon intersectPlaneSphere sph2cart2d ** Updated functions distancePoints ** Bug Fixes: - drawArrow was not working due to porting errors. =============================================================================== geometry-1.5.0 Release Date: 2012-06-05 Release Manager: Juan Pablo Carbajal =============================================================================== * Added functions: - cov2ellipse & ellipse2cov: transform between ellipses and covariances matrices. - beltproblem : Finds the four lines tangent to two circles with given centers and radii. This is the solution to the belt problem in 2D. - curveval : Evaluates a polynomial curve defined as a 2-by-N matrix. - curve2polyline : Converts a polynomial curve into a polyline by the adaptive sampling method. - simplifypolyline : Ramer-Douglas-Peucker algorithm to simplify polylines. - parametrize : Estimate a parametrization of a polygon/line based on the distance between the points. - curvature : Estimation of the curvature of a polygon/line based on polynomial approximation. - reversePolygon and reversePolyline : reverse the orders of the points in of polygon/line. - supportFunction : Compute support function of a polygon. - distancePointPolygon , distancePointPolyline , distancePolygons , expandPolygon , medialAxisConvex , polygonLoops , polygonSelfIntersections polylineSelfIntersections , splitPolygons - close_path : given a set of points in the plane calculate a piecewise linear simple path that passes through all points. * Changed functions: - distancePointEdge : Now the function computes the distance between all points and all edges. A third optional argument provides backward compatibility. * Solved bugs: - simplifypolygon returned empty polygons when points are repeated, i.e when the polygon is not correctly formed. - Removed installation warnings. =============================================================================== geometry-1.4.1 Release Date: 2012-03-24 Release Manager: Juan Pablo Carbajal =============================================================================== * Renamed functions - Contents renamed to geom2d_Contents to avoid clashes. * Deprecated functions - svgload, svgnormalize, svgpath2polygon: Use the methods in class svg. * Bug fixes - @svg/path2polygon - Fix addpath/rmpath installation warnings - Fix octclip/src/Makefile - Fix shapecentriod for piece-wise polynomial shapes. * Known issues - simplifypolygon returns empty polygons when points are repeated, i.e when the polygon is not correctly formed. =============================================================================== geometry-1.4.0 Release Date: 2012-01-25 Release Manager: Juan Pablo Carbajal =============================================================================== * Added basic geometric graphs creation and manipulation. =============================================================================== geometry-1.3.0 Release Date: 2011-11-24 Release Manager: Juan Pablo Carbajal =============================================================================== * Geometry merged with octCLIP. * Geometry autoloads. =============================================================================== geometry-1.2.2 Release Date: 2011-11-04 Release Manager: Juan Pablo Carbajal =============================================================================== * Improved SVG interface. Thanks to jwe and carandraug. * Adding files to manipulate and convert 2D shapes defined with smooth polynomials. shape2polygon shapearea shapecentroid shapeplot shapetransform * Inverted the order in the NEWS file. New entries are on top. =============================================================================== geometry-1.2.1 Release Date: 2011-11-02 Release Manager: Juan Pablo Carbajal =============================================================================== * Adding SVG object and demo for data2geom (converting SVG to msh format) =============================================================================== geometry-1.2.0 Release Date: 2011-10-21 Release Manager: Juan Pablo Carbajal =============================================================================== * All geom2d added createCircle createDirectedCircle createEdge medianLine Contents bisector cartesianLine drawArrow edges2d lines2d orthogonalLine parallelLine projPointOnLine drawCenteredEdge drawCircle drawCircleArc drawEllipse drawEllipseArc drawLabels drawOrientedBox drawParabola drawRect drawShape circles2d ellipses2d createVector inertiaEllipse changelog.txt readme.txt hexagonalGrid squareGrid triangleGrid intersectCircles intersectEdges intersectLineCircle isLeftOriented isPointInCircle isPointInEllipse isPointOnCircle isPointOnLine edgeLength edgePosition edgeToLine circleArcAsCurve circleAsPolygon crackPattern crackPattern2 distancePointEdge distancePointLine ellipseAsPolygon enclosingCircle radicalAxis reverseEdge reverseLine =============================================================================== geometry-1.1.3 Release Date: 2011-10-13 Release Manager: Juan Pablo Carbajal =============================================================================== * Continue to add geom2d from matGeom (transforms and points2d) createBasisTransform createHomothecy createLineReflection createRotation createScaling createTranslation transformPoint transforms2d fitAffineTransform2d transformEdge transformLine centroid distancePoints midPoint polarPoint drawPoint isCounterClockwise minDistancePoints pointOnLine points2d intersectLineEdge isPointOnEdge =============================================================================== geometry-1.1.2 Release Date: 2011-10-09 Release Manager: Juan Pablo Carbajal =============================================================================== * Continue to add geom2d from matGeom (rays and vectors) createRay drawEdge drawRay isParallel isPerpendicular isPointOnRay normalizeVector rays2d rotateVector transformVector vectorNorm vectors2d =============================================================================== geometry-1.1.1 Release Date: 2011-10-06 Release Manager: Juan Pablo Carbajal =============================================================================== * Continue to add geom2d from matGeom (boxes and clips) cbezier2poly boxes2d clipEdge clipLine clipPoints drawBezierCurve drawBox clipRay intersectBoxes intersectLines linePosition mergeBoxes randomPointInBox drawLine =============================================================================== geometry-1.1.0 Release Date: 2011-10-04 Release Manager: Juan Pablo Carbajal =============================================================================== * Starting to add geom2d from matGeom angle2Points angle3Points angleAbsDiff angleDiff angles2d angleSort createLine deg2rad edgeAngle lineAngle normalizeAngle rad2deg vectorAngle =============================================================================== geometry-1.0.1 Release Date: 2011-09-27 Release Manager: Juan Pablo Carbajal =============================================================================== Improvements to the docstrings of all functions. =============================================================================== geometry-1.0.0 Release Date: 2011-09-26 Release Manager: Juan Pablo Carbajal =============================================================================== ** First official release. =============================================================================== ������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/PaxHeaders.28738/src�����������������������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�013640� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.696871393 30 atime=1490795556.716871764 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/���������������������������������������������������������������������������������0002755�0001750�0001750�00000000000�13066736044�014073� 5����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/PaxHeaders.28738/Makefile��������������������������������������������������������0000644�0000000�0000000�00000000130�13066736044�015353� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������29 mtime=1490795556.69287132 29 atime=1490795556.69287132 30 ctime=1490795556.716871764 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/Makefile�������������������������������������������������������������������������0000644�0001750�0001750�00000000241�13066736044�015526� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������all: clipper.mex MKOCTFILE ?= mkoctfile %.mex: %.cpp $(MKOCTFILE) -Wall -mex -s clipper.cpp mexclipper.cpp clean: rm -f *.o octave-core core *.oct *.mex *~ ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/PaxHeaders.28738/mexclipper.cpp��������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016571� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.696871393 30 atime=1490795556.696871393 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/mexclipper.cpp�������������������������������������������������������������������0000644�0001750�0001750�00000027041�13066736044�016751� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* (C) 2012-2017 Angus Johnson Boost Software License - Version 1.0 - August 17th, 2003 http://www.boost.org/LICENSE_1_0.txt Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // mex clipper.cpp mexclipper.cpp // // Modified 2014-10-24, Jari Repo (JR), University West, jari.repo@hv.se // replaced "Polygons" to "Paths" // replaced "AddPolygons" by "AddPaths" // replaced the call to "OffsetPolygons" by use of the "ClipperOffset" class // Adapted 2017-01-24 Philip Nienhuis // allow clipping polylines #include "mex.h" #include "clipper.hpp" using namespace ClipperLib; //void read_polygons_MATLAB(const mxArray *prhs, Polygons &poly) void read_polygons_MATLAB(const mxArray *prhs, Paths &poly) { int id_x, id_y; unsigned int num_contours; unsigned int nx, ny; long64 *x, *y; const mxArray *x_in, *y_in; /* Checking if input is non empty Matlab-structure */ if (!mxIsStruct(prhs)) mexErrMsgTxt("Input needs to be structure."); if (!mxGetM(prhs) || !mxGetN(prhs)) mexErrMsgTxt("Empty structure."); /* Checking field names and data type */ id_x = mxGetFieldNumber(prhs,"x"); if (id_x==-1) mexErrMsgTxt("Input structure must contain a field 'x'."); x_in = mxGetFieldByNumber(prhs, 0, id_x); if (!mxIsInt64(x_in)) mexErrMsgTxt("Structure field 'x' must be of type INT64."); id_y = mxGetFieldNumber(prhs,"y"); if (id_y==-1) mexErrMsgTxt("Input structure must contain a field 'y'."); y_in = mxGetFieldByNumber(prhs, 0, id_y); if (!mxIsInt64(y_in)) mexErrMsgTxt("Structure field 'y' must be of type INT64."); num_contours = mxGetNumberOfElements(prhs); poly.resize(num_contours); for (unsigned i = 0; i < num_contours; i++){ x_in = mxGetFieldByNumber(prhs, i, id_x); y_in = mxGetFieldByNumber(prhs, i, id_y); nx = mxGetNumberOfElements(x_in); ny = mxGetNumberOfElements(y_in); if (nx!=ny) mexErrMsgTxt("Structure fields x and y must be the same length."); poly[i].resize(nx); x = (long64*)mxGetData(x_in); y = (long64*)mxGetData(y_in); for (unsigned j = 0; j < nx; j++){ poly[i][j].X = x[j]; poly[i][j].Y = y[j]; } } } //void write_polygons_MATLAB(mxArray *plhs, Polygons &solution) void write_polygons_MATLAB(mxArray *plhs, Paths &solution) { mxArray *x_out, *y_out; for (unsigned i = 0; i < solution.size(); ++i) { x_out = mxCreateDoubleMatrix(solution[i].size(), 1, mxREAL); y_out = mxCreateDoubleMatrix(solution[i].size(), 1, mxREAL); for (unsigned j = 0; j < solution[i].size(); ++j) { ((double*)mxGetPr(x_out))[j]=solution[i][j].X; ((double*)mxGetPr(y_out))[j]=solution[i][j].Y; } mxSetFieldByNumber(plhs,i,0,x_out); mxSetFieldByNumber(plhs,i,1,y_out); } } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { //Polygons subj, clip, solution; Paths subj, clip, solution; PolyTree solutionL; const char *field_names[] = {"x","y"}; mwSize dims[2]; if (nrhs == 0) { mexPrintf("OutPol = clipper(RefPol, ClipPol, Method, [RefF], [ClipF]);\n"); mexPrintf(" Clips polygons or polylines by Method:\n"); mexPrintf(" 0 - Difference (RefPol - ClipPol)\n"); mexPrintf(" 1 - Intersection\n"); mexPrintf(" 2 - Xor (polygons only)\n"); mexPrintf(" 3 - Union (polygons only)\n"); mexPrintf(" Optionally specifying Fill Types for the polygons (polygons only):\n"); mexPrintf(" 0 - Even-Odd (default)\n"); mexPrintf(" 1 - Non-Zero\n"); mexPrintf(" 2 - Positive\n"); mexPrintf(" 3 - Negative\n\n"); mexPrintf("Or:\n\n"); mexPrintf("OutPol = clipper(RefPol, Delta, MiterLimit);\n"); mexPrintf(" Offsets RefPol by Delta (+: outset, -: inset).\n"); mexPrintf(" MiterLimit * Delta = max distance of new vertex.\n"); mexPrintf(" MiterLimit = 1 for square corners.\n"); mexPrintf(" MiterLimit = 0 for round corners.\n\n"); mexPrintf("Or:\n\n"); mexPrintf("Orientation = clipper(RefPol);\n"); mexPrintf(" Returns boolean orientations of polygons.\n\n"); mexPrintf("All polygons are structures with the fields ...\n"); mexPrintf(" .x: x-coordinates of contour\n"); mexPrintf(" .y: y-coordinates of contour\n"); mexPrintf("All polygons may contain several contours.\n"); mexPrintf("\nPolygon Clipping Routine based on clipper v4.7.5.\n"); mexPrintf(" Credit goes to Angus Johnson\n"); mexPrintf(" http://www.angusj.com/delphi/clipper.php\n\n"); return;} /* Check number of arguments */ if (nlhs != 1) mexErrMsgTxt("One output required."); if (nrhs == 1) { // Find the orientation of input polygons bool orient; read_polygons_MATLAB(prhs[0], subj); plhs[0] = mxCreateDoubleMatrix(subj.size(), 1, mxREAL); for (unsigned i = 0; i < subj.size(); ++i) { orient = Orientation(subj[i]); ((double*)mxGetPr(plhs[0]))[i] = (double)orient; } } else if (nrhs >= 3) { if (!mxIsDouble(prhs[2]) || mxGetM(prhs[2])!=1 || mxGetN(prhs[2])!=1) mexErrMsgTxt("Third input must be scalar."); if (mxIsStruct(prhs[1])) { // Clip two input polygons int ct, clpl; clpl = 0; ct = mxGetScalar(prhs[2]); ClipType CT = ctDifference; switch (ct){ case 0: CT=ctDifference; break; case 1: CT=ctIntersection; break; case 2: CT=ctXor; break; case 3: CT=ctUnion; break; default: mexErrMsgTxt("Third input must be 0, 1, 2, or 3."); } PolyFillType SFT = pftEvenOdd; if (nrhs >= 4) { if (!mxIsDouble(prhs[3]) || mxGetM(prhs[3])!=1 || mxGetN(prhs[3])!=1) mexErrMsgTxt("Fourth input must be scalar if specified."); int sft; sft = mxGetScalar(prhs[3]); switch (sft){ case 0: SFT = pftEvenOdd; break; case 1: SFT = pftNonZero; break; case 2: SFT = pftPositive; break; case 3: SFT = pftNegative; break; case -1: clpl = 1; SFT=pftEvenOdd; break; default: mexErrMsgTxt("Fourth input must be 0, 1, 2, 3, or -1."); } } PolyFillType CFT = pftEvenOdd; if (nrhs >= 5) { if (!mxIsDouble(prhs[4]) || mxGetM(prhs[4])!=1 || mxGetN(prhs[4])!=1) mexErrMsgTxt("Fifth input must be scalar if specified."); int cft; cft=mxGetScalar(prhs[4]); switch (cft){ case 0: CFT = pftEvenOdd; break; case 1: CFT = pftNonZero; break; case 2: CFT = pftPositive; break; case 3: CFT = pftNegative; break; default: mexErrMsgTxt("Fifth input must be 0, 1, 2, or 3."); } } /* Import polygons to structures */ read_polygons_MATLAB(prhs[0], subj); read_polygons_MATLAB(prhs[1], clip); Clipper c; if (clpl) { c.AddPaths(subj, ptSubject, false); //assume polylines c.AddPaths(clip, ptClip, true); if (c.Execute(CT, solutionL, SFT, CFT)){ dims[0] = 1; OpenPathsFromPolyTree(solutionL, solution); dims[1] = solution.size(); plhs[0] = mxCreateStructArray(2, dims, 2, field_names); write_polygons_MATLAB(plhs[0], solution); } else mexErrMsgTxt("Clipper Error."); } else { c.AddPaths(subj, ptSubject, true); //assume closed polygons c.AddPaths(clip, ptClip, true); if (c.Execute(CT, solution, SFT, CFT)){ dims[0] = 1; dims[1] = solution.size(); plhs[0] = mxCreateStructArray(2, dims, 2, field_names); write_polygons_MATLAB(plhs[0], solution); } else mexErrMsgTxt("Clipper Error."); } } else { // Offset single input polygon if (!mxIsDouble(prhs[1]) || mxGetM(prhs[1])!=1 || mxGetN(prhs[1])!=1) mexErrMsgTxt("Second input must be either a structure or a scalar double."); if (nrhs > 3) mexPrintf("Ignoring fill type arguments for offsetting.\n"); /* Import polygons to structures */ read_polygons_MATLAB(prhs[0], subj); JoinType jt; double delta, ml; delta = mxGetScalar(prhs[1]); ml = mxGetScalar(prhs[2]); if (ml==0) jt = jtRound; else if (ml==1) jt = jtSquare; else jt = jtMiter; ClipperOffset offs( ml ); //enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound}; offs.AddPaths(subj,jt,etClosedPolygon); offs.Execute(solution, delta); dims[0] = 1; dims[1] = solution.size(); plhs[0] = mxCreateStructArray(2, dims, 2, field_names); write_polygons_MATLAB(plhs[0], solution); offs.Clear(); } } else mexErrMsgTxt("One or three inputs required."); } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/PaxHeaders.28738/clipper.cpp�����������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016057� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.696871393 30 atime=1490795556.696871393 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/clipper.cpp����������������������������������������������������������������������0000644�0001750�0001750�00000416773�13066736044�016255� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* (C) 2012-2017 Angus Johnson Boost Software License - Version 1.0 - August 17th, 2003 http://www.boost.org/LICENSE_1_0.txt Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /******************************************************************************* * * * Author : Angus Johnson * * Version : 6.4.2 * * Date : 27 February 2017 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2010-2017 * * * * License: * * Use, modification & distribution is subject to Boost Software License Ver 1. * * http://www.boost.org/LICENSE_1_0.txt * * * * Attributions: * * The code in this library is an extension of Bala Vatti's clipping algorithm: * * "A generic solution to polygon clipping" * * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. * * http://portal.acm.org/citation.cfm?id=129906 * * * * Computer graphics and geometric modeling: implementation and algorithms * * By Max K. Agoston * * Springer; 1 edition (January 4, 2005) * * http://books.google.com/books?q=vatti+clipping+agoston * * * * See also: * * "Polygon Offsetting by Computing Winding Numbers" * * Paper no. DETC2005-85513 pp. 565-575 * * ASME 2005 International Design Engineering Technical Conferences * * and Computers and Information in Engineering Conference (IDETC/CIE2005) * * September 24-28, 2005 , Long Beach, California, USA * * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf * * * *******************************************************************************/ /******************************************************************************* * * * This is a translation of the Delphi Clipper library and the naming style * * used has retained a Delphi flavour. * * * *******************************************************************************/ #include "clipper.hpp" #include #include #include #include #include #include #include #include namespace ClipperLib { static double const pi = 3.141592653589793238; static double const two_pi = pi *2; static double const def_arc_tolerance = 0.25; enum Direction { dRightToLeft, dLeftToRight }; static int const Unassigned = -1; //edge not currently 'owning' a solution static int const Skip = -2; //edge that would otherwise close a path #define HORIZONTAL (-1.0E+40) #define TOLERANCE (1.0e-20) #define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE)) struct TEdge { IntPoint Bot; IntPoint Curr; //current (updated for every new scanbeam) IntPoint Top; double Dx; PolyType PolyTyp; EdgeSide Side; //side only refers to current side of solution poly int WindDelta; //1 or -1 depending on winding direction int WindCnt; int WindCnt2; //winding count of the opposite polytype int OutIdx; TEdge *Next; TEdge *Prev; TEdge *NextInLML; TEdge *NextInAEL; TEdge *PrevInAEL; TEdge *NextInSEL; TEdge *PrevInSEL; }; struct IntersectNode { TEdge *Edge1; TEdge *Edge2; IntPoint Pt; }; struct LocalMinimum { cInt Y; TEdge *LeftBound; TEdge *RightBound; }; struct OutPt; //OutRec: contains a path in the clipping solution. Edges in the AEL will //carry a pointer to an OutRec when they are part of the clipping solution. struct OutRec { int Idx; bool IsHole; bool IsOpen; OutRec *FirstLeft; //see comments in clipper.pas PolyNode *PolyNd; OutPt *Pts; OutPt *BottomPt; }; struct OutPt { int Idx; IntPoint Pt; OutPt *Next; OutPt *Prev; }; struct Join { OutPt *OutPt1; OutPt *OutPt2; IntPoint OffPt; }; struct LocMinSorter { inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2) { return locMin2.Y < locMin1.Y; } }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ inline cInt Round(double val) { if ((val < 0)) return static_cast(val - 0.5); else return static_cast(val + 0.5); } //------------------------------------------------------------------------------ inline cInt Abs(cInt val) { return val < 0 ? -val : val; } //------------------------------------------------------------------------------ // PolyTree methods ... //------------------------------------------------------------------------------ void PolyTree::Clear() { for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i) delete AllNodes[i]; AllNodes.resize(0); Childs.resize(0); } //------------------------------------------------------------------------------ PolyNode* PolyTree::GetFirst() const { if (!Childs.empty()) return Childs[0]; else return 0; } //------------------------------------------------------------------------------ int PolyTree::Total() const { int result = (int)AllNodes.size(); //with negative offsets, ignore the hidden outer polygon ... if (result > 0 && Childs[0] != AllNodes[0]) result--; return result; } //------------------------------------------------------------------------------ // PolyNode methods ... //------------------------------------------------------------------------------ PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false) { } //------------------------------------------------------------------------------ int PolyNode::ChildCount() const { return (int)Childs.size(); } //------------------------------------------------------------------------------ void PolyNode::AddChild(PolyNode& child) { unsigned cnt = (unsigned)Childs.size(); Childs.push_back(&child); child.Parent = this; child.Index = cnt; } //------------------------------------------------------------------------------ PolyNode* PolyNode::GetNext() const { if (!Childs.empty()) return Childs[0]; else return GetNextSiblingUp(); } //------------------------------------------------------------------------------ PolyNode* PolyNode::GetNextSiblingUp() const { if (!Parent) //protects against PolyTree.GetNextSiblingUp() return 0; else if (Index == Parent->Childs.size() - 1) return Parent->GetNextSiblingUp(); else return Parent->Childs[Index + 1]; } //------------------------------------------------------------------------------ bool PolyNode::IsHole() const { bool result = true; PolyNode* node = Parent; while (node) { result = !result; node = node->Parent; } return result; } //------------------------------------------------------------------------------ bool PolyNode::IsOpen() const { return m_IsOpen; } //------------------------------------------------------------------------------ #ifndef use_int32 //------------------------------------------------------------------------------ // Int128 class (enables safe math on signed 64bit integers) // eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1 // Int128 val2((long64)9223372036854775807); // Int128 val3 = val1 * val2; // val3.AsString => "85070591730234615847396907784232501249" (8.5e+37) //------------------------------------------------------------------------------ class Int128 { public: ulong64 lo; long64 hi; Int128(long64 _lo = 0) { lo = (ulong64)_lo; if (_lo < 0) hi = -1; else hi = 0; } Int128(const Int128 &val): lo(val.lo), hi(val.hi){} Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){} Int128& operator = (const long64 &val) { lo = (ulong64)val; if (val < 0) hi = -1; else hi = 0; return *this; } bool operator == (const Int128 &val) const {return (hi == val.hi && lo == val.lo);} bool operator != (const Int128 &val) const { return !(*this == val);} bool operator > (const Int128 &val) const { if (hi != val.hi) return hi > val.hi; else return lo > val.lo; } bool operator < (const Int128 &val) const { if (hi != val.hi) return hi < val.hi; else return lo < val.lo; } bool operator >= (const Int128 &val) const { return !(*this < val);} bool operator <= (const Int128 &val) const { return !(*this > val);} Int128& operator += (const Int128 &rhs) { hi += rhs.hi; lo += rhs.lo; if (lo < rhs.lo) hi++; return *this; } Int128 operator + (const Int128 &rhs) const { Int128 result(*this); result+= rhs; return result; } Int128& operator -= (const Int128 &rhs) { *this += -rhs; return *this; } Int128 operator - (const Int128 &rhs) const { Int128 result(*this); result -= rhs; return result; } Int128 operator-() const //unary negation { if (lo == 0) return Int128(-hi, 0); else return Int128(~hi, ~lo + 1); } operator double() const { const double shift64 = 18446744073709551616.0; //2^64 if (hi < 0) { if (lo == 0) return (double)hi * shift64; else return -(double)(~lo + ~hi * shift64); } else return (double)(lo + hi * shift64); } }; //------------------------------------------------------------------------------ Int128 Int128Mul (long64 lhs, long64 rhs) { bool negate = (lhs < 0) != (rhs < 0); if (lhs < 0) lhs = -lhs; ulong64 int1Hi = ulong64(lhs) >> 32; ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF); if (rhs < 0) rhs = -rhs; ulong64 int2Hi = ulong64(rhs) >> 32; ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF); //nb: see comments in clipper.pas ulong64 a = int1Hi * int2Hi; ulong64 b = int1Lo * int2Lo; ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi; Int128 tmp; tmp.hi = long64(a + (c >> 32)); tmp.lo = long64(c << 32); tmp.lo += long64(b); if (tmp.lo < b) tmp.hi++; if (negate) tmp = -tmp; return tmp; }; #endif //------------------------------------------------------------------------------ // Miscellaneous global functions //------------------------------------------------------------------------------ bool Orientation(const Path &poly) { return Area(poly) >= 0; } //------------------------------------------------------------------------------ double Area(const Path &poly) { int size = (int)poly.size(); if (size < 3) return 0; double a = 0; for (int i = 0, j = size -1; i < size; ++i) { a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y); j = i; } return -a * 0.5; } //------------------------------------------------------------------------------ double Area(const OutPt *op) { const OutPt *startOp = op; if (!op) return 0; double a = 0; do { a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y); op = op->Next; } while (op != startOp); return a * 0.5; } //------------------------------------------------------------------------------ double Area(const OutRec &outRec) { return Area(outRec.Pts); } //------------------------------------------------------------------------------ bool PointIsVertex(const IntPoint &Pt, OutPt *pp) { OutPt *pp2 = pp; do { if (pp2->Pt == Pt) return true; pp2 = pp2->Next; } while (pp2 != pp); return false; } //------------------------------------------------------------------------------ //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf int PointInPolygon(const IntPoint &pt, const Path &path) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary int result = 0; size_t cnt = path.size(); if (cnt < 3) return 0; IntPoint ip = path[0]; for(size_t i = 1; i <= cnt; ++i) { IntPoint ipNext = (i == cnt ? path[0] : path[i]); if (ipNext.Y == pt.Y) { if ((ipNext.X == pt.X) || (ip.Y == pt.Y && ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1; } if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y)) { if (ip.X >= pt.X) { if (ipNext.X > pt.X) result = 1 - result; else { double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); if (!d) return -1; if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; } } else { if (ipNext.X > pt.X) { double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); if (!d) return -1; if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; } } } ip = ipNext; } return result; } //------------------------------------------------------------------------------ int PointInPolygon (const IntPoint &pt, OutPt *op) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary int result = 0; OutPt* startOp = op; for(;;) { if (op->Next->Pt.Y == pt.Y) { if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y && ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1; } if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y)) { if (op->Pt.X >= pt.X) { if (op->Next->Pt.X > pt.X) result = 1 - result; else { double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y); if (!d) return -1; if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result; } } else { if (op->Next->Pt.X > pt.X) { double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y); if (!d) return -1; if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result; } } } op = op->Next; if (startOp == op) break; } return result; } //------------------------------------------------------------------------------ bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2) { OutPt* op = OutPt1; do { //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon int res = PointInPolygon(op->Pt, OutPt2); if (res >= 0) return res > 0; op = op->Next; } while (op != OutPt1); return true; } //---------------------------------------------------------------------- bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range) { #ifndef use_int32 if (UseFullInt64Range) return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) == Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y); else #endif return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) == (e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y); } //------------------------------------------------------------------------------ bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3, bool UseFullInt64Range) { #ifndef use_int32 if (UseFullInt64Range) return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y); else #endif return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y); } //------------------------------------------------------------------------------ bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range) { #ifndef use_int32 if (UseFullInt64Range) return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y); else #endif return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y); } //------------------------------------------------------------------------------ inline bool IsHorizontal(TEdge &e) { return e.Dx == HORIZONTAL; } //------------------------------------------------------------------------------ inline double GetDx(const IntPoint pt1, const IntPoint pt2) { return (pt1.Y == pt2.Y) ? HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y); } //--------------------------------------------------------------------------- inline void SetDx(TEdge &e) { cInt dy = (e.Top.Y - e.Bot.Y); if (dy == 0) e.Dx = HORIZONTAL; else e.Dx = (double)(e.Top.X - e.Bot.X) / dy; } //--------------------------------------------------------------------------- inline void SwapSides(TEdge &Edge1, TEdge &Edge2) { EdgeSide Side = Edge1.Side; Edge1.Side = Edge2.Side; Edge2.Side = Side; } //------------------------------------------------------------------------------ inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2) { int OutIdx = Edge1.OutIdx; Edge1.OutIdx = Edge2.OutIdx; Edge2.OutIdx = OutIdx; } //------------------------------------------------------------------------------ inline cInt TopX(TEdge &edge, const cInt currentY) { return ( currentY == edge.Top.Y ) ? edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y)); } //------------------------------------------------------------------------------ void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip) { #ifdef use_xyz ip.Z = 0; #endif double b1, b2; if (Edge1.Dx == Edge2.Dx) { ip.Y = Edge1.Curr.Y; ip.X = TopX(Edge1, ip.Y); return; } else if (Edge1.Dx == 0) { ip.X = Edge1.Bot.X; if (IsHorizontal(Edge2)) ip.Y = Edge2.Bot.Y; else { b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx); ip.Y = Round(ip.X / Edge2.Dx + b2); } } else if (Edge2.Dx == 0) { ip.X = Edge2.Bot.X; if (IsHorizontal(Edge1)) ip.Y = Edge1.Bot.Y; else { b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx); ip.Y = Round(ip.X / Edge1.Dx + b1); } } else { b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx; b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx; double q = (b2-b1) / (Edge1.Dx - Edge2.Dx); ip.Y = Round(q); if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) ip.X = Round(Edge1.Dx * q + b1); else ip.X = Round(Edge2.Dx * q + b2); } if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y) { if (Edge1.Top.Y > Edge2.Top.Y) ip.Y = Edge1.Top.Y; else ip.Y = Edge2.Top.Y; if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) ip.X = TopX(Edge1, ip.Y); else ip.X = TopX(Edge2, ip.Y); } //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ... if (ip.Y > Edge1.Curr.Y) { ip.Y = Edge1.Curr.Y; //use the more vertical edge to derive X ... if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx)) ip.X = TopX(Edge2, ip.Y); else ip.X = TopX(Edge1, ip.Y); } } //------------------------------------------------------------------------------ void ReversePolyPtLinks(OutPt *pp) { if (!pp) return; OutPt *pp1, *pp2; pp1 = pp; do { pp2 = pp1->Next; pp1->Next = pp1->Prev; pp1->Prev = pp2; pp1 = pp2; } while( pp1 != pp ); } //------------------------------------------------------------------------------ void DisposeOutPts(OutPt*& pp) { if (pp == 0) return; pp->Prev->Next = 0; while( pp ) { OutPt *tmpPp = pp; pp = pp->Next; delete tmpPp; } } //------------------------------------------------------------------------------ inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt) { std::memset(e, 0, sizeof(TEdge)); e->Next = eNext; e->Prev = ePrev; e->Curr = Pt; e->OutIdx = Unassigned; } //------------------------------------------------------------------------------ void InitEdge2(TEdge& e, PolyType Pt) { if (e.Curr.Y >= e.Next->Curr.Y) { e.Bot = e.Curr; e.Top = e.Next->Curr; } else { e.Top = e.Curr; e.Bot = e.Next->Curr; } SetDx(e); e.PolyTyp = Pt; } //------------------------------------------------------------------------------ TEdge* RemoveEdge(TEdge* e) { //removes e from double_linked_list (but without removing from memory) e->Prev->Next = e->Next; e->Next->Prev = e->Prev; TEdge* result = e->Next; e->Prev = 0; //flag as removed (see ClipperBase.Clear) return result; } //------------------------------------------------------------------------------ inline void ReverseHorizontal(TEdge &e) { //swap horizontal edges' Top and Bottom x's so they follow the natural //progression of the bounds - ie so their xbots will align with the //adjoining lower edge. [Helpful in the ProcessHorizontal() method.] std::swap(e.Top.X, e.Bot.X); #ifdef use_xyz std::swap(e.Top.Z, e.Bot.Z); #endif } //------------------------------------------------------------------------------ void SwapPoints(IntPoint &pt1, IntPoint &pt2) { IntPoint tmp = pt1; pt1 = pt2; pt2 = tmp; } //------------------------------------------------------------------------------ bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a, IntPoint pt2b, IntPoint &pt1, IntPoint &pt2) { //precondition: segments are Collinear. if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y)) { if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b); if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b); if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a; if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b; return pt1.X < pt2.X; } else { if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b); if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b); if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a; if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b; return pt1.Y > pt2.Y; } } //------------------------------------------------------------------------------ bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2) { OutPt *p = btmPt1->Prev; while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev; double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt)); p = btmPt1->Next; while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next; double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt)); p = btmPt2->Prev; while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev; double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt)); p = btmPt2->Next; while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next; double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt)); if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) && std::min(dx1p, dx1n) == std::min(dx2p, dx2n)) return Area(btmPt1) > 0; //if otherwise identical use orientation else return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n); } //------------------------------------------------------------------------------ OutPt* GetBottomPt(OutPt *pp) { OutPt* dups = 0; OutPt* p = pp->Next; while (p != pp) { if (p->Pt.Y > pp->Pt.Y) { pp = p; dups = 0; } else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X) { if (p->Pt.X < pp->Pt.X) { dups = 0; pp = p; } else { if (p->Next != pp && p->Prev != pp) dups = p; } } p = p->Next; } if (dups) { //there appears to be at least 2 vertices at BottomPt so ... while (dups != p) { if (!FirstIsBottomPt(p, dups)) pp = dups; dups = dups->Next; while (dups->Pt != pp->Pt) dups = dups->Next; } } return pp; } //------------------------------------------------------------------------------ bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3) { if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2)) return false; else if (pt1.X != pt3.X) return (pt2.X > pt1.X) == (pt2.X < pt3.X); else return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y); } //------------------------------------------------------------------------------ bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b) { if (seg1a > seg1b) std::swap(seg1a, seg1b); if (seg2a > seg2b) std::swap(seg2a, seg2b); return (seg1a < seg2b) && (seg2a < seg1b); } //------------------------------------------------------------------------------ // ClipperBase class methods ... //------------------------------------------------------------------------------ ClipperBase::ClipperBase() //constructor { m_CurrentLM = m_MinimaList.begin(); //begin() == end() here m_UseFullRange = false; } //------------------------------------------------------------------------------ ClipperBase::~ClipperBase() //destructor { Clear(); } //------------------------------------------------------------------------------ void RangeTest(const IntPoint& Pt, bool& useFullRange) { if (useFullRange) { if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange) throw clipperException("Coordinate outside allowed range"); } else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange) { useFullRange = true; RangeTest(Pt, useFullRange); } } //------------------------------------------------------------------------------ TEdge* FindNextLocMin(TEdge* E) { for (;;) { while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next; if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break; while (IsHorizontal(*E->Prev)) E = E->Prev; TEdge* E2 = E; while (IsHorizontal(*E)) E = E->Next; if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz. if (E2->Prev->Bot.X < E->Bot.X) E = E2; break; } return E; } //------------------------------------------------------------------------------ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) { TEdge *Result = E; TEdge *Horz = 0; if (E->OutIdx == Skip) { //if edges still remain in the current bound beyond the skip edge then //create another LocMin and call ProcessBound once more if (NextIsForward) { while (E->Top.Y == E->Next->Bot.Y) E = E->Next; //don't include top horizontals when parsing a bound a second time, //they will be contained in the opposite bound ... while (E != Result && IsHorizontal(*E)) E = E->Prev; } else { while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev; while (E != Result && IsHorizontal(*E)) E = E->Next; } if (E == Result) { if (NextIsForward) Result = E->Next; else Result = E->Prev; } else { //there are more edges in the bound beyond result starting with E if (NextIsForward) E = Result->Next; else E = Result->Prev; MinimaList::value_type locMin; locMin.Y = E->Bot.Y; locMin.LeftBound = 0; locMin.RightBound = E; E->WindDelta = 0; Result = ProcessBound(E, NextIsForward); m_MinimaList.push_back(locMin); } return Result; } TEdge *EStart; if (IsHorizontal(*E)) { //We need to be careful with open paths because this may not be a //true local minima (ie E may be following a skip edge). //Also, consecutive horz. edges may start heading left before going right. if (NextIsForward) EStart = E->Prev; else EStart = E->Next; if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge { if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X) ReverseHorizontal(*E); } else if (EStart->Bot.X != E->Bot.X) ReverseHorizontal(*E); } EStart = E; if (NextIsForward) { while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip) Result = Result->Next; if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip) { //nb: at the top of a bound, horizontals are added to the bound //only when the preceding edge attaches to the horizontal's left vertex //unless a Skip edge is encountered when that becomes the top divide Horz = Result; while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev; if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev; } while (E != Result) { E->NextInLML = E->Next; if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); E = E->Next; } if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); Result = Result->Next; //move to the edge just beyond current bound } else { while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip) Result = Result->Prev; if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip) { Horz = Result; while (IsHorizontal(*Horz->Next)) Horz = Horz->Next; if (Horz->Next->Top.X == Result->Prev->Top.X || Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next; } while (E != Result) { E->NextInLML = E->Prev; if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) ReverseHorizontal(*E); E = E->Prev; } if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) ReverseHorizontal(*E); Result = Result->Prev; //move to the edge just beyond current bound } return Result; } //------------------------------------------------------------------------------ bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed) { #ifdef use_lines if (!Closed && PolyTyp == ptClip) throw clipperException("AddPath: Open paths must be subject."); #else if (!Closed) throw clipperException("AddPath: Open paths have been disabled."); #endif int highI = (int)pg.size() -1; if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI; while (highI > 0 && (pg[highI] == pg[highI -1])) --highI; if ((Closed && highI < 2) || (!Closed && highI < 1)) return false; //create a new edge array ... TEdge *edges = new TEdge [highI +1]; bool IsFlat = true; //1. Basic (first) edge initialization ... try { edges[1].Curr = pg[1]; RangeTest(pg[0], m_UseFullRange); RangeTest(pg[highI], m_UseFullRange); InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]); InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]); for (int i = highI - 1; i >= 1; --i) { RangeTest(pg[i], m_UseFullRange); InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]); } } catch(...) { delete [] edges; throw; //range test fails } TEdge *eStart = &edges[0]; //2. Remove duplicate vertices, and (when closed) collinear edges ... TEdge *E = eStart, *eLoopStop = eStart; for (;;) { //nb: allows matching start and end points when not Closed ... if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart)) { if (E == E->Next) break; if (E == eStart) eStart = E->Next; E = RemoveEdge(E); eLoopStop = E; continue; } if (E->Prev == E->Next) break; //only two vertices else if (Closed && SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) && (!m_PreserveCollinear || !Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr))) { //Collinear edges are allowed for open paths but in closed paths //the default is to merge adjacent collinear edges into a single edge. //However, if the PreserveCollinear property is enabled, only overlapping //collinear edges (ie spikes) will be removed from closed paths. if (E == eStart) eStart = E->Next; E = RemoveEdge(E); E = E->Prev; eLoopStop = E; continue; } E = E->Next; if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break; } if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next))) { delete [] edges; return false; } if (!Closed) { m_HasOpenPaths = true; eStart->Prev->OutIdx = Skip; } //3. Do second stage of edge initialization ... E = eStart; do { InitEdge2(*E, PolyTyp); E = E->Next; if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false; } while (E != eStart); //4. Finally, add edge bounds to LocalMinima list ... //Totally flat paths must be handled differently when adding them //to LocalMinima list to avoid endless loops etc ... if (IsFlat) { if (Closed) { delete [] edges; return false; } E->Prev->OutIdx = Skip; MinimaList::value_type locMin; locMin.Y = E->Bot.Y; locMin.LeftBound = 0; locMin.RightBound = E; locMin.RightBound->Side = esRight; locMin.RightBound->WindDelta = 0; for (;;) { if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); if (E->Next->OutIdx == Skip) break; E->NextInLML = E->Next; E = E->Next; } m_MinimaList.push_back(locMin); m_edges.push_back(edges); return true; } m_edges.push_back(edges); bool leftBoundIsForward; TEdge* EMin = 0; //workaround to avoid an endless loop in the while loop below when //open paths have matching start and end points ... if (E->Prev->Bot == E->Prev->Top) E = E->Next; for (;;) { E = FindNextLocMin(E); if (E == EMin) break; else if (!EMin) EMin = E; //E and E.Prev now share a local minima (left aligned if horizontal). //Compare their slopes to find which starts which bound ... MinimaList::value_type locMin; locMin.Y = E->Bot.Y; if (E->Dx < E->Prev->Dx) { locMin.LeftBound = E->Prev; locMin.RightBound = E; leftBoundIsForward = false; //Q.nextInLML = Q.prev } else { locMin.LeftBound = E; locMin.RightBound = E->Prev; leftBoundIsForward = true; //Q.nextInLML = Q.next } if (!Closed) locMin.LeftBound->WindDelta = 0; else if (locMin.LeftBound->Next == locMin.RightBound) locMin.LeftBound->WindDelta = -1; else locMin.LeftBound->WindDelta = 1; locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta; E = ProcessBound(locMin.LeftBound, leftBoundIsForward); if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward); TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward); if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward); if (locMin.LeftBound->OutIdx == Skip) locMin.LeftBound = 0; else if (locMin.RightBound->OutIdx == Skip) locMin.RightBound = 0; m_MinimaList.push_back(locMin); if (!leftBoundIsForward) E = E2; } return true; } //------------------------------------------------------------------------------ bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed) { bool result = false; for (Paths::size_type i = 0; i < ppg.size(); ++i) if (AddPath(ppg[i], PolyTyp, Closed)) result = true; return result; } //------------------------------------------------------------------------------ void ClipperBase::Clear() { DisposeLocalMinimaList(); for (EdgeList::size_type i = 0; i < m_edges.size(); ++i) { TEdge* edges = m_edges[i]; delete [] edges; } m_edges.clear(); m_UseFullRange = false; m_HasOpenPaths = false; } //------------------------------------------------------------------------------ void ClipperBase::Reset() { m_CurrentLM = m_MinimaList.begin(); if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter()); m_Scanbeam = ScanbeamList(); //clears/resets priority_queue //reset all edges ... for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm) { InsertScanbeam(lm->Y); TEdge* e = lm->LeftBound; if (e) { e->Curr = e->Bot; e->Side = esLeft; e->OutIdx = Unassigned; } e = lm->RightBound; if (e) { e->Curr = e->Bot; e->Side = esRight; e->OutIdx = Unassigned; } } m_ActiveEdges = 0; m_CurrentLM = m_MinimaList.begin(); } //------------------------------------------------------------------------------ void ClipperBase::DisposeLocalMinimaList() { m_MinimaList.clear(); m_CurrentLM = m_MinimaList.begin(); } //------------------------------------------------------------------------------ bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin) { if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false; locMin = &(*m_CurrentLM); ++m_CurrentLM; return true; } //------------------------------------------------------------------------------ IntRect ClipperBase::GetBounds() { IntRect result; MinimaList::iterator lm = m_MinimaList.begin(); if (lm == m_MinimaList.end()) { result.left = result.top = result.right = result.bottom = 0; return result; } result.left = lm->LeftBound->Bot.X; result.top = lm->LeftBound->Bot.Y; result.right = lm->LeftBound->Bot.X; result.bottom = lm->LeftBound->Bot.Y; while (lm != m_MinimaList.end()) { //todo - needs fixing for open paths result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y); TEdge* e = lm->LeftBound; for (;;) { TEdge* bottomE = e; while (e->NextInLML) { if (e->Bot.X < result.left) result.left = e->Bot.X; if (e->Bot.X > result.right) result.right = e->Bot.X; e = e->NextInLML; } result.left = std::min(result.left, e->Bot.X); result.right = std::max(result.right, e->Bot.X); result.left = std::min(result.left, e->Top.X); result.right = std::max(result.right, e->Top.X); result.top = std::min(result.top, e->Top.Y); if (bottomE == lm->LeftBound) e = lm->RightBound; else break; } ++lm; } return result; } //------------------------------------------------------------------------------ void ClipperBase::InsertScanbeam(const cInt Y) { m_Scanbeam.push(Y); } //------------------------------------------------------------------------------ bool ClipperBase::PopScanbeam(cInt &Y) { if (m_Scanbeam.empty()) return false; Y = m_Scanbeam.top(); m_Scanbeam.pop(); while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates. return true; } //------------------------------------------------------------------------------ void ClipperBase::DisposeAllOutRecs(){ for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) DisposeOutRec(i); m_PolyOuts.clear(); } //------------------------------------------------------------------------------ void ClipperBase::DisposeOutRec(PolyOutList::size_type index) { OutRec *outRec = m_PolyOuts[index]; if (outRec->Pts) DisposeOutPts(outRec->Pts); delete outRec; m_PolyOuts[index] = 0; } //------------------------------------------------------------------------------ void ClipperBase::DeleteFromAEL(TEdge *e) { TEdge* AelPrev = e->PrevInAEL; TEdge* AelNext = e->NextInAEL; if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted if (AelPrev) AelPrev->NextInAEL = AelNext; else m_ActiveEdges = AelNext; if (AelNext) AelNext->PrevInAEL = AelPrev; e->NextInAEL = 0; e->PrevInAEL = 0; } //------------------------------------------------------------------------------ OutRec* ClipperBase::CreateOutRec() { OutRec* result = new OutRec; result->IsHole = false; result->IsOpen = false; result->FirstLeft = 0; result->Pts = 0; result->BottomPt = 0; result->PolyNd = 0; m_PolyOuts.push_back(result); result->Idx = (int)m_PolyOuts.size() - 1; return result; } //------------------------------------------------------------------------------ void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2) { //check that one or other edge hasn't already been removed from AEL ... if (Edge1->NextInAEL == Edge1->PrevInAEL || Edge2->NextInAEL == Edge2->PrevInAEL) return; if (Edge1->NextInAEL == Edge2) { TEdge* Next = Edge2->NextInAEL; if (Next) Next->PrevInAEL = Edge1; TEdge* Prev = Edge1->PrevInAEL; if (Prev) Prev->NextInAEL = Edge2; Edge2->PrevInAEL = Prev; Edge2->NextInAEL = Edge1; Edge1->PrevInAEL = Edge2; Edge1->NextInAEL = Next; } else if (Edge2->NextInAEL == Edge1) { TEdge* Next = Edge1->NextInAEL; if (Next) Next->PrevInAEL = Edge2; TEdge* Prev = Edge2->PrevInAEL; if (Prev) Prev->NextInAEL = Edge1; Edge1->PrevInAEL = Prev; Edge1->NextInAEL = Edge2; Edge2->PrevInAEL = Edge1; Edge2->NextInAEL = Next; } else { TEdge* Next = Edge1->NextInAEL; TEdge* Prev = Edge1->PrevInAEL; Edge1->NextInAEL = Edge2->NextInAEL; if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1; Edge1->PrevInAEL = Edge2->PrevInAEL; if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1; Edge2->NextInAEL = Next; if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2; Edge2->PrevInAEL = Prev; if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2; } if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1; else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2; } //------------------------------------------------------------------------------ void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e) { if (!e->NextInLML) throw clipperException("UpdateEdgeIntoAEL: invalid call"); e->NextInLML->OutIdx = e->OutIdx; TEdge* AelPrev = e->PrevInAEL; TEdge* AelNext = e->NextInAEL; if (AelPrev) AelPrev->NextInAEL = e->NextInLML; else m_ActiveEdges = e->NextInLML; if (AelNext) AelNext->PrevInAEL = e->NextInLML; e->NextInLML->Side = e->Side; e->NextInLML->WindDelta = e->WindDelta; e->NextInLML->WindCnt = e->WindCnt; e->NextInLML->WindCnt2 = e->WindCnt2; e = e->NextInLML; e->Curr = e->Bot; e->PrevInAEL = AelPrev; e->NextInAEL = AelNext; if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y); } //------------------------------------------------------------------------------ bool ClipperBase::LocalMinimaPending() { return (m_CurrentLM != m_MinimaList.end()); } //------------------------------------------------------------------------------ // TClipper methods ... //------------------------------------------------------------------------------ Clipper::Clipper(int initOptions) : ClipperBase() //constructor { m_ExecuteLocked = false; m_UseFullRange = false; m_ReverseOutput = ((initOptions & ioReverseSolution) != 0); m_StrictSimple = ((initOptions & ioStrictlySimple) != 0); m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0); m_HasOpenPaths = false; #ifdef use_xyz m_ZFill = 0; #endif } //------------------------------------------------------------------------------ #ifdef use_xyz void Clipper::ZFillFunction(ZFillCallback zFillFunc) { m_ZFill = zFillFunc; } //------------------------------------------------------------------------------ #endif bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType) { return Execute(clipType, solution, fillType, fillType); } //------------------------------------------------------------------------------ bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType) { return Execute(clipType, polytree, fillType, fillType); } //------------------------------------------------------------------------------ bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType subjFillType, PolyFillType clipFillType) { if( m_ExecuteLocked ) return false; if (m_HasOpenPaths) throw clipperException("Error: PolyTree struct is needed for open path clipping."); m_ExecuteLocked = true; solution.resize(0); m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; m_UsingPolyTree = false; bool succeeded = ExecuteInternal(); if (succeeded) BuildResult(solution); DisposeAllOutRecs(); m_ExecuteLocked = false; return succeeded; } //------------------------------------------------------------------------------ bool Clipper::Execute(ClipType clipType, PolyTree& polytree, PolyFillType subjFillType, PolyFillType clipFillType) { if( m_ExecuteLocked ) return false; m_ExecuteLocked = true; m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; m_UsingPolyTree = true; bool succeeded = ExecuteInternal(); if (succeeded) BuildResult2(polytree); DisposeAllOutRecs(); m_ExecuteLocked = false; return succeeded; } //------------------------------------------------------------------------------ void Clipper::FixHoleLinkage(OutRec &outrec) { //skip OutRecs that (a) contain outermost polygons or //(b) already have the correct owner/child linkage ... if (!outrec.FirstLeft || (outrec.IsHole != outrec.FirstLeft->IsHole && outrec.FirstLeft->Pts)) return; OutRec* orfl = outrec.FirstLeft; while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts)) orfl = orfl->FirstLeft; outrec.FirstLeft = orfl; } //------------------------------------------------------------------------------ bool Clipper::ExecuteInternal() { bool succeeded = true; try { Reset(); m_Maxima = MaximaList(); m_SortedEdges = 0; succeeded = true; cInt botY, topY; if (!PopScanbeam(botY)) return false; InsertLocalMinimaIntoAEL(botY); while (PopScanbeam(topY) || LocalMinimaPending()) { ProcessHorizontals(); ClearGhostJoins(); if (!ProcessIntersections(topY)) { succeeded = false; break; } ProcessEdgesAtTopOfScanbeam(topY); botY = topY; InsertLocalMinimaIntoAEL(botY); } } catch(...) { succeeded = false; } if (succeeded) { //fix orientations ... for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec *outRec = m_PolyOuts[i]; if (!outRec->Pts || outRec->IsOpen) continue; if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0)) ReversePolyPtLinks(outRec->Pts); } if (!m_Joins.empty()) JoinCommonEdges(); //unfortunately FixupOutPolygon() must be done after JoinCommonEdges() for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec *outRec = m_PolyOuts[i]; if (!outRec->Pts) continue; if (outRec->IsOpen) FixupOutPolyline(*outRec); else FixupOutPolygon(*outRec); } if (m_StrictSimple) DoSimplePolygons(); } ClearJoins(); ClearGhostJoins(); return succeeded; } //------------------------------------------------------------------------------ void Clipper::SetWindingCount(TEdge &edge) { TEdge *e = edge.PrevInAEL; //find the edge of the same polytype that immediately preceeds 'edge' in AEL while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL; if (!e) { if (edge.WindDelta == 0) { PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType); edge.WindCnt = (pft == pftNegative ? -1 : 1); } else edge.WindCnt = edge.WindDelta; edge.WindCnt2 = 0; e = m_ActiveEdges; //ie get ready to calc WindCnt2 } else if (edge.WindDelta == 0 && m_ClipType != ctUnion) { edge.WindCnt = 1; edge.WindCnt2 = e->WindCnt2; e = e->NextInAEL; //ie get ready to calc WindCnt2 } else if (IsEvenOddFillType(edge)) { //EvenOdd filling ... if (edge.WindDelta == 0) { //are we inside a subj polygon ... bool Inside = true; TEdge *e2 = e->PrevInAEL; while (e2) { if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0) Inside = !Inside; e2 = e2->PrevInAEL; } edge.WindCnt = (Inside ? 0 : 1); } else { edge.WindCnt = edge.WindDelta; } edge.WindCnt2 = e->WindCnt2; e = e->NextInAEL; //ie get ready to calc WindCnt2 } else { //nonZero, Positive or Negative filling ... if (e->WindCnt * e->WindDelta < 0) { //prev edge is 'decreasing' WindCount (WC) toward zero //so we're outside the previous polygon ... if (Abs(e->WindCnt) > 1) { //outside prev poly but still inside another. //when reversing direction of prev poly use the same WC if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt; //otherwise continue to 'decrease' WC ... else edge.WindCnt = e->WindCnt + edge.WindDelta; } else //now outside all polys of same polytype so set own WC ... edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta); } else { //prev edge is 'increasing' WindCount (WC) away from zero //so we're inside the previous polygon ... if (edge.WindDelta == 0) edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1); //if wind direction is reversing prev then use same WC else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt; //otherwise add to WC ... else edge.WindCnt = e->WindCnt + edge.WindDelta; } edge.WindCnt2 = e->WindCnt2; e = e->NextInAEL; //ie get ready to calc WindCnt2 } //update WindCnt2 ... if (IsEvenOddAltFillType(edge)) { //EvenOdd filling ... while (e != &edge) { if (e->WindDelta != 0) edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0); e = e->NextInAEL; } } else { //nonZero, Positive or Negative filling ... while ( e != &edge ) { edge.WindCnt2 += e->WindDelta; e = e->NextInAEL; } } } //------------------------------------------------------------------------------ bool Clipper::IsEvenOddFillType(const TEdge& edge) const { if (edge.PolyTyp == ptSubject) return m_SubjFillType == pftEvenOdd; else return m_ClipFillType == pftEvenOdd; } //------------------------------------------------------------------------------ bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const { if (edge.PolyTyp == ptSubject) return m_ClipFillType == pftEvenOdd; else return m_SubjFillType == pftEvenOdd; } //------------------------------------------------------------------------------ bool Clipper::IsContributing(const TEdge& edge) const { PolyFillType pft, pft2; if (edge.PolyTyp == ptSubject) { pft = m_SubjFillType; pft2 = m_ClipFillType; } else { pft = m_ClipFillType; pft2 = m_SubjFillType; } switch(pft) { case pftEvenOdd: //return false if a subj line has been flagged as inside a subj polygon if (edge.WindDelta == 0 && edge.WindCnt != 1) return false; break; case pftNonZero: if (Abs(edge.WindCnt) != 1) return false; break; case pftPositive: if (edge.WindCnt != 1) return false; break; default: //pftNegative if (edge.WindCnt != -1) return false; } switch(m_ClipType) { case ctIntersection: switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 != 0); case pftPositive: return (edge.WindCnt2 > 0); default: return (edge.WindCnt2 < 0); } break; case ctUnion: switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 == 0); case pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } break; case ctDifference: if (edge.PolyTyp == ptSubject) switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 == 0); case pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } else switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 != 0); case pftPositive: return (edge.WindCnt2 > 0); default: return (edge.WindCnt2 < 0); } break; case ctXor: if (edge.WindDelta == 0) //XOr always contributing unless open switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 == 0); case pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } else return true; break; default: return true; } } //------------------------------------------------------------------------------ OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt) { OutPt* result; TEdge *e, *prevE; if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx )) { result = AddOutPt(e1, Pt); e2->OutIdx = e1->OutIdx; e1->Side = esLeft; e2->Side = esRight; e = e1; if (e->PrevInAEL == e2) prevE = e2->PrevInAEL; else prevE = e->PrevInAEL; } else { result = AddOutPt(e2, Pt); e1->OutIdx = e2->OutIdx; e1->Side = esRight; e2->Side = esLeft; e = e2; if (e->PrevInAEL == e1) prevE = e1->PrevInAEL; else prevE = e->PrevInAEL; } if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y) { cInt xPrev = TopX(*prevE, Pt.Y); cInt xE = TopX(*e, Pt.Y); if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) && SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange)) { OutPt* outPt = AddOutPt(prevE, Pt); AddJoin(result, outPt, e->Top); } } return result; } //------------------------------------------------------------------------------ void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt) { AddOutPt( e1, Pt ); if (e2->WindDelta == 0) AddOutPt(e2, Pt); if( e1->OutIdx == e2->OutIdx ) { e1->OutIdx = Unassigned; e2->OutIdx = Unassigned; } else if (e1->OutIdx < e2->OutIdx) AppendPolygon(e1, e2); else AppendPolygon(e2, e1); } //------------------------------------------------------------------------------ void Clipper::AddEdgeToSEL(TEdge *edge) { //SEL pointers in PEdge are reused to build a list of horizontal edges. //However, we don't need to worry about order with horizontal edge processing. if( !m_SortedEdges ) { m_SortedEdges = edge; edge->PrevInSEL = 0; edge->NextInSEL = 0; } else { edge->NextInSEL = m_SortedEdges; edge->PrevInSEL = 0; m_SortedEdges->PrevInSEL = edge; m_SortedEdges = edge; } } //------------------------------------------------------------------------------ bool Clipper::PopEdgeFromSEL(TEdge *&edge) { if (!m_SortedEdges) return false; edge = m_SortedEdges; DeleteFromSEL(m_SortedEdges); return true; } //------------------------------------------------------------------------------ void Clipper::CopyAELToSEL() { TEdge* e = m_ActiveEdges; m_SortedEdges = e; while ( e ) { e->PrevInSEL = e->PrevInAEL; e->NextInSEL = e->NextInAEL; e = e->NextInAEL; } } //------------------------------------------------------------------------------ void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt) { Join* j = new Join; j->OutPt1 = op1; j->OutPt2 = op2; j->OffPt = OffPt; m_Joins.push_back(j); } //------------------------------------------------------------------------------ void Clipper::ClearJoins() { for (JoinList::size_type i = 0; i < m_Joins.size(); i++) delete m_Joins[i]; m_Joins.resize(0); } //------------------------------------------------------------------------------ void Clipper::ClearGhostJoins() { for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++) delete m_GhostJoins[i]; m_GhostJoins.resize(0); } //------------------------------------------------------------------------------ void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt) { Join* j = new Join; j->OutPt1 = op; j->OutPt2 = 0; j->OffPt = OffPt; m_GhostJoins.push_back(j); } //------------------------------------------------------------------------------ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) { const LocalMinimum *lm; while (PopLocalMinima(botY, lm)) { TEdge* lb = lm->LeftBound; TEdge* rb = lm->RightBound; OutPt *Op1 = 0; if (!lb) { //nb: don't insert LB into either AEL or SEL InsertEdgeIntoAEL(rb, 0); SetWindingCount(*rb); if (IsContributing(*rb)) Op1 = AddOutPt(rb, rb->Bot); } else if (!rb) { InsertEdgeIntoAEL(lb, 0); SetWindingCount(*lb); if (IsContributing(*lb)) Op1 = AddOutPt(lb, lb->Bot); InsertScanbeam(lb->Top.Y); } else { InsertEdgeIntoAEL(lb, 0); InsertEdgeIntoAEL(rb, lb); SetWindingCount( *lb ); rb->WindCnt = lb->WindCnt; rb->WindCnt2 = lb->WindCnt2; if (IsContributing(*lb)) Op1 = AddLocalMinPoly(lb, rb, lb->Bot); InsertScanbeam(lb->Top.Y); } if (rb) { if (IsHorizontal(*rb)) { AddEdgeToSEL(rb); if (rb->NextInLML) InsertScanbeam(rb->NextInLML->Top.Y); } else InsertScanbeam( rb->Top.Y ); } if (!lb || !rb) continue; //if any output polygons share an edge, they'll need joining later ... if (Op1 && IsHorizontal(*rb) && m_GhostJoins.size() > 0 && (rb->WindDelta != 0)) { for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i) { Join* jr = m_GhostJoins[i]; //if the horizontal Rb and a 'ghost' horizontal overlap, then convert //the 'ghost' join to a real join ready for later ... if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X)) AddJoin(jr->OutPt1, Op1, jr->OffPt); } } if (lb->OutIdx >= 0 && lb->PrevInAEL && lb->PrevInAEL->Curr.X == lb->Bot.X && lb->PrevInAEL->OutIdx >= 0 && SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) && (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0)) { OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot); AddJoin(Op1, Op2, lb->Top); } if(lb->NextInAEL != rb) { if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 && SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) && (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0)) { OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot); AddJoin(Op1, Op2, rb->Top); } TEdge* e = lb->NextInAEL; if (e) { while( e != rb ) { //nb: For calculating winding counts etc, IntersectEdges() assumes //that param1 will be to the Right of param2 ABOVE the intersection ... IntersectEdges(rb , e , lb->Curr); //order important here e = e->NextInAEL; } } } } } //------------------------------------------------------------------------------ void Clipper::DeleteFromSEL(TEdge *e) { TEdge* SelPrev = e->PrevInSEL; TEdge* SelNext = e->NextInSEL; if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted if( SelPrev ) SelPrev->NextInSEL = SelNext; else m_SortedEdges = SelNext; if( SelNext ) SelNext->PrevInSEL = SelPrev; e->NextInSEL = 0; e->PrevInSEL = 0; } //------------------------------------------------------------------------------ #ifdef use_xyz void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2) { if (pt.Z != 0 || !m_ZFill) return; else if (pt == e1.Bot) pt.Z = e1.Bot.Z; else if (pt == e1.Top) pt.Z = e1.Top.Z; else if (pt == e2.Bot) pt.Z = e2.Bot.Z; else if (pt == e2.Top) pt.Z = e2.Top.Z; else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt); } //------------------------------------------------------------------------------ #endif void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt) { bool e1Contributing = ( e1->OutIdx >= 0 ); bool e2Contributing = ( e2->OutIdx >= 0 ); #ifdef use_xyz SetZ(Pt, *e1, *e2); #endif #ifdef use_lines //if either edge is on an OPEN path ... if (e1->WindDelta == 0 || e2->WindDelta == 0) { //ignore subject-subject open path intersections UNLESS they //are both open paths, AND they are both 'contributing maximas' ... if (e1->WindDelta == 0 && e2->WindDelta == 0) return; //if intersecting a subj line with a subj poly ... else if (e1->PolyTyp == e2->PolyTyp && e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion) { if (e1->WindDelta == 0) { if (e2Contributing) { AddOutPt(e1, Pt); if (e1Contributing) e1->OutIdx = Unassigned; } } else { if (e1Contributing) { AddOutPt(e2, Pt); if (e2Contributing) e2->OutIdx = Unassigned; } } } else if (e1->PolyTyp != e2->PolyTyp) { //toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ... if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 && (m_ClipType != ctUnion || e2->WindCnt2 == 0)) { AddOutPt(e1, Pt); if (e1Contributing) e1->OutIdx = Unassigned; } else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) && (m_ClipType != ctUnion || e1->WindCnt2 == 0)) { AddOutPt(e2, Pt); if (e2Contributing) e2->OutIdx = Unassigned; } } return; } #endif //update winding counts... //assumes that e1 will be to the Right of e2 ABOVE the intersection if ( e1->PolyTyp == e2->PolyTyp ) { if ( IsEvenOddFillType( *e1) ) { int oldE1WindCnt = e1->WindCnt; e1->WindCnt = e2->WindCnt; e2->WindCnt = oldE1WindCnt; } else { if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt; else e1->WindCnt += e2->WindDelta; if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt; else e2->WindCnt -= e1->WindDelta; } } else { if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta; else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0; if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta; else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0; } PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2; if (e1->PolyTyp == ptSubject) { e1FillType = m_SubjFillType; e1FillType2 = m_ClipFillType; } else { e1FillType = m_ClipFillType; e1FillType2 = m_SubjFillType; } if (e2->PolyTyp == ptSubject) { e2FillType = m_SubjFillType; e2FillType2 = m_ClipFillType; } else { e2FillType = m_ClipFillType; e2FillType2 = m_SubjFillType; } cInt e1Wc, e2Wc; switch (e1FillType) { case pftPositive: e1Wc = e1->WindCnt; break; case pftNegative: e1Wc = -e1->WindCnt; break; default: e1Wc = Abs(e1->WindCnt); } switch(e2FillType) { case pftPositive: e2Wc = e2->WindCnt; break; case pftNegative: e2Wc = -e2->WindCnt; break; default: e2Wc = Abs(e2->WindCnt); } if ( e1Contributing && e2Contributing ) { if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) || (e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) ) { AddLocalMaxPoly(e1, e2, Pt); } else { AddOutPt(e1, Pt); AddOutPt(e2, Pt); SwapSides( *e1 , *e2 ); SwapPolyIndexes( *e1 , *e2 ); } } else if ( e1Contributing ) { if (e2Wc == 0 || e2Wc == 1) { AddOutPt(e1, Pt); SwapSides(*e1, *e2); SwapPolyIndexes(*e1, *e2); } } else if ( e2Contributing ) { if (e1Wc == 0 || e1Wc == 1) { AddOutPt(e2, Pt); SwapSides(*e1, *e2); SwapPolyIndexes(*e1, *e2); } } else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1)) { //neither edge is currently contributing ... cInt e1Wc2, e2Wc2; switch (e1FillType2) { case pftPositive: e1Wc2 = e1->WindCnt2; break; case pftNegative : e1Wc2 = -e1->WindCnt2; break; default: e1Wc2 = Abs(e1->WindCnt2); } switch (e2FillType2) { case pftPositive: e2Wc2 = e2->WindCnt2; break; case pftNegative: e2Wc2 = -e2->WindCnt2; break; default: e2Wc2 = Abs(e2->WindCnt2); } if (e1->PolyTyp != e2->PolyTyp) { AddLocalMinPoly(e1, e2, Pt); } else if (e1Wc == 1 && e2Wc == 1) switch( m_ClipType ) { case ctIntersection: if (e1Wc2 > 0 && e2Wc2 > 0) AddLocalMinPoly(e1, e2, Pt); break; case ctUnion: if ( e1Wc2 <= 0 && e2Wc2 <= 0 ) AddLocalMinPoly(e1, e2, Pt); break; case ctDifference: if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) || ((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0))) AddLocalMinPoly(e1, e2, Pt); break; case ctXor: AddLocalMinPoly(e1, e2, Pt); } else SwapSides( *e1, *e2 ); } } //------------------------------------------------------------------------------ void Clipper::SetHoleState(TEdge *e, OutRec *outrec) { TEdge *e2 = e->PrevInAEL; TEdge *eTmp = 0; while (e2) { if (e2->OutIdx >= 0 && e2->WindDelta != 0) { if (!eTmp) eTmp = e2; else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0; } e2 = e2->PrevInAEL; } if (!eTmp) { outrec->FirstLeft = 0; outrec->IsHole = false; } else { outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx]; outrec->IsHole = !outrec->FirstLeft->IsHole; } } //------------------------------------------------------------------------------ OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2) { //work out which polygon fragment has the correct hole state ... if (!outRec1->BottomPt) outRec1->BottomPt = GetBottomPt(outRec1->Pts); if (!outRec2->BottomPt) outRec2->BottomPt = GetBottomPt(outRec2->Pts); OutPt *OutPt1 = outRec1->BottomPt; OutPt *OutPt2 = outRec2->BottomPt; if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1; else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2; else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1; else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2; else if (OutPt1->Next == OutPt1) return outRec2; else if (OutPt2->Next == OutPt2) return outRec1; else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1; else return outRec2; } //------------------------------------------------------------------------------ bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2) { do { outRec1 = outRec1->FirstLeft; if (outRec1 == outRec2) return true; } while (outRec1); return false; } //------------------------------------------------------------------------------ OutRec* Clipper::GetOutRec(int Idx) { OutRec* outrec = m_PolyOuts[Idx]; while (outrec != m_PolyOuts[outrec->Idx]) outrec = m_PolyOuts[outrec->Idx]; return outrec; } //------------------------------------------------------------------------------ void Clipper::AppendPolygon(TEdge *e1, TEdge *e2) { //get the start and ends of both output polygons ... OutRec *outRec1 = m_PolyOuts[e1->OutIdx]; OutRec *outRec2 = m_PolyOuts[e2->OutIdx]; OutRec *holeStateRec; if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2; else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1; else holeStateRec = GetLowermostRec(outRec1, outRec2); //get the start and ends of both output polygons and //join e2 poly onto e1 poly and delete pointers to e2 ... OutPt* p1_lft = outRec1->Pts; OutPt* p1_rt = p1_lft->Prev; OutPt* p2_lft = outRec2->Pts; OutPt* p2_rt = p2_lft->Prev; //join e2 poly onto e1 poly and delete pointers to e2 ... if( e1->Side == esLeft ) { if( e2->Side == esLeft ) { //z y x a b c ReversePolyPtLinks(p2_lft); p2_lft->Next = p1_lft; p1_lft->Prev = p2_lft; p1_rt->Next = p2_rt; p2_rt->Prev = p1_rt; outRec1->Pts = p2_rt; } else { //x y z a b c p2_rt->Next = p1_lft; p1_lft->Prev = p2_rt; p2_lft->Prev = p1_rt; p1_rt->Next = p2_lft; outRec1->Pts = p2_lft; } } else { if( e2->Side == esRight ) { //a b c z y x ReversePolyPtLinks(p2_lft); p1_rt->Next = p2_rt; p2_rt->Prev = p1_rt; p2_lft->Next = p1_lft; p1_lft->Prev = p2_lft; } else { //a b c x y z p1_rt->Next = p2_lft; p2_lft->Prev = p1_rt; p1_lft->Prev = p2_rt; p2_rt->Next = p1_lft; } } outRec1->BottomPt = 0; if (holeStateRec == outRec2) { if (outRec2->FirstLeft != outRec1) outRec1->FirstLeft = outRec2->FirstLeft; outRec1->IsHole = outRec2->IsHole; } outRec2->Pts = 0; outRec2->BottomPt = 0; outRec2->FirstLeft = outRec1; int OKIdx = e1->OutIdx; int ObsoleteIdx = e2->OutIdx; e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly e2->OutIdx = Unassigned; TEdge* e = m_ActiveEdges; while( e ) { if( e->OutIdx == ObsoleteIdx ) { e->OutIdx = OKIdx; e->Side = e1->Side; break; } e = e->NextInAEL; } outRec2->Idx = outRec1->Idx; } //------------------------------------------------------------------------------ OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt) { if( e->OutIdx < 0 ) { OutRec *outRec = CreateOutRec(); outRec->IsOpen = (e->WindDelta == 0); OutPt* newOp = new OutPt; outRec->Pts = newOp; newOp->Idx = outRec->Idx; newOp->Pt = pt; newOp->Next = newOp; newOp->Prev = newOp; if (!outRec->IsOpen) SetHoleState(e, outRec); e->OutIdx = outRec->Idx; return newOp; } else { OutRec *outRec = m_PolyOuts[e->OutIdx]; //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most' OutPt* op = outRec->Pts; bool ToFront = (e->Side == esLeft); if (ToFront && (pt == op->Pt)) return op; else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev; OutPt* newOp = new OutPt; newOp->Idx = outRec->Idx; newOp->Pt = pt; newOp->Next = op; newOp->Prev = op->Prev; newOp->Prev->Next = newOp; op->Prev = newOp; if (ToFront) outRec->Pts = newOp; return newOp; } } //------------------------------------------------------------------------------ OutPt* Clipper::GetLastOutPt(TEdge *e) { OutRec *outRec = m_PolyOuts[e->OutIdx]; if (e->Side == esLeft) return outRec->Pts; else return outRec->Pts->Prev; } //------------------------------------------------------------------------------ void Clipper::ProcessHorizontals() { TEdge* horzEdge; while (PopEdgeFromSEL(horzEdge)) ProcessHorizontal(horzEdge); } //------------------------------------------------------------------------------ inline bool IsMinima(TEdge *e) { return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e); } //------------------------------------------------------------------------------ inline bool IsMaxima(TEdge *e, const cInt Y) { return e && e->Top.Y == Y && !e->NextInLML; } //------------------------------------------------------------------------------ inline bool IsIntermediate(TEdge *e, const cInt Y) { return e->Top.Y == Y && e->NextInLML; } //------------------------------------------------------------------------------ TEdge *GetMaximaPair(TEdge *e) { if ((e->Next->Top == e->Top) && !e->Next->NextInLML) return e->Next; else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML) return e->Prev; else return 0; } //------------------------------------------------------------------------------ TEdge *GetMaximaPairEx(TEdge *e) { //as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal) TEdge* result = GetMaximaPair(e); if (result && (result->OutIdx == Skip || (result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0; return result; } //------------------------------------------------------------------------------ void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2) { if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return; if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return; if( Edge1->NextInSEL == Edge2 ) { TEdge* Next = Edge2->NextInSEL; if( Next ) Next->PrevInSEL = Edge1; TEdge* Prev = Edge1->PrevInSEL; if( Prev ) Prev->NextInSEL = Edge2; Edge2->PrevInSEL = Prev; Edge2->NextInSEL = Edge1; Edge1->PrevInSEL = Edge2; Edge1->NextInSEL = Next; } else if( Edge2->NextInSEL == Edge1 ) { TEdge* Next = Edge1->NextInSEL; if( Next ) Next->PrevInSEL = Edge2; TEdge* Prev = Edge2->PrevInSEL; if( Prev ) Prev->NextInSEL = Edge1; Edge1->PrevInSEL = Prev; Edge1->NextInSEL = Edge2; Edge2->PrevInSEL = Edge1; Edge2->NextInSEL = Next; } else { TEdge* Next = Edge1->NextInSEL; TEdge* Prev = Edge1->PrevInSEL; Edge1->NextInSEL = Edge2->NextInSEL; if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1; Edge1->PrevInSEL = Edge2->PrevInSEL; if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1; Edge2->NextInSEL = Next; if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2; Edge2->PrevInSEL = Prev; if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2; } if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1; else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2; } //------------------------------------------------------------------------------ TEdge* GetNextInAEL(TEdge *e, Direction dir) { return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL; } //------------------------------------------------------------------------------ void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right) { if (HorzEdge.Bot.X < HorzEdge.Top.X) { Left = HorzEdge.Bot.X; Right = HorzEdge.Top.X; Dir = dLeftToRight; } else { Left = HorzEdge.Top.X; Right = HorzEdge.Bot.X; Dir = dRightToLeft; } } //------------------------------------------------------------------------ /******************************************************************************* * Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or * * Bottom of a scanbeam) are processed as if layered. The order in which HEs * * are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] * * (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), * * and with other non-horizontal edges [*]. Once these intersections are * * processed, intermediate HEs then 'promote' the Edge above (NextInLML) into * * the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. * *******************************************************************************/ void Clipper::ProcessHorizontal(TEdge *horzEdge) { Direction dir; cInt horzLeft, horzRight; bool IsOpen = (horzEdge->WindDelta == 0); GetHorzDirection(*horzEdge, dir, horzLeft, horzRight); TEdge* eLastHorz = horzEdge, *eMaxPair = 0; while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML)) eLastHorz = eLastHorz->NextInLML; if (!eLastHorz->NextInLML) eMaxPair = GetMaximaPair(eLastHorz); MaximaList::const_iterator maxIt; MaximaList::const_reverse_iterator maxRit; if (m_Maxima.size() > 0) { //get the first maxima in range (X) ... if (dir == dLeftToRight) { maxIt = m_Maxima.begin(); while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++; if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X) maxIt = m_Maxima.end(); } else { maxRit = m_Maxima.rbegin(); while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++; if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X) maxRit = m_Maxima.rend(); } } OutPt* op1 = 0; for (;;) //loop through consec. horizontal edges { bool IsLastHorz = (horzEdge == eLastHorz); TEdge* e = GetNextInAEL(horzEdge, dir); while(e) { //this code block inserts extra coords into horizontal edges (in output //polygons) whereever maxima touch these horizontal edges. This helps //'simplifying' polygons (ie if the Simplify property is set). if (m_Maxima.size() > 0) { if (dir == dLeftToRight) { while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X) { if (horzEdge->OutIdx >= 0 && !IsOpen) AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y)); maxIt++; } } else { while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X) { if (horzEdge->OutIdx >= 0 && !IsOpen) AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y)); maxRit++; } } }; if ((dir == dLeftToRight && e->Curr.X > horzRight) || (dir == dRightToLeft && e->Curr.X < horzLeft)) break; //Also break if we've got to the end of an intermediate horizontal edge ... //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal. if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML && e->Dx < horzEdge->NextInLML->Dx) break; if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times { #ifdef use_xyz if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e); else SetZ(e->Curr, *e, *horzEdge); #endif op1 = AddOutPt(horzEdge, e->Curr); TEdge* eNextHorz = m_SortedEdges; while (eNextHorz) { if (eNextHorz->OutIdx >= 0 && HorzSegmentsOverlap(horzEdge->Bot.X, horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X)) { OutPt* op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz->Top); } eNextHorz = eNextHorz->NextInSEL; } AddGhostJoin(op1, horzEdge->Bot); } //OK, so far we're still in range of the horizontal Edge but make sure //we're at the last of consec. horizontals when matching with eMaxPair if(e == eMaxPair && IsLastHorz) { if (horzEdge->OutIdx >= 0) AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top); DeleteFromAEL(horzEdge); DeleteFromAEL(eMaxPair); return; } if(dir == dLeftToRight) { IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y); IntersectEdges(horzEdge, e, Pt); } else { IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y); IntersectEdges( e, horzEdge, Pt); } TEdge* eNext = GetNextInAEL(e, dir); SwapPositionsInAEL( horzEdge, e ); e = eNext; } //end while(e) //Break out of loop if HorzEdge.NextInLML is not also horizontal ... if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break; UpdateEdgeIntoAEL(horzEdge); if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot); GetHorzDirection(*horzEdge, dir, horzLeft, horzRight); } //end for (;;) if (horzEdge->OutIdx >= 0 && !op1) { op1 = GetLastOutPt(horzEdge); TEdge* eNextHorz = m_SortedEdges; while (eNextHorz) { if (eNextHorz->OutIdx >= 0 && HorzSegmentsOverlap(horzEdge->Bot.X, horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X)) { OutPt* op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz->Top); } eNextHorz = eNextHorz->NextInSEL; } AddGhostJoin(op1, horzEdge->Top); } if (horzEdge->NextInLML) { if(horzEdge->OutIdx >= 0) { op1 = AddOutPt( horzEdge, horzEdge->Top); UpdateEdgeIntoAEL(horzEdge); if (horzEdge->WindDelta == 0) return; //nb: HorzEdge is no longer horizontal here TEdge* ePrev = horzEdge->PrevInAEL; TEdge* eNext = horzEdge->NextInAEL; if (ePrev && ePrev->Curr.X == horzEdge->Bot.X && ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 && (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y && SlopesEqual(*horzEdge, *ePrev, m_UseFullRange))) { OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot); AddJoin(op1, op2, horzEdge->Top); } else if (eNext && eNext->Curr.X == horzEdge->Bot.X && eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 && eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y && SlopesEqual(*horzEdge, *eNext, m_UseFullRange)) { OutPt* op2 = AddOutPt(eNext, horzEdge->Bot); AddJoin(op1, op2, horzEdge->Top); } } else UpdateEdgeIntoAEL(horzEdge); } else { if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top); DeleteFromAEL(horzEdge); } } //------------------------------------------------------------------------------ bool Clipper::ProcessIntersections(const cInt topY) { if( !m_ActiveEdges ) return true; try { BuildIntersectList(topY); size_t IlSize = m_IntersectList.size(); if (IlSize == 0) return true; if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList(); else return false; } catch(...) { m_SortedEdges = 0; DisposeIntersectNodes(); throw clipperException("ProcessIntersections error"); } m_SortedEdges = 0; return true; } //------------------------------------------------------------------------------ void Clipper::DisposeIntersectNodes() { for (size_t i = 0; i < m_IntersectList.size(); ++i ) delete m_IntersectList[i]; m_IntersectList.clear(); } //------------------------------------------------------------------------------ void Clipper::BuildIntersectList(const cInt topY) { if ( !m_ActiveEdges ) return; //prepare for sorting ... TEdge* e = m_ActiveEdges; m_SortedEdges = e; while( e ) { e->PrevInSEL = e->PrevInAEL; e->NextInSEL = e->NextInAEL; e->Curr.X = TopX( *e, topY ); e = e->NextInAEL; } //bubblesort ... bool isModified; do { isModified = false; e = m_SortedEdges; while( e->NextInSEL ) { TEdge *eNext = e->NextInSEL; IntPoint Pt; if(e->Curr.X > eNext->Curr.X) { IntersectPoint(*e, *eNext, Pt); if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY); IntersectNode * newNode = new IntersectNode; newNode->Edge1 = e; newNode->Edge2 = eNext; newNode->Pt = Pt; m_IntersectList.push_back(newNode); SwapPositionsInSEL(e, eNext); isModified = true; } else e = eNext; } if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0; else break; } while ( isModified ); m_SortedEdges = 0; //important } //------------------------------------------------------------------------------ void Clipper::ProcessIntersectList() { for (size_t i = 0; i < m_IntersectList.size(); ++i) { IntersectNode* iNode = m_IntersectList[i]; { IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt); SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 ); } delete iNode; } m_IntersectList.clear(); } //------------------------------------------------------------------------------ bool IntersectListSort(IntersectNode* node1, IntersectNode* node2) { return node2->Pt.Y < node1->Pt.Y; } //------------------------------------------------------------------------------ inline bool EdgesAdjacent(const IntersectNode &inode) { return (inode.Edge1->NextInSEL == inode.Edge2) || (inode.Edge1->PrevInSEL == inode.Edge2); } //------------------------------------------------------------------------------ bool Clipper::FixupIntersectionOrder() { //pre-condition: intersections are sorted Bottom-most first. //Now it's crucial that intersections are made only between adjacent edges, //so to ensure this the order of intersections may need adjusting ... CopyAELToSEL(); std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort); size_t cnt = m_IntersectList.size(); for (size_t i = 0; i < cnt; ++i) { if (!EdgesAdjacent(*m_IntersectList[i])) { size_t j = i + 1; while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++; if (j == cnt) return false; std::swap(m_IntersectList[i], m_IntersectList[j]); } SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2); } return true; } //------------------------------------------------------------------------------ void Clipper::DoMaxima(TEdge *e) { TEdge* eMaxPair = GetMaximaPairEx(e); if (!eMaxPair) { if (e->OutIdx >= 0) AddOutPt(e, e->Top); DeleteFromAEL(e); return; } TEdge* eNext = e->NextInAEL; while(eNext && eNext != eMaxPair) { IntersectEdges(e, eNext, e->Top); SwapPositionsInAEL(e, eNext); eNext = e->NextInAEL; } if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned) { DeleteFromAEL(e); DeleteFromAEL(eMaxPair); } else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 ) { if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top); DeleteFromAEL(e); DeleteFromAEL(eMaxPair); } #ifdef use_lines else if (e->WindDelta == 0) { if (e->OutIdx >= 0) { AddOutPt(e, e->Top); e->OutIdx = Unassigned; } DeleteFromAEL(e); if (eMaxPair->OutIdx >= 0) { AddOutPt(eMaxPair, e->Top); eMaxPair->OutIdx = Unassigned; } DeleteFromAEL(eMaxPair); } #endif else throw clipperException("DoMaxima error"); } //------------------------------------------------------------------------------ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) { TEdge* e = m_ActiveEdges; while( e ) { //1. process maxima, treating them as if they're 'bent' horizontal edges, // but exclude maxima with horizontal edges. nb: e can't be a horizontal. bool IsMaximaEdge = IsMaxima(e, topY); if(IsMaximaEdge) { TEdge* eMaxPair = GetMaximaPairEx(e); IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair)); } if(IsMaximaEdge) { if (m_StrictSimple) m_Maxima.push_back(e->Top.X); TEdge* ePrev = e->PrevInAEL; DoMaxima(e); if( !ePrev ) e = m_ActiveEdges; else e = ePrev->NextInAEL; } else { //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ... if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML)) { UpdateEdgeIntoAEL(e); if (e->OutIdx >= 0) AddOutPt(e, e->Bot); AddEdgeToSEL(e); } else { e->Curr.X = TopX( *e, topY ); e->Curr.Y = topY; #ifdef use_xyz e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0); #endif } //When StrictlySimple and 'e' is being touched by another edge, then //make sure both edges have a vertex here ... if (m_StrictSimple) { TEdge* ePrev = e->PrevInAEL; if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) && (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0)) { IntPoint pt = e->Curr; #ifdef use_xyz SetZ(pt, *ePrev, *e); #endif OutPt* op = AddOutPt(ePrev, pt); OutPt* op2 = AddOutPt(e, pt); AddJoin(op, op2, pt); //StrictlySimple (type-3) join } } e = e->NextInAEL; } } //3. Process horizontals at the Top of the scanbeam ... m_Maxima.sort(); ProcessHorizontals(); m_Maxima.clear(); //4. Promote intermediate vertices ... e = m_ActiveEdges; while(e) { if(IsIntermediate(e, topY)) { OutPt* op = 0; if( e->OutIdx >= 0 ) op = AddOutPt(e, e->Top); UpdateEdgeIntoAEL(e); //if output polygons share an edge, they'll need joining later ... TEdge* ePrev = e->PrevInAEL; TEdge* eNext = e->NextInAEL; if (ePrev && ePrev->Curr.X == e->Bot.X && ePrev->Curr.Y == e->Bot.Y && op && ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y && SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) && (e->WindDelta != 0) && (ePrev->WindDelta != 0)) { OutPt* op2 = AddOutPt(ePrev, e->Bot); AddJoin(op, op2, e->Top); } else if (eNext && eNext->Curr.X == e->Bot.X && eNext->Curr.Y == e->Bot.Y && op && eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y && SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) && (e->WindDelta != 0) && (eNext->WindDelta != 0)) { OutPt* op2 = AddOutPt(eNext, e->Bot); AddJoin(op, op2, e->Top); } } e = e->NextInAEL; } } //------------------------------------------------------------------------------ void Clipper::FixupOutPolyline(OutRec &outrec) { OutPt *pp = outrec.Pts; OutPt *lastPP = pp->Prev; while (pp != lastPP) { pp = pp->Next; if (pp->Pt == pp->Prev->Pt) { if (pp == lastPP) lastPP = pp->Prev; OutPt *tmpPP = pp->Prev; tmpPP->Next = pp->Next; pp->Next->Prev = tmpPP; delete pp; pp = tmpPP; } } if (pp == pp->Prev) { DisposeOutPts(pp); outrec.Pts = 0; return; } } //------------------------------------------------------------------------------ void Clipper::FixupOutPolygon(OutRec &outrec) { //FixupOutPolygon() - removes duplicate points and simplifies consecutive //parallel edges by removing the middle vertex. OutPt *lastOK = 0; outrec.BottomPt = 0; OutPt *pp = outrec.Pts; bool preserveCol = m_PreserveCollinear || m_StrictSimple; for (;;) { if (pp->Prev == pp || pp->Prev == pp->Next) { DisposeOutPts(pp); outrec.Pts = 0; return; } //test for duplicate points and collinear edges ... if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) || (SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) && (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt)))) { lastOK = 0; OutPt *tmp = pp; pp->Prev->Next = pp->Next; pp->Next->Prev = pp->Prev; pp = pp->Prev; delete tmp; } else if (pp == lastOK) break; else { if (!lastOK) lastOK = pp; pp = pp->Next; } } outrec.Pts = pp; } //------------------------------------------------------------------------------ int PointCount(OutPt *Pts) { if (!Pts) return 0; int result = 0; OutPt* p = Pts; do { result++; p = p->Next; } while (p != Pts); return result; } //------------------------------------------------------------------------------ void Clipper::BuildResult(Paths &polys) { polys.reserve(m_PolyOuts.size()); for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { if (!m_PolyOuts[i]->Pts) continue; Path pg; OutPt* p = m_PolyOuts[i]->Pts->Prev; int cnt = PointCount(p); if (cnt < 2) continue; pg.reserve(cnt); for (int i = 0; i < cnt; ++i) { pg.push_back(p->Pt); p = p->Prev; } polys.push_back(pg); } } //------------------------------------------------------------------------------ void Clipper::BuildResult2(PolyTree& polytree) { polytree.Clear(); polytree.AllNodes.reserve(m_PolyOuts.size()); //add each output polygon/contour to polytree ... for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++) { OutRec* outRec = m_PolyOuts[i]; int cnt = PointCount(outRec->Pts); if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue; FixHoleLinkage(*outRec); PolyNode* pn = new PolyNode(); //nb: polytree takes ownership of all the PolyNodes polytree.AllNodes.push_back(pn); outRec->PolyNd = pn; pn->Parent = 0; pn->Index = 0; pn->Contour.reserve(cnt); OutPt *op = outRec->Pts->Prev; for (int j = 0; j < cnt; j++) { pn->Contour.push_back(op->Pt); op = op->Prev; } } //fixup PolyNode links etc ... polytree.Childs.reserve(m_PolyOuts.size()); for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++) { OutRec* outRec = m_PolyOuts[i]; if (!outRec->PolyNd) continue; if (outRec->IsOpen) { outRec->PolyNd->m_IsOpen = true; polytree.AddChild(*outRec->PolyNd); } else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd) outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd); else polytree.AddChild(*outRec->PolyNd); } } //------------------------------------------------------------------------------ void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2) { //just swap the contents (because fIntersectNodes is a single-linked-list) IntersectNode inode = int1; //gets a copy of Int1 int1.Edge1 = int2.Edge1; int1.Edge2 = int2.Edge2; int1.Pt = int2.Pt; int2.Edge1 = inode.Edge1; int2.Edge2 = inode.Edge2; int2.Pt = inode.Pt; } //------------------------------------------------------------------------------ inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2) { if (e2.Curr.X == e1.Curr.X) { if (e2.Top.Y > e1.Top.Y) return e2.Top.X < TopX(e1, e2.Top.Y); else return e1.Top.X > TopX(e2, e1.Top.Y); } else return e2.Curr.X < e1.Curr.X; } //------------------------------------------------------------------------------ bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2, cInt& Left, cInt& Right) { if (a1 < a2) { if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);} else {Left = std::max(a1,b2); Right = std::min(a2,b1);} } else { if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);} else {Left = std::max(a2,b2); Right = std::min(a1,b1);} } return Left < Right; } //------------------------------------------------------------------------------ inline void UpdateOutPtIdxs(OutRec& outrec) { OutPt* op = outrec.Pts; do { op->Idx = outrec.Idx; op = op->Prev; } while(op != outrec.Pts); } //------------------------------------------------------------------------------ void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge) { if(!m_ActiveEdges) { edge->PrevInAEL = 0; edge->NextInAEL = 0; m_ActiveEdges = edge; } else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge)) { edge->PrevInAEL = 0; edge->NextInAEL = m_ActiveEdges; m_ActiveEdges->PrevInAEL = edge; m_ActiveEdges = edge; } else { if(!startEdge) startEdge = m_ActiveEdges; while(startEdge->NextInAEL && !E2InsertsBeforeE1(*startEdge->NextInAEL , *edge)) startEdge = startEdge->NextInAEL; edge->NextInAEL = startEdge->NextInAEL; if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge; edge->PrevInAEL = startEdge; startEdge->NextInAEL = edge; } } //---------------------------------------------------------------------- OutPt* DupOutPt(OutPt* outPt, bool InsertAfter) { OutPt* result = new OutPt; result->Pt = outPt->Pt; result->Idx = outPt->Idx; if (InsertAfter) { result->Next = outPt->Next; result->Prev = outPt; outPt->Next->Prev = result; outPt->Next = result; } else { result->Prev = outPt->Prev; result->Next = outPt; outPt->Prev->Next = result; outPt->Prev = result; } return result; } //------------------------------------------------------------------------------ bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, const IntPoint Pt, bool DiscardLeft) { Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight); Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight); if (Dir1 == Dir2) return false; //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we //want Op1b to be on the Right. (And likewise with Op2 and Op2b.) //So, to facilitate this while inserting Op1b and Op2b ... //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b, //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.) if (Dir1 == dLeftToRight) { while (op1->Next->Pt.X <= Pt.X && op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) op1 = op1->Next; if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next; op1b = DupOutPt(op1, !DiscardLeft); if (op1b->Pt != Pt) { op1 = op1b; op1->Pt = Pt; op1b = DupOutPt(op1, !DiscardLeft); } } else { while (op1->Next->Pt.X >= Pt.X && op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) op1 = op1->Next; if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next; op1b = DupOutPt(op1, DiscardLeft); if (op1b->Pt != Pt) { op1 = op1b; op1->Pt = Pt; op1b = DupOutPt(op1, DiscardLeft); } } if (Dir2 == dLeftToRight) { while (op2->Next->Pt.X <= Pt.X && op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) op2 = op2->Next; if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next; op2b = DupOutPt(op2, !DiscardLeft); if (op2b->Pt != Pt) { op2 = op2b; op2->Pt = Pt; op2b = DupOutPt(op2, !DiscardLeft); }; } else { while (op2->Next->Pt.X >= Pt.X && op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) op2 = op2->Next; if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next; op2b = DupOutPt(op2, DiscardLeft); if (op2b->Pt != Pt) { op2 = op2b; op2->Pt = Pt; op2b = DupOutPt(op2, DiscardLeft); }; }; if ((Dir1 == dLeftToRight) == DiscardLeft) { op1->Prev = op2; op2->Next = op1; op1b->Next = op2b; op2b->Prev = op1b; } else { op1->Next = op2; op2->Prev = op1; op1b->Prev = op2b; op2b->Next = op1b; } return true; } //------------------------------------------------------------------------------ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2) { OutPt *op1 = j->OutPt1, *op1b; OutPt *op2 = j->OutPt2, *op2b; //There are 3 kinds of joins for output polygons ... //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal). //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same //location at the Bottom of the overlapping segment (& Join.OffPt is above). //3. StrictSimple joins where edges touch but are not collinear and where //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point. bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y); if (isHorizontal && (j->OffPt == j->OutPt1->Pt) && (j->OffPt == j->OutPt2->Pt)) { //Strictly Simple join ... if (outRec1 != outRec2) return false; op1b = j->OutPt1->Next; while (op1b != op1 && (op1b->Pt == j->OffPt)) op1b = op1b->Next; bool reverse1 = (op1b->Pt.Y > j->OffPt.Y); op2b = j->OutPt2->Next; while (op2b != op2 && (op2b->Pt == j->OffPt)) op2b = op2b->Next; bool reverse2 = (op2b->Pt.Y > j->OffPt.Y); if (reverse1 == reverse2) return false; if (reverse1) { op1b = DupOutPt(op1, false); op2b = DupOutPt(op2, true); op1->Prev = op2; op2->Next = op1; op1b->Next = op2b; op2b->Prev = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } else { op1b = DupOutPt(op1, true); op2b = DupOutPt(op2, false); op1->Next = op2; op2->Prev = op1; op1b->Prev = op2b; op2b->Next = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } } else if (isHorizontal) { //treat horizontal joins differently to non-horizontal joins since with //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt //may be anywhere along the horizontal edge. op1b = op1; while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2) op1 = op1->Prev; while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2) op1b = op1b->Next; if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon' op2b = op2; while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b) op2 = op2->Prev; while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1) op2b = op2b->Next; if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon' cInt Left, Right; //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right)) return false; //DiscardLeftSide: when overlapping edges are joined, a spike will created //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up //on the discard Side as either may still be needed for other joins ... IntPoint Pt; bool DiscardLeftSide; if (op1->Pt.X >= Left && op1->Pt.X <= Right) { Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X); } else if (op2->Pt.X >= Left&& op2->Pt.X <= Right) { Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X); } else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right) { Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X; } else { Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X); } j->OutPt1 = op1; j->OutPt2 = op2; return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide); } else { //nb: For non-horizontal joins ... // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y // 2. Jr.OutPt1.Pt > Jr.OffPt.Y //make sure the polygons are correctly oriented ... op1b = op1->Next; while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next; bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)); if (Reverse1) { op1b = op1->Prev; while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev; if ((op1b->Pt.Y > op1->Pt.Y) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false; }; op2b = op2->Next; while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next; bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)); if (Reverse2) { op2b = op2->Prev; while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev; if ((op2b->Pt.Y > op2->Pt.Y) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false; } if ((op1b == op1) || (op2b == op2) || (op1b == op2b) || ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false; if (Reverse1) { op1b = DupOutPt(op1, false); op2b = DupOutPt(op2, true); op1->Prev = op2; op2->Next = op1; op1b->Next = op2b; op2b->Prev = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } else { op1b = DupOutPt(op1, true); op2b = DupOutPt(op2, false); op1->Next = op2; op2->Prev = op1; op1b->Prev = op2b; op2b->Next = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } } } //---------------------------------------------------------------------- static OutRec* ParseFirstLeft(OutRec* FirstLeft) { while (FirstLeft && !FirstLeft->Pts) FirstLeft = FirstLeft->FirstLeft; return FirstLeft; } //------------------------------------------------------------------------------ void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec) { //tests if NewOutRec contains the polygon before reassigning FirstLeft for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec* outRec = m_PolyOuts[i]; OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft); if (outRec->Pts && firstLeft == OldOutRec) { if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts)) outRec->FirstLeft = NewOutRec; } } } //---------------------------------------------------------------------- void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec) { //A polygon has split into two such that one is now the inner of the other. //It's possible that these polygons now wrap around other polygons, so check //every polygon that's also contained by OuterOutRec's FirstLeft container //(including 0) to see if they've become inner to the new inner polygon ... OutRec* orfl = OuterOutRec->FirstLeft; for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec* outRec = m_PolyOuts[i]; if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec) continue; OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft); if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec) continue; if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts)) outRec->FirstLeft = InnerOutRec; else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts)) outRec->FirstLeft = OuterOutRec; else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec) outRec->FirstLeft = orfl; } } //---------------------------------------------------------------------- void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec) { //reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec* outRec = m_PolyOuts[i]; OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft); if (outRec->Pts && firstLeft == OldOutRec) outRec->FirstLeft = NewOutRec; } } //---------------------------------------------------------------------- void Clipper::JoinCommonEdges() { for (JoinList::size_type i = 0; i < m_Joins.size(); i++) { Join* join = m_Joins[i]; OutRec *outRec1 = GetOutRec(join->OutPt1->Idx); OutRec *outRec2 = GetOutRec(join->OutPt2->Idx); if (!outRec1->Pts || !outRec2->Pts) continue; if (outRec1->IsOpen || outRec2->IsOpen) continue; //get the polygon fragment with the correct hole state (FirstLeft) //before calling JoinPoints() ... OutRec *holeStateRec; if (outRec1 == outRec2) holeStateRec = outRec1; else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2; else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1; else holeStateRec = GetLowermostRec(outRec1, outRec2); if (!JoinPoints(join, outRec1, outRec2)) continue; if (outRec1 == outRec2) { //instead of joining two polygons, we've just created a new one by //splitting one polygon into two. outRec1->Pts = join->OutPt1; outRec1->BottomPt = 0; outRec2 = CreateOutRec(); outRec2->Pts = join->OutPt2; //update all OutRec2.Pts Idx's ... UpdateOutPtIdxs(*outRec2); if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts)) { //outRec1 contains outRec2 ... outRec2->IsHole = !outRec1->IsHole; outRec2->FirstLeft = outRec1; if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1); if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0)) ReversePolyPtLinks(outRec2->Pts); } else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts)) { //outRec2 contains outRec1 ... outRec2->IsHole = outRec1->IsHole; outRec1->IsHole = !outRec2->IsHole; outRec2->FirstLeft = outRec1->FirstLeft; outRec1->FirstLeft = outRec2; if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2); if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0)) ReversePolyPtLinks(outRec1->Pts); } else { //the 2 polygons are completely separate ... outRec2->IsHole = outRec1->IsHole; outRec2->FirstLeft = outRec1->FirstLeft; //fixup FirstLeft pointers that may need reassigning to OutRec2 if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2); } } else { //joined 2 polygons together ... outRec2->Pts = 0; outRec2->BottomPt = 0; outRec2->Idx = outRec1->Idx; outRec1->IsHole = holeStateRec->IsHole; if (holeStateRec == outRec2) outRec1->FirstLeft = outRec2->FirstLeft; outRec2->FirstLeft = outRec1; if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1); } } } //------------------------------------------------------------------------------ // ClipperOffset support functions ... //------------------------------------------------------------------------------ DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2) { if(pt2.X == pt1.X && pt2.Y == pt1.Y) return DoublePoint(0, 0); double Dx = (double)(pt2.X - pt1.X); double dy = (double)(pt2.Y - pt1.Y); double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy ); Dx *= f; dy *= f; return DoublePoint(dy, -Dx); } //------------------------------------------------------------------------------ // ClipperOffset class //------------------------------------------------------------------------------ ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance) { this->MiterLimit = miterLimit; this->ArcTolerance = arcTolerance; m_lowest.X = -1; } //------------------------------------------------------------------------------ ClipperOffset::~ClipperOffset() { Clear(); } //------------------------------------------------------------------------------ void ClipperOffset::Clear() { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) delete m_polyNodes.Childs[i]; m_polyNodes.Childs.clear(); m_lowest.X = -1; } //------------------------------------------------------------------------------ void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType) { int highI = (int)path.size() - 1; if (highI < 0) return; PolyNode* newNode = new PolyNode(); newNode->m_jointype = joinType; newNode->m_endtype = endType; //strip duplicate points from path and also get index to the lowest point ... if (endType == etClosedLine || endType == etClosedPolygon) while (highI > 0 && path[0] == path[highI]) highI--; newNode->Contour.reserve(highI + 1); newNode->Contour.push_back(path[0]); int j = 0, k = 0; for (int i = 1; i <= highI; i++) if (newNode->Contour[j] != path[i]) { j++; newNode->Contour.push_back(path[i]); if (path[i].Y > newNode->Contour[k].Y || (path[i].Y == newNode->Contour[k].Y && path[i].X < newNode->Contour[k].X)) k = j; } if (endType == etClosedPolygon && j < 2) { delete newNode; return; } m_polyNodes.AddChild(*newNode); //if this path's lowest pt is lower than all the others then update m_lowest if (endType != etClosedPolygon) return; if (m_lowest.X < 0) m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k); else { IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y]; if (newNode->Contour[k].Y > ip.Y || (newNode->Contour[k].Y == ip.Y && newNode->Contour[k].X < ip.X)) m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k); } } //------------------------------------------------------------------------------ void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType) { for (Paths::size_type i = 0; i < paths.size(); ++i) AddPath(paths[i], joinType, endType); } //------------------------------------------------------------------------------ void ClipperOffset::FixOrientations() { //fixup orientations of all closed paths if the orientation of the //closed path with the lowermost vertex is wrong ... if (m_lowest.X >= 0 && !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour)) { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) { PolyNode& node = *m_polyNodes.Childs[i]; if (node.m_endtype == etClosedPolygon || (node.m_endtype == etClosedLine && Orientation(node.Contour))) ReversePath(node.Contour); } } else { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) { PolyNode& node = *m_polyNodes.Childs[i]; if (node.m_endtype == etClosedLine && !Orientation(node.Contour)) ReversePath(node.Contour); } } } //------------------------------------------------------------------------------ void ClipperOffset::Execute(Paths& solution, double delta) { solution.clear(); FixOrientations(); DoOffset(delta); //now clean up 'corners' ... Clipper clpr; clpr.AddPaths(m_destPolys, ptSubject, true); if (delta > 0) { clpr.Execute(ctUnion, solution, pftPositive, pftPositive); } else { IntRect r = clpr.GetBounds(); Path outer(4); outer[0] = IntPoint(r.left - 10, r.bottom + 10); outer[1] = IntPoint(r.right + 10, r.bottom + 10); outer[2] = IntPoint(r.right + 10, r.top - 10); outer[3] = IntPoint(r.left - 10, r.top - 10); clpr.AddPath(outer, ptSubject, true); clpr.ReverseSolution(true); clpr.Execute(ctUnion, solution, pftNegative, pftNegative); if (solution.size() > 0) solution.erase(solution.begin()); } } //------------------------------------------------------------------------------ void ClipperOffset::Execute(PolyTree& solution, double delta) { solution.Clear(); FixOrientations(); DoOffset(delta); //now clean up 'corners' ... Clipper clpr; clpr.AddPaths(m_destPolys, ptSubject, true); if (delta > 0) { clpr.Execute(ctUnion, solution, pftPositive, pftPositive); } else { IntRect r = clpr.GetBounds(); Path outer(4); outer[0] = IntPoint(r.left - 10, r.bottom + 10); outer[1] = IntPoint(r.right + 10, r.bottom + 10); outer[2] = IntPoint(r.right + 10, r.top - 10); outer[3] = IntPoint(r.left - 10, r.top - 10); clpr.AddPath(outer, ptSubject, true); clpr.ReverseSolution(true); clpr.Execute(ctUnion, solution, pftNegative, pftNegative); //remove the outer PolyNode rectangle ... if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0) { PolyNode* outerNode = solution.Childs[0]; solution.Childs.reserve(outerNode->ChildCount()); solution.Childs[0] = outerNode->Childs[0]; solution.Childs[0]->Parent = outerNode->Parent; for (int i = 1; i < outerNode->ChildCount(); ++i) solution.AddChild(*outerNode->Childs[i]); } else solution.Clear(); } } //------------------------------------------------------------------------------ void ClipperOffset::DoOffset(double delta) { m_destPolys.clear(); m_delta = delta; //if Zero offset, just copy any CLOSED polygons to m_p and return ... if (NEAR_ZERO(delta)) { m_destPolys.reserve(m_polyNodes.ChildCount()); for (int i = 0; i < m_polyNodes.ChildCount(); i++) { PolyNode& node = *m_polyNodes.Childs[i]; if (node.m_endtype == etClosedPolygon) m_destPolys.push_back(node.Contour); } return; } //see offset_triginometry3.svg in the documentation folder ... if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit); else m_miterLim = 0.5; double y; if (ArcTolerance <= 0.0) y = def_arc_tolerance; else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance) y = std::fabs(delta) * def_arc_tolerance; else y = ArcTolerance; //see offset_triginometry2.svg in the documentation folder ... double steps = pi / std::acos(1 - y / std::fabs(delta)); if (steps > std::fabs(delta) * pi) steps = std::fabs(delta) * pi; //ie excessive precision check m_sin = std::sin(two_pi / steps); m_cos = std::cos(two_pi / steps); m_StepsPerRad = steps / two_pi; if (delta < 0.0) m_sin = -m_sin; m_destPolys.reserve(m_polyNodes.ChildCount() * 2); for (int i = 0; i < m_polyNodes.ChildCount(); i++) { PolyNode& node = *m_polyNodes.Childs[i]; m_srcPoly = node.Contour; int len = (int)m_srcPoly.size(); if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon))) continue; m_destPoly.clear(); if (len == 1) { if (node.m_jointype == jtRound) { double X = 1.0, Y = 0.0; for (cInt j = 1; j <= steps; j++) { m_destPoly.push_back(IntPoint( Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta))); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } } else { double X = -1.0, Y = -1.0; for (int j = 0; j < 4; ++j) { m_destPoly.push_back(IntPoint( Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta))); if (X < 0) X = 1; else if (Y < 0) Y = 1; else X = -1; } } m_destPolys.push_back(m_destPoly); continue; } //build m_normals ... m_normals.clear(); m_normals.reserve(len); for (int j = 0; j < len - 1; ++j) m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1])); if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon) m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0])); else m_normals.push_back(DoublePoint(m_normals[len - 2])); if (node.m_endtype == etClosedPolygon) { int k = len - 1; for (int j = 0; j < len; ++j) OffsetPoint(j, k, node.m_jointype); m_destPolys.push_back(m_destPoly); } else if (node.m_endtype == etClosedLine) { int k = len - 1; for (int j = 0; j < len; ++j) OffsetPoint(j, k, node.m_jointype); m_destPolys.push_back(m_destPoly); m_destPoly.clear(); //re-build m_normals ... DoublePoint n = m_normals[len -1]; for (int j = len - 1; j > 0; j--) m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); m_normals[0] = DoublePoint(-n.X, -n.Y); k = 0; for (int j = len - 1; j >= 0; j--) OffsetPoint(j, k, node.m_jointype); m_destPolys.push_back(m_destPoly); } else { int k = 0; for (int j = 1; j < len - 1; ++j) OffsetPoint(j, k, node.m_jointype); IntPoint pt1; if (node.m_endtype == etOpenButt) { int j = len - 1; pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X * delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta)); m_destPoly.push_back(pt1); pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X * delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta)); m_destPoly.push_back(pt1); } else { int j = len - 1; k = len - 2; m_sinA = 0; m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y); if (node.m_endtype == etOpenSquare) DoSquare(j, k); else DoRound(j, k); } //re-build m_normals ... for (int j = len - 1; j > 0; j--) m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y); k = len - 1; for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype); if (node.m_endtype == etOpenButt) { pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta), (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta)); m_destPoly.push_back(pt1); pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta), (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta)); m_destPoly.push_back(pt1); } else { k = 1; m_sinA = 0; if (node.m_endtype == etOpenSquare) DoSquare(0, 1); else DoRound(0, 1); } m_destPolys.push_back(m_destPoly); } } } //------------------------------------------------------------------------------ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) { //cross product ... m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y); if (std::fabs(m_sinA * m_delta) < 1.0) { //dot product ... double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y ); if (cosA > 0) // angle => 0 degrees { m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); return; } //else angle => 180 degrees } else if (m_sinA > 1.0) m_sinA = 1.0; else if (m_sinA < -1.0) m_sinA = -1.0; if (m_sinA * m_delta < 0) { m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); m_destPoly.push_back(m_srcPoly[j]); m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta), Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); } else switch (jointype) { case jtMiter: { double r = 1 + (m_normals[j].X * m_normals[k].X + m_normals[j].Y * m_normals[k].Y); if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k); break; } case jtSquare: DoSquare(j, k); break; case jtRound: DoRound(j, k); break; } k = j; } //------------------------------------------------------------------------------ void ClipperOffset::DoSquare(int j, int k) { double dx = std::tan(std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx)))); m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx)))); } //------------------------------------------------------------------------------ void ClipperOffset::DoMiter(int j, int k, double r) { double q = m_delta / r; m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q), Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q))); } //------------------------------------------------------------------------------ void ClipperOffset::DoRound(int j, int k) { double a = std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1); double X = m_normals[k].X, Y = m_normals[k].Y, X2; for (int i = 0; i < steps; ++i) { m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + X * m_delta), Round(m_srcPoly[j].Y + Y * m_delta))); X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + m_normals[j].X * m_delta), Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); } //------------------------------------------------------------------------------ // Miscellaneous public functions //------------------------------------------------------------------------------ void Clipper::DoSimplePolygons() { PolyOutList::size_type i = 0; while (i < m_PolyOuts.size()) { OutRec* outrec = m_PolyOuts[i++]; OutPt* op = outrec->Pts; if (!op || outrec->IsOpen) continue; do //for each Pt in Polygon until duplicate found do ... { OutPt* op2 = op->Next; while (op2 != outrec->Pts) { if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op) { //split the polygon into two ... OutPt* op3 = op->Prev; OutPt* op4 = op2->Prev; op->Prev = op4; op4->Next = op; op2->Prev = op3; op3->Next = op2; outrec->Pts = op; OutRec* outrec2 = CreateOutRec(); outrec2->Pts = op2; UpdateOutPtIdxs(*outrec2); if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts)) { //OutRec2 is contained by OutRec1 ... outrec2->IsHole = !outrec->IsHole; outrec2->FirstLeft = outrec; if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec); } else if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts)) { //OutRec1 is contained by OutRec2 ... outrec2->IsHole = outrec->IsHole; outrec->IsHole = !outrec2->IsHole; outrec2->FirstLeft = outrec->FirstLeft; outrec->FirstLeft = outrec2; if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2); } else { //the 2 polygons are separate ... outrec2->IsHole = outrec->IsHole; outrec2->FirstLeft = outrec->FirstLeft; if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2); } op2 = op; //ie get ready for the Next iteration } op2 = op2->Next; } op = op->Next; } while (op != outrec->Pts); } } //------------------------------------------------------------------------------ void ReversePath(Path& p) { std::reverse(p.begin(), p.end()); } //------------------------------------------------------------------------------ void ReversePaths(Paths& p) { for (Paths::size_type i = 0; i < p.size(); ++i) ReversePath(p[i]); } //------------------------------------------------------------------------------ void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType) { Clipper c; c.StrictlySimple(true); c.AddPath(in_poly, ptSubject, true); c.Execute(ctUnion, out_polys, fillType, fillType); } //------------------------------------------------------------------------------ void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType) { Clipper c; c.StrictlySimple(true); c.AddPaths(in_polys, ptSubject, true); c.Execute(ctUnion, out_polys, fillType, fillType); } //------------------------------------------------------------------------------ void SimplifyPolygons(Paths &polys, PolyFillType fillType) { SimplifyPolygons(polys, polys, fillType); } //------------------------------------------------------------------------------ inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2) { double Dx = ((double)pt1.X - pt2.X); double dy = ((double)pt1.Y - pt2.Y); return (Dx*Dx + dy*dy); } //------------------------------------------------------------------------------ double DistanceFromLineSqrd( const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2) { //The equation of a line in general form (Ax + By + C = 0) //given 2 points (x�,y�) & (x�,y�) is ... //(y� - y�)x + (x� - x�)y + (y� - y�)x� - (x� - x�)y� = 0 //A = (y� - y�); B = (x� - x�); C = (y� - y�)x� - (x� - x�)y� //perpendicular distance of point (x�,y�) = (Ax� + By� + C)/Sqrt(A� + B�) //see http://en.wikipedia.org/wiki/Perpendicular_distance double A = double(ln1.Y - ln2.Y); double B = double(ln2.X - ln1.X); double C = A * ln1.X + B * ln1.Y; C = A * pt.X + B * pt.Y - C; return (C * C) / (A * A + B * B); } //--------------------------------------------------------------------------- bool SlopesNearCollinear(const IntPoint& pt1, const IntPoint& pt2, const IntPoint& pt3, double distSqrd) { //this function is more accurate when the point that's geometrically //between the other 2 points is the one that's tested for distance. //ie makes it more likely to pick up 'spikes' ... if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y)) { if ((pt1.X > pt2.X) == (pt1.X < pt3.X)) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; else if ((pt2.X > pt1.X) == (pt2.X < pt3.X)) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } else { if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y)) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y)) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } } //------------------------------------------------------------------------------ bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd) { double Dx = (double)pt1.X - pt2.X; double dy = (double)pt1.Y - pt2.Y; return ((Dx * Dx) + (dy * dy) <= distSqrd); } //------------------------------------------------------------------------------ OutPt* ExcludeOp(OutPt* op) { OutPt* result = op->Prev; result->Next = op->Next; op->Next->Prev = result; result->Idx = 0; return result; } //------------------------------------------------------------------------------ void CleanPolygon(const Path& in_poly, Path& out_poly, double distance) { //distance = proximity in units/pixels below which vertices //will be stripped. Default ~= sqrt(2). size_t size = in_poly.size(); if (size == 0) { out_poly.clear(); return; } OutPt* outPts = new OutPt[size]; for (size_t i = 0; i < size; ++i) { outPts[i].Pt = in_poly[i]; outPts[i].Next = &outPts[(i + 1) % size]; outPts[i].Next->Prev = &outPts[i]; outPts[i].Idx = 0; } double distSqrd = distance * distance; OutPt* op = &outPts[0]; while (op->Idx == 0 && op->Next != op->Prev) { if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd)) { op = ExcludeOp(op); size--; } else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd)) { ExcludeOp(op->Next); op = ExcludeOp(op); size -= 2; } else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd)) { op = ExcludeOp(op); size--; } else { op->Idx = 1; op = op->Next; } } if (size < 3) size = 0; out_poly.resize(size); for (size_t i = 0; i < size; ++i) { out_poly[i] = op->Pt; op = op->Next; } delete [] outPts; } //------------------------------------------------------------------------------ void CleanPolygon(Path& poly, double distance) { CleanPolygon(poly, poly, distance); } //------------------------------------------------------------------------------ void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance) { out_polys.resize(in_polys.size()); for (Paths::size_type i = 0; i < in_polys.size(); ++i) CleanPolygon(in_polys[i], out_polys[i], distance); } //------------------------------------------------------------------------------ void CleanPolygons(Paths& polys, double distance) { CleanPolygons(polys, polys, distance); } //------------------------------------------------------------------------------ void Minkowski(const Path& poly, const Path& path, Paths& solution, bool isSum, bool isClosed) { int delta = (isClosed ? 1 : 0); size_t polyCnt = poly.size(); size_t pathCnt = path.size(); Paths pp; pp.reserve(pathCnt); if (isSum) for (size_t i = 0; i < pathCnt; ++i) { Path p; p.reserve(polyCnt); for (size_t j = 0; j < poly.size(); ++j) p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y)); pp.push_back(p); } else for (size_t i = 0; i < pathCnt; ++i) { Path p; p.reserve(polyCnt); for (size_t j = 0; j < poly.size(); ++j) p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y)); pp.push_back(p); } solution.clear(); solution.reserve((pathCnt + delta) * (polyCnt + 1)); for (size_t i = 0; i < pathCnt - 1 + delta; ++i) for (size_t j = 0; j < polyCnt; ++j) { Path quad; quad.reserve(4); quad.push_back(pp[i % pathCnt][j % polyCnt]); quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]); quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]); quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]); if (!Orientation(quad)) ReversePath(quad); solution.push_back(quad); } } //------------------------------------------------------------------------------ void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed) { Minkowski(pattern, path, solution, true, pathIsClosed); Clipper c; c.AddPaths(solution, ptSubject, true); c.Execute(ctUnion, solution, pftNonZero, pftNonZero); } //------------------------------------------------------------------------------ void TranslatePath(const Path& input, Path& output, const IntPoint delta) { //precondition: input != output output.resize(input.size()); for (size_t i = 0; i < input.size(); ++i) output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y); } //------------------------------------------------------------------------------ void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed) { Clipper c; for (size_t i = 0; i < paths.size(); ++i) { Paths tmp; Minkowski(pattern, paths[i], tmp, true, pathIsClosed); c.AddPaths(tmp, ptSubject, true); if (pathIsClosed) { Path tmp2; TranslatePath(paths[i], tmp2, pattern[0]); c.AddPath(tmp2, ptClip, true); } } c.Execute(ctUnion, solution, pftNonZero, pftNonZero); } //------------------------------------------------------------------------------ void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution) { Minkowski(poly1, poly2, solution, false, true); Clipper c; c.AddPaths(solution, ptSubject, true); c.Execute(ctUnion, solution, pftNonZero, pftNonZero); } //------------------------------------------------------------------------------ enum NodeType {ntAny, ntOpen, ntClosed}; void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths) { bool match = true; if (nodetype == ntClosed) match = !polynode.IsOpen(); else if (nodetype == ntOpen) return; if (!polynode.Contour.empty() && match) paths.push_back(polynode.Contour); for (int i = 0; i < polynode.ChildCount(); ++i) AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths); } //------------------------------------------------------------------------------ void PolyTreeToPaths(const PolyTree& polytree, Paths& paths) { paths.resize(0); paths.reserve(polytree.Total()); AddPolyNodeToPaths(polytree, ntAny, paths); } //------------------------------------------------------------------------------ void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths) { paths.resize(0); paths.reserve(polytree.Total()); AddPolyNodeToPaths(polytree, ntClosed, paths); } //------------------------------------------------------------------------------ void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths) { paths.resize(0); paths.reserve(polytree.Total()); //Open paths are top level only, so ... for (int i = 0; i < polytree.ChildCount(); ++i) if (polytree.Childs[i]->IsOpen()) paths.push_back(polytree.Childs[i]->Contour); } //------------------------------------------------------------------------------ std::ostream& operator <<(std::ostream &s, const IntPoint &p) { s << "(" << p.X << "," << p.Y << ")"; return s; } //------------------------------------------------------------------------------ std::ostream& operator <<(std::ostream &s, const Path &p) { if (p.empty()) return s; Path::size_type last = p.size() -1; for (Path::size_type i = 0; i < last; i++) s << "(" << p[i].X << "," << p[i].Y << "), "; s << "(" << p[last].X << "," << p[last].Y << ")\n"; return s; } //------------------------------------------------------------------------------ std::ostream& operator <<(std::ostream &s, const Paths &p) { for (Paths::size_type i = 0; i < p.size(); i++) s << p[i]; s << "\n"; return s; } //------------------------------------------------------------------------------ } //ClipperLib namespace �����geometry-3.0.0/src/PaxHeaders.28738/clipper.hpp�����������������������������������������������������0000644�0000000�0000000�00000000132�13066736044�016064� x����������������������������������������������������������������������������������������������������ustar�00�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������30 mtime=1490795556.696871393 30 atime=1490795556.696871393 30 ctime=1490795556.716871764 ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-3.0.0/src/clipper.hpp����������������������������������������������������������������������0000644�0001750�0001750�00000040033�13066736044�016240� 0����������������������������������������������������������������������������������������������������ustar�00olaf����������������������������olaf����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* (C) 2012-2017 Angus Johnson Boost Software License - Version 1.0 - August 17th, 2003 http://www.boost.org/LICENSE_1_0.txt Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /******************************************************************************* * * * Author : Angus Johnson * * Version : 6.4.2 * * Date : 27 February 2017 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2010-2017 * * * * License: * * Use, modification & distribution is subject to Boost Software License Ver 1. * * http://www.boost.org/LICENSE_1_0.txt * * * * Attributions: * * The code in this library is an extension of Bala Vatti's clipping algorithm: * * "A generic solution to polygon clipping" * * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. * * http://portal.acm.org/citation.cfm?id=129906 * * * * Computer graphics and geometric modeling: implementation and algorithms * * By Max K. Agoston * * Springer; 1 edition (January 4, 2005) * * http://books.google.com/books?q=vatti+clipping+agoston * * * * See also: * * "Polygon Offsetting by Computing Winding Numbers" * * Paper no. DETC2005-85513 pp. 565-575 * * ASME 2005 International Design Engineering Technical Conferences * * and Computers and Information in Engineering Conference (IDETC/CIE2005) * * September 24-28, 2005 , Long Beach, California, USA * * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf * * * *******************************************************************************/ #ifndef clipper_hpp #define clipper_hpp #define CLIPPER_VERSION "6.4.2" //use_int32: When enabled 32bit ints are used instead of 64bit ints. This //improve performance but coordinate values are limited to the range +/- 46340 //#define use_int32 //use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance. #define use_xyz //use_lines: Enables line clipping. Adds a very minor cost to performance. #define use_lines //use_deprecated: Enables temporary support for the obsolete functions //#define use_deprecated #include #include #include #include #include #include #include #include #include namespace ClipperLib { enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor }; enum PolyType { ptSubject, ptClip }; //By far the most widely used winding rules for polygon filling are //EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32) //Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL) //see http://glprogramming.com/red/chapter11.html enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative }; #ifdef use_int32 typedef int cInt; static cInt const loRange = 0x7FFF; static cInt const hiRange = 0x7FFF; #else typedef signed long long cInt; static cInt const loRange = 0x3FFFFFFF; static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL; typedef signed long long long64; //used by Int128 class typedef unsigned long long ulong64; #endif struct IntPoint { cInt X; cInt Y; #ifdef use_xyz cInt Z; IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {}; #else IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {}; #endif friend inline bool operator== (const IntPoint& a, const IntPoint& b) { return a.X == b.X && a.Y == b.Y; } friend inline bool operator!= (const IntPoint& a, const IntPoint& b) { return a.X != b.X || a.Y != b.Y; } }; //------------------------------------------------------------------------------ typedef std::vector< IntPoint > Path; typedef std::vector< Path > Paths; inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;} inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;} std::ostream& operator <<(std::ostream &s, const IntPoint &p); std::ostream& operator <<(std::ostream &s, const Path &p); std::ostream& operator <<(std::ostream &s, const Paths &p); struct DoublePoint { double X; double Y; DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {} DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {} }; //------------------------------------------------------------------------------ #ifdef use_xyz typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt); #endif enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4}; enum JoinType {jtSquare, jtRound, jtMiter}; enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound}; class PolyNode; typedef std::vector< PolyNode* > PolyNodes; class PolyNode { public: PolyNode(); virtual ~PolyNode(){}; Path Contour; PolyNodes Childs; PolyNode* Parent; PolyNode* GetNext() const; bool IsHole() const; bool IsOpen() const; int ChildCount() const; private: //PolyNode& operator =(PolyNode& other); unsigned Index; //node index in Parent.Childs bool m_IsOpen; JoinType m_jointype; EndType m_endtype; PolyNode* GetNextSiblingUp() const; void AddChild(PolyNode& child); friend class Clipper; //to access Index friend class ClipperOffset; }; class PolyTree: public PolyNode { public: ~PolyTree(){ Clear(); }; PolyNode* GetFirst() const; void Clear(); int Total() const; private: //PolyTree& operator =(PolyTree& other); PolyNodes AllNodes; friend class Clipper; //to access AllNodes }; bool Orientation(const Path &poly); double Area(const Path &poly); int PointInPolygon(const IntPoint &pt, const Path &path); void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd); void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd); void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd); void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415); void CleanPolygon(Path& poly, double distance = 1.415); void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415); void CleanPolygons(Paths& polys, double distance = 1.415); void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed); void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed); void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution); void PolyTreeToPaths(const PolyTree& polytree, Paths& paths); void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths); void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths); void ReversePath(Path& p); void ReversePaths(Paths& p); struct IntRect { cInt left; cInt top; cInt right; cInt bottom; }; //enums that are used internally ... enum EdgeSide { esLeft = 1, esRight = 2}; //forward declarations (for stuff used internally) ... struct TEdge; struct IntersectNode; struct LocalMinimum; struct OutPt; struct OutRec; struct Join; typedef std::vector < OutRec* > PolyOutList; typedef std::vector < TEdge* > EdgeList; typedef std::vector < Join* > JoinList; typedef std::vector < IntersectNode* > IntersectList; //------------------------------------------------------------------------------ //ClipperBase is the ancestor to the Clipper class. It should not be //instantiated directly. This class simply abstracts the conversion of sets of //polygon coordinates into edge objects that are stored in a LocalMinima list. class ClipperBase { public: ClipperBase(); virtual ~ClipperBase(); virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed); bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed); virtual void Clear(); IntRect GetBounds(); bool PreserveCollinear() {return m_PreserveCollinear;}; void PreserveCollinear(bool value) {m_PreserveCollinear = value;}; protected: void DisposeLocalMinimaList(); TEdge* AddBoundsToLML(TEdge *e, bool IsClosed); virtual void Reset(); TEdge* ProcessBound(TEdge* E, bool IsClockwise); void InsertScanbeam(const cInt Y); bool PopScanbeam(cInt &Y); bool LocalMinimaPending(); bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin); OutRec* CreateOutRec(); void DisposeAllOutRecs(); void DisposeOutRec(PolyOutList::size_type index); void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2); void DeleteFromAEL(TEdge *e); void UpdateEdgeIntoAEL(TEdge *&e); typedef std::vector MinimaList; MinimaList::iterator m_CurrentLM; MinimaList m_MinimaList; bool m_UseFullRange; EdgeList m_edges; bool m_PreserveCollinear; bool m_HasOpenPaths; PolyOutList m_PolyOuts; TEdge *m_ActiveEdges; typedef std::priority_queue ScanbeamList; ScanbeamList m_Scanbeam; }; //------------------------------------------------------------------------------ class Clipper : public virtual ClipperBase { public: Clipper(int initOptions = 0); bool Execute(ClipType clipType, Paths &solution, PolyFillType fillType = pftEvenOdd); bool Execute(ClipType clipType, Paths &solution, PolyFillType subjFillType, PolyFillType clipFillType); bool Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType = pftEvenOdd); bool Execute(ClipType clipType, PolyTree &polytree, PolyFillType subjFillType, PolyFillType clipFillType); bool ReverseSolution() { return m_ReverseOutput; }; void ReverseSolution(bool value) {m_ReverseOutput = value;}; bool StrictlySimple() {return m_StrictSimple;}; void StrictlySimple(bool value) {m_StrictSimple = value;}; //set the callback function for z value filling on intersections (otherwise Z is 0) #ifdef use_xyz void ZFillFunction(ZFillCallback zFillFunc); #endif protected: virtual bool ExecuteInternal(); private: JoinList m_Joins; JoinList m_GhostJoins; IntersectList m_IntersectList; ClipType m_ClipType; typedef std::list MaximaList; MaximaList m_Maxima; TEdge *m_SortedEdges; bool m_ExecuteLocked; PolyFillType m_ClipFillType; PolyFillType m_SubjFillType; bool m_ReverseOutput; bool m_UsingPolyTree; bool m_StrictSimple; #ifdef use_xyz ZFillCallback m_ZFill; //custom callback #endif void SetWindingCount(TEdge& edge); bool IsEvenOddFillType(const TEdge& edge) const; bool IsEvenOddAltFillType(const TEdge& edge) const; void InsertLocalMinimaIntoAEL(const cInt botY); void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge); void AddEdgeToSEL(TEdge *edge); bool PopEdgeFromSEL(TEdge *&edge); void CopyAELToSEL(); void DeleteFromSEL(TEdge *e); void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2); bool IsContributing(const TEdge& edge) const; bool IsTopHorz(const cInt XPos); void DoMaxima(TEdge *e); void ProcessHorizontals(); void ProcessHorizontal(TEdge *horzEdge); void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt); OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt); OutRec* GetOutRec(int idx); void AppendPolygon(TEdge *e1, TEdge *e2); void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt); OutPt* AddOutPt(TEdge *e, const IntPoint &pt); OutPt* GetLastOutPt(TEdge *e); bool ProcessIntersections(const cInt topY); void BuildIntersectList(const cInt topY); void ProcessIntersectList(); void ProcessEdgesAtTopOfScanbeam(const cInt topY); void BuildResult(Paths& polys); void BuildResult2(PolyTree& polytree); void SetHoleState(TEdge *e, OutRec *outrec); void DisposeIntersectNodes(); bool FixupIntersectionOrder(); void FixupOutPolygon(OutRec &outrec); void FixupOutPolyline(OutRec &outrec); bool IsHole(TEdge *e); bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl); void FixHoleLinkage(OutRec &outrec); void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt); void ClearJoins(); void ClearGhostJoins(); void AddGhostJoin(OutPt *op, const IntPoint offPt); bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2); void JoinCommonEdges(); void DoSimplePolygons(); void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec); void FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec); void FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec); #ifdef use_xyz void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2); #endif }; //------------------------------------------------------------------------------ class ClipperOffset { public: ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25); ~ClipperOffset(); void AddPath(const Path& path, JoinType joinType, EndType endType); void AddPaths(const Paths& paths, JoinType joinType, EndType endType); void Execute(Paths& solution, double delta); void Execute(PolyTree& solution, double delta); void Clear(); double MiterLimit; double ArcTolerance; private: Paths m_destPolys; Path m_srcPoly; Path m_destPoly; std::vector m_normals; double m_delta, m_sinA, m_sin, m_cos; double m_miterLim, m_StepsPerRad; IntPoint m_lowest; PolyNode m_polyNodes; void FixOrientations(); void DoOffset(double delta); void OffsetPoint(int j, int& k, JoinType jointype); void DoSquare(int j, int k); void DoMiter(int j, int k, double r); void DoRound(int j, int k); }; //------------------------------------------------------------------------------ class clipperException : public std::exception { public: clipperException(const char* description): m_descr(description) {} virtual ~clipperException() throw() {} virtual const char* what() const throw() {return m_descr.c_str();} private: std::string m_descr; }; //------------------------------------------------------------------------------ } //ClipperLib namespace #endif //clipper_hpp �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������