vrml_layer.cpp 43.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * file: vrml_layer.cpp
 *
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2013  Cirilo Bernardo
 *
 * 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 2
 * 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, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

26 27 28 29 30 31 32 33
// Wishlist:
// 1. crop anything outside the board outline on PTH, silk, and copper layers
// 2. on the PTH layer, handle cropped holes differently from others;
//    these are assumed to be castellated edges and the profile is not
//    a closed loop as assumed for all other outlines.
// 3. a scheme is needed to tell a castellated edge from a plain board edge

#include <iostream>
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
#include <sstream>
#include <string>
#include <iomanip>
#include <cmath>
#include <vrml_layer.h>

#ifndef CALLBACK
#define CALLBACK
#endif

#define GLCALLBACK(x) (( void (CALLBACK*)() )&(x))

// minimum sides to a circle
#define MIN_NSIDES 6

static void FormatDoublet( double x, double y, int precision, std::string& strx, std::string& stry )
{
    std::ostringstream ostr;

    ostr << std::fixed << std::setprecision( precision );

    ostr << x;
    strx = ostr.str();

    ostr.str( "" );
    ostr << y;
    stry = ostr.str();

    while( *strx.rbegin() == '0' )
        strx.erase( strx.size() - 1 );

    while( *stry.rbegin() == '0' )
        stry.erase( stry.size() - 1 );
}


static void FormatSinglet( double x, int precision, std::string& strx )
{
    std::ostringstream ostr;

    ostr << std::fixed << std::setprecision( precision );

    ostr << x;
    strx = ostr.str();

    while( *strx.rbegin() == '0' )
        strx.erase( strx.size() - 1 );
}


int VRML_LAYER::calcNSides( double aRadius, double aAngle )
{
    // check #segments on ends of arc
    int maxSeg = maxArcSeg * aAngle / M_PI;

    if( maxSeg < 3 )
        maxSeg = 3;

    int csides = aRadius * M_PI / minSegLength;

    if( csides < 0 )
        csides = -csides;

    if( csides > maxSeg )
    {
        if( csides < 2 * maxSeg )
            csides /= 2;
        else
            csides = (((double) csides) * minSegLength / maxSegLength );
    }

    if( csides < 3 )
        csides = 3;

    if( (csides & 1) == 0 )
        csides += 1;

    return csides;
}


static void CALLBACK vrml_tess_begin( GLenum cmd, void* user_data )
{
    VRML_LAYER* lp = (VRML_LAYER*) user_data;

    lp->glStart( cmd );
}


static void CALLBACK vrml_tess_end( void* user_data )
{
    VRML_LAYER* lp = (VRML_LAYER*) user_data;

    lp->glEnd();
}


static void CALLBACK vrml_tess_vertex( void* vertex_data, void* user_data )
{
    VRML_LAYER* lp = (VRML_LAYER*) user_data;

    lp->glPushVertex( (VERTEX_3D*) vertex_data );
}


static void CALLBACK vrml_tess_err( GLenum errorID, void* user_data )
{
    VRML_LAYER* lp = (VRML_LAYER*) user_data;

    lp->Fault = true;
    lp->SetGLError( errorID );
}


148
static void CALLBACK vrml_tess_combine( GLdouble coords[3], VERTEX_3D* vertex_data[4],
149 150 151 152
        GLfloat weight[4], void** outData, void* user_data )
{
    VRML_LAYER* lp = (VRML_LAYER*) user_data;

153 154 155 156 157 158 159 160 161 162 163 164 165
    // the plating is set to true only if all are plated
    bool plated = vertex_data[0]->pth;

    if( !vertex_data[1]->pth )
        plated = false;

    if( vertex_data[2] && !vertex_data[2]->pth )
        plated = false;

    if( vertex_data[3] && !vertex_data[3]->pth )
        plated = false;

    *outData = lp->AddExtraVertex( coords[0], coords[1], plated );
166 167 168 169 170 171 172 173 174
}


VRML_LAYER::VRML_LAYER()
{
    // arc parameters suitable to mm measurements
    maxArcSeg = 48;
    minSegLength = 0.1;
    maxSegLength = 0.5;
175 176
    offsetX = 0.0;
    offsetY = 0.0;
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    fix = false;
    Fault = false;
    idx = 0;
    ord = 0;
    glcmd   = 0;
    pholes  = NULL;

    tess = gluNewTess();

    if( !tess )
        return;

    // set up the tesselator callbacks
    gluTessCallback( tess, GLU_TESS_BEGIN_DATA, GLCALLBACK( vrml_tess_begin ) );

    gluTessCallback( tess, GLU_TESS_VERTEX_DATA, GLCALLBACK( vrml_tess_vertex ) );

    gluTessCallback( tess, GLU_TESS_END_DATA, GLCALLBACK( vrml_tess_end ) );

    gluTessCallback( tess, GLU_TESS_ERROR_DATA, GLCALLBACK( vrml_tess_err ) );

    gluTessCallback( tess, GLU_TESS_COMBINE_DATA, GLCALLBACK( vrml_tess_combine ) );

    gluTessProperty( tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE );

    gluTessNormal( tess, 0, 0, 1 );
}


VRML_LAYER::~VRML_LAYER()
{
    Clear();

    if( tess )
    {
        gluDeleteTess( tess );
        tess = NULL;
    }
}


void VRML_LAYER::GetArcParams( int& aMaxSeg, double& aMinLength, double& aMaxLength )
{
    aMaxSeg = maxArcSeg;
    aMinLength = minSegLength;
    aMaxLength = maxSegLength;
}

bool VRML_LAYER::SetArcParams( int aMaxSeg, double aMinLength, double aMaxLength )
{
    if( aMaxSeg < 8 )
        aMaxSeg = 8;

    if( aMinLength <= 0 || aMaxLength <= aMinLength )
        return false;

    maxArcSeg = aMaxSeg;
    minSegLength = aMinLength;
    maxSegLength = aMaxLength;
    return true;
}


// clear all data
void VRML_LAYER::Clear( void )
{
    int i;

    fix = false;
    idx = 0;

    for( i = contours.size(); i > 0; --i )
    {
        delete contours.back();
        contours.pop_back();
    }

255 256
    pth.clear();

unknown's avatar
unknown committed
257
    areas.clear();
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

    for( i = vertices.size(); i > 0; --i )
    {
        delete vertices.back();
        vertices.pop_back();
    }

    clearTmp();
}


// clear ephemeral data in between invocations of the tesselation routine
void VRML_LAYER::clearTmp( void )
{
    unsigned int i;

    Fault   = false;
    hidx    = 0;
    eidx    = 0;
    ord = 0;
    glcmd = 0;

unknown's avatar
unknown committed
280
    triplets.clear();
281
    solid.clear();
282 283 284 285 286 287 288

    for( i = outline.size(); i > 0; --i )
    {
        delete outline.back();
        outline.pop_back();
    }

unknown's avatar
unknown committed
289
    ordmap.clear();
290 291 292 293 294 295 296 297 298

    for( i = extra_verts.size(); i > 0; --i )
    {
        delete extra_verts.back();
        extra_verts.pop_back();
    }

    // note: unlike outline and extra_verts,
    // vlist is not responsible for memory management
unknown's avatar
unknown committed
299
    vlist.clear();
300 301 302 303 304 305 306 307 308 309 310

    // go through the vertex list and reset ephemeral parameters
    for( i = 0; i < vertices.size(); ++i )
    {
        vertices[i]->o = -1;
    }
}


// create a new contour to be populated; returns an index
// into the contour list or -1 if there are problems
311
int VRML_LAYER::NewContour(  bool aPlatedHole )
312 313 314 315 316 317 318 319 320 321 322 323
{
    if( fix )
        return -1;

    std::list<int>* contour = new std::list<int>;

    if( !contour )
        return -1;

    contours.push_back( contour );
    areas.push_back( 0.0 );

324 325
    pth.push_back( aPlatedHole );

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    return contours.size() - 1;
}


// adds a vertex to the existing list and places its index in
// an existing contour; returns true if OK,
// false otherwise (indexed contour does not exist)
bool VRML_LAYER::AddVertex( int aContourID, double aXpos, double aYpos )
{
    if( fix )
    {
        error = "AddVertex(): no more vertices may be added (Tesselate was previously executed)";
        return false;
    }

    if( aContourID < 0 || (unsigned int) aContourID >= contours.size() )
    {
        error = "AddVertex(): aContour is not within a valid range";
        return false;
    }

    VERTEX_3D* vertex = new VERTEX_3D;

    if( !vertex )
    {
        error = "AddVertex(): a new vertex could not be allocated";
        return false;
    }

    vertex->x   = aXpos;
    vertex->y   = aYpos;
    vertex->i   = idx++;
    vertex->o   = -1;
359
    vertex->pth = pth[ aContourID ];
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

    VERTEX_3D* v2 = NULL;

    if( contours[aContourID]->size() > 0 )
        v2 = vertices[ contours[aContourID]->back() ];

    vertices.push_back( vertex );
    contours[aContourID]->push_back( vertex->i );

    if( v2 )
        areas[aContourID] += ( aXpos - v2->x ) * ( aYpos + v2->y );

    return true;
}


// ensure the winding of a contour with respect to the normal (0, 0, 1);
// set 'hole' to true to ensure a hole (clockwise winding)
bool VRML_LAYER::EnsureWinding( int aContourID, bool aHoleFlag )
{
    if( aContourID < 0 || (unsigned int) aContourID >= contours.size() )
    {
        error = "EnsureWinding(): aContour is outside the valid range";
        return false;
    }

    std::list<int>* cp = contours[aContourID];

    if( cp->size() < 3 )
    {
        error = "EnsureWinding(): there are fewer than 3 vertices";
        return false;
    }

    double dir = areas[aContourID];

    VERTEX_3D* vp0 = vertices[ cp->back() ];
    VERTEX_3D* vp1 = vertices[ cp->front() ];

    dir += ( vp1->x - vp0->x ) * ( vp1->y + vp0->y );

    // if dir is positive, winding is CW
    if( ( aHoleFlag && dir < 0 ) || ( !aHoleFlag && dir > 0 ) )
    {
        cp->reverse();
        areas[aContourID] = -areas[aContourID];
    }

    return true;
}


bool VRML_LAYER::AppendCircle( double aXpos, double aYpos,
                               double aRadius, int aContourID,
                               bool aHoleFlag )
{
    if( aContourID < 0 || (unsigned int) aContourID >= contours.size() )
    {
        error = "AppendCircle(): invalid contour (out of range)";
        return false;
    }

    int nsides = M_PI * 2.0 * aRadius / minSegLength;

    if( nsides > maxArcSeg )
    {
        if( nsides > 2 * maxArcSeg )
        {
            // use segments approx. maxAr
            nsides = M_PI * 2.0 * aRadius / maxSegLength;
        }
        else
        {
            nsides /= 2;
        }
    }

    if( nsides < MIN_NSIDES )
        nsides = MIN_NSIDES;

    // even numbers give prettier results for circles
    if( nsides & 1 )
        nsides += 1;

    double da = M_PI * 2.0 / nsides;

    bool fail = false;

    if( aHoleFlag )
    {
        fail |= !AddVertex( aContourID, aXpos + aRadius, aYpos );

        for( double angle = da; angle < M_PI * 2; angle += da )
            fail |= !AddVertex( aContourID, aXpos + aRadius * cos( angle ),
                                aYpos - aRadius * sin( angle ) );
    }
    else
    {
        fail |= !AddVertex( aContourID, aXpos + aRadius, aYpos );

        for( double angle = da; angle < M_PI * 2; angle += da )
            fail |= !AddVertex( aContourID, aXpos + aRadius * cos( angle ),
                                aYpos + aRadius * sin( angle ) );
    }

    return !fail;
}


// adds a circle the existing list; if 'hole' is true the contour is
// a hole. Returns true if OK.
471 472
bool VRML_LAYER::AddCircle( double aXpos, double aYpos, double aRadius,
                            bool aHoleFlag, bool aPlatedHole )
473
{
474 475 476 477 478 479
    int pad;

    if( aHoleFlag && aPlatedHole )
        pad = NewContour( true );
    else
        pad = NewContour( false );
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

    if( pad < 0 )
    {
        error = "AddCircle(): failed to add a contour";
        return false;
    }

    return AppendCircle( aXpos, aYpos, aRadius, pad, aHoleFlag );
}


// adds a slotted pad with orientation given by angle; if 'hole' is true the
// contour is a hole. Returns true if OK.
bool VRML_LAYER::AddSlot( double aCenterX, double aCenterY,
                          double aSlotLength, double aSlotWidth,
495
                          double aAngle, bool aHoleFlag, bool aPlatedHole )
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
{
    aAngle *= M_PI / 180.0;

    if( aSlotWidth > aSlotLength )
    {
        aAngle += M_PI2;
        std::swap( aSlotLength, aSlotWidth );
    }

    aSlotWidth /= 2.0;
    aSlotLength = aSlotLength / 2.0 - aSlotWidth;

    int csides = calcNSides( aSlotWidth, M_PI );

    double capx, capy;

    capx    = aCenterX + cos( aAngle ) * aSlotLength;
    capy    = aCenterY + sin( aAngle ) * aSlotLength;

    double ang, da;
    int i;
517 518 519 520 521 522
    int pad;

    if( aHoleFlag && aPlatedHole )
        pad = NewContour( true );
    else
        pad = NewContour( false );
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619

    if( pad < 0 )
    {
        error = "AddCircle(): failed to add a contour";
        return false;
    }

    da = M_PI / csides;
    bool fail = false;

    if( aHoleFlag )
    {
        for( ang = aAngle + M_PI2, i = 0; i < csides; ang -= da, ++i )
            fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                                capy + aSlotWidth * sin( ang ) );

        ang = aAngle - M_PI2;
        fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                            capy + aSlotWidth * sin( ang ) );

        capx    = aCenterX - cos( aAngle ) * aSlotLength;
        capy    = aCenterY - sin( aAngle ) * aSlotLength;

        for( ang = aAngle - M_PI2, i = 0; i < csides; ang -= da, ++i )
            fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                                capy + aSlotWidth * sin( ang ) );

        ang = aAngle + M_PI2;
        fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                            capy + aSlotWidth * sin( ang ) );
    }
    else
    {
        for( ang = aAngle - M_PI2, i = 0; i < csides; ang += da, ++i )
            fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                                capy + aSlotWidth * sin( ang ) );

        ang = aAngle + M_PI2;
        fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                            capy + aSlotWidth * sin( ang ) );

        capx    = aCenterX - cos( aAngle ) * aSlotLength;
        capy    = aCenterY - sin( aAngle ) * aSlotLength;

        for( ang = aAngle + M_PI2, i = 0; i < csides; ang += da, ++i )
            fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                                capy + aSlotWidth * sin( ang ) );

        ang = aAngle - M_PI2;
        fail |= !AddVertex( pad, capx + aSlotWidth * cos( ang ),
                            capy + aSlotWidth * sin( ang ) );
    }

    return !fail;
}


// adds an arc to the given center, start point, pen width, and angle (degrees).
bool VRML_LAYER::AppendArc( double aCenterX, double aCenterY, double aRadius,
                            double aStartAngle, double aAngle, int aContourID )
{
    if( aContourID < 0 || (unsigned int) aContourID >= contours.size() )
    {
        error = "AppendArc(): invalid contour (out of range)";
        return false;
    }

    aAngle = aAngle / 180.0 * M_PI;
    aStartAngle = aStartAngle / 180.0 * M_PI;

    int nsides = calcNSides( aRadius, aAngle );

    double da = aAngle / nsides;

    bool fail = false;

    if( aAngle > 0 )
    {
        aAngle += aStartAngle;
        for( double ang = aStartAngle; ang < aAngle; ang += da )
            fail |= !AddVertex( aContourID, aCenterX + aRadius * cos( ang ),
                                aCenterY + aRadius * sin( ang ) );
    }
    else
    {
        aAngle += aStartAngle;
        for( double ang = aStartAngle; ang > aAngle; ang += da )
            fail |= !AddVertex( aContourID, aCenterX + aRadius * cos( ang ),
                                aCenterY + aRadius * sin( ang ) );
    }

    return !fail;
}


// adds an arc with the given center, start point, pen width, and angle (degrees).
bool VRML_LAYER::AddArc( double aCenterX, double aCenterY, double aStartX, double aStartY,
620
                         double aArcWidth, double aAngle, bool aHoleFlag, bool aPlatedHole )
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
{
    aAngle *= M_PI / 180.0;

    // we don't accept small angles; in fact, 1 degree ( 0.01745 ) is already
    // way too small but we must set a limit somewhere
    if( aAngle < 0.01745 && aAngle > -0.01745 )
    {
        error = "AddArc(): angle is too small: abs( angle ) < 1 degree";
        return false;
    }

    double rad = sqrt( (aStartX - aCenterX) * (aStartX - aCenterX)
                        + (aStartY - aCenterY) * (aStartY - aCenterY) );

    aArcWidth /= 2.0;    // this is the radius of the caps

    // we will not accept an arc with an inner radius close to zero so we
    // set a limit here. the end result will vary somewhat depending on
    // the output units
    if( aArcWidth >= ( rad * 1.01 ) )
    {
        error = "AddArc(): width/2 exceeds radius*1.01";
        return false;
    }

    // calculate the radii of the outer and inner arcs
    double  orad    = rad + aArcWidth;
    double  irad    = rad - aArcWidth;

    int osides  = calcNSides( orad, aAngle );
    int isides  = calcNSides( irad, aAngle );
    int csides  = calcNSides( aArcWidth, M_PI );

    double  stAngle     = atan2( aStartY - aCenterY, aStartX - aCenterX );
    double  endAngle    = stAngle + aAngle;

    // calculate ends of inner and outer arc
    double  oendx   = aCenterX + orad* cos( endAngle );
    double  oendy   = aCenterY + orad* sin( endAngle );
    double  ostx    = aCenterX + orad* cos( stAngle );
    double  osty    = aCenterY + orad* sin( stAngle );

    double  iendx   = aCenterX + irad* cos( endAngle );
    double  iendy   = aCenterY + irad* sin( endAngle );
    double  istx    = aCenterX + irad* cos( stAngle );
    double  isty    = aCenterY + irad* sin( stAngle );

    if( ( aAngle < 0 && !aHoleFlag ) || ( aAngle > 0 && aHoleFlag ) )
    {
        aAngle = -aAngle;
        std::swap( stAngle, endAngle );
        std::swap( oendx, ostx );
        std::swap( oendy, osty );
        std::swap( iendx, istx );
        std::swap( iendy, isty );
    }

678 679 680 681 682 683
    int arc;

    if( aHoleFlag && aPlatedHole )
        arc = NewContour( true );
    else
        arc = NewContour( false );
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

    if( arc < 0 )
    {
        error = "AddArc(): could not create a contour";
        return false;
    }

    // trace the outer arc:
    int i;
    double  ang;
    double  da = aAngle / osides;

    for( ang = stAngle, i = 0; i < osides; ang += da, ++i )
        AddVertex( arc, aCenterX + orad * cos( ang ), aCenterY + orad * sin( ang ) );

    // trace the first cap
    double  capx    = ( iendx + oendx ) / 2.0;
    double  capy    = ( iendy + oendy ) / 2.0;

    if( aHoleFlag )
        da = -M_PI / csides;
    else
        da = M_PI / csides;

    for( ang = endAngle, i = 0; i < csides; ang += da, ++i )
        AddVertex( arc, capx + aArcWidth * cos( ang ), capy + aArcWidth * sin( ang ) );

    // trace the inner arc:
    da = -aAngle / isides;

    for( ang = endAngle, i = 0; i < isides; ang += da, ++i )
        AddVertex( arc, aCenterX + irad * cos( ang ), aCenterY + irad * sin( ang ) );

    // trace the final cap
    capx    = ( istx + ostx ) / 2.0;
    capy    = ( isty + osty ) / 2.0;

    if( aHoleFlag )
        da = -M_PI / csides;
    else
        da = M_PI / csides;

    for( ang = stAngle + M_PI, i = 0; i < csides; ang += da, ++i )
        AddVertex( arc, capx + aArcWidth * cos( ang ), capy + aArcWidth * sin( ang ) );

    return true;
}


// tesselates the contours in preparation for a 3D output;
// returns true if all was fine, false otherwise
735
bool VRML_LAYER::Tesselate( VRML_LAYER* holes, bool aHolesOnly )
736 737 738 739 740 741 742 743 744 745
{
    if( !tess )
    {
        error = "Tesselate(): GLU tesselator was not initialized";
        return false;
    }

    pholes  = holes;
    Fault   = false;

746 747 748 749 750 751
    if( aHolesOnly )
        gluTessProperty( tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NEGATIVE );
    else
        gluTessProperty( tess, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE );


752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    if( contours.size() < 1 || vertices.size() < 3 )
    {
        error = "Tesselate(): not enough vertices";
        return false;
    }

    // finish the winding calculation on all vertices prior to setting 'fix'
    if( !fix )
    {
        for( unsigned int i = 0; i < contours.size(); ++i )
        {
            if( contours[i]->size() < 3 )
                continue;

            VERTEX_3D* vp0 = vertices[ contours[i]->back() ];
            VERTEX_3D* vp1 = vertices[ contours[i]->front() ];
            areas[i] += ( vp1->x - vp0->x ) * ( vp1->y + vp0->y );
        }
    }

    // prevent the addition of any further contours and contour vertices
    fix = true;

    // clear temporary internals which may have been used in a previous run
    clearTmp();

    // request an outline
    gluTessProperty( tess, GLU_TESS_BOUNDARY_ONLY, GL_TRUE );

    // adjust internal indices for extra points and holes
    if( holes )
        hidx = holes->GetSize();
    else
        hidx = 0;

    eidx = idx + hidx;

789 790 791 792 793 794 795 796 797 798 799
    if( aHolesOnly && ( checkNContours( true ) == 0 ) )
    {
        error = "tesselate(): no hole contours";
        return false;
    }
    else if( !aHolesOnly && ( checkNContours( false ) == 0 ) )
    {
        error = "tesselate(): no solid contours";
        return false;
    }

800 801 802
    // open the polygon
    gluTessBeginPolygon( tess, this );

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    if( aHolesOnly )
    {
        pholes = NULL;  // do not accept foreign holes
        hidx = 0;
        eidx = idx;

        // add holes
        pushVertices( true );

        gluTessEndPolygon( tess );

        if( Fault )
            return false;

        return true;
    }

unknown's avatar
unknown committed
820
    // add solid outlines
821 822 823 824 825 826 827 828
    pushVertices( false );

    // close the polygon
    gluTessEndPolygon( tess );

    if( Fault )
        return false;

829 830 831 832 833 834 835
    // if there are no outlines we cannot proceed
    if( outline.empty() )
    {
        error = "tesselate(): no points in result";
        return false;
    }

unknown's avatar
unknown committed
836 837 838 839
    // at this point we have a solid outline; add it to the tesselator
    gluTessBeginPolygon( tess, this );

    if( !pushOutline( NULL ) )
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        return false;

    // add the holes contained by this object
    pushVertices( true );

    // import external holes (if any)
    if( hidx && ( holes->Import( idx, tess ) < 0 ) )
    {
        std::ostringstream ostr;
        ostr << "Tesselate():FAILED: " << holes->GetError();
        error = ostr.str();
        return NULL;
    }

    if( Fault )
        return false;

    // erase the previous outline data and vertex order
    // but preserve the extra vertices
unknown's avatar
unknown committed
859
    while( !outline.empty() )
860 861 862 863 864
    {
        delete outline.back();
        outline.pop_back();
    }

unknown's avatar
unknown committed
865 866
    ordmap.clear();
    ord = 0;
867 868 869 870 871 872 873 874 875 876 877 878

    // go through the vertex lists and reset ephemeral parameters
    for( unsigned int i = 0; i < vertices.size(); ++i )
    {
        vertices[i]->o = -1;
    }

    for( unsigned int i = 0; i < extra_verts.size(); ++i )
    {
        extra_verts[i]->o = -1;
    }

unknown's avatar
unknown committed
879 880
    // close the polygon; this creates the outline points
    // and the point ordering list 'ordmap'
881
    solid.clear();
882 883
    gluTessEndPolygon( tess );

unknown's avatar
unknown committed
884 885
    // repeat the last operation but request a tesselated surface
    // rather than an outline; this creates the triangles list.
886 887
    gluTessProperty( tess, GLU_TESS_BOUNDARY_ONLY, GL_FALSE );

unknown's avatar
unknown committed
888 889
    gluTessBeginPolygon( tess, this );

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    if( !pushOutline( holes ) )
        return false;

    gluTessEndPolygon( tess );

    if( Fault )
        return false;

    return true;
}


bool VRML_LAYER::pushOutline( VRML_LAYER* holes )
{
    // traverse the outline list to push all used vertices
    if( outline.size() < 1 )
    {
        error = "pushOutline() failed: no vertices to push";
        return false;
    }

    std::list<std::list<int>*>::const_iterator obeg = outline.begin();
    std::list<std::list<int>*>::const_iterator oend = outline.end();

914 915
    int nc = 0; // number of contours pushed

916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
    int pi;
    std::list<int>::const_iterator  begin;
    std::list<int>::const_iterator  end;
    GLdouble pt[3];
    VERTEX_3D* vp;

    while( obeg != oend )
    {
        if( (*obeg)->size() < 3 )
        {
            ++obeg;
            continue;
        }

        gluTessBeginContour( tess );

        begin = (*obeg)->begin();
        end = (*obeg)->end();

        while( begin != end )
        {
            pi = *begin;

            if( pi < 0 || (unsigned int) pi > ordmap.size() )
            {
unknown's avatar
unknown committed
941
                gluTessEndContour( tess );
942 943 944 945 946 947 948 949 950 951 952
                error = "pushOutline():BUG: *outline.begin() is not a valid index to ordmap";
                return false;
            }

            // retrieve the actual index
            pi = ordmap[pi];

            vp = getVertexByIndex( pi, holes );

            if( !vp )
            {
unknown's avatar
unknown committed
953
                gluTessEndContour( tess );
954 955 956 957 958 959 960 961 962 963 964 965 966
                error = "pushOutline():: BUG: ordmap[n] is not a valid index to vertices[]";
                return false;
            }

            pt[0]   = vp->x;
            pt[1]   = vp->y;
            pt[2]   = 0.0;
            gluTessVertex( tess, pt, vp );
            ++begin;
        }

        gluTessEndContour( tess );
        ++obeg;
967 968 969 970 971 972 973
        ++nc;
    }

    if( !nc )
    {
        error = "pushOutline():: no valid contours available";
        return false;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
    }

    return true;
}


// writes out the vertex list for a planar feature
bool VRML_LAYER::WriteVertices( double aZcoord, std::ofstream& aOutFile, int aPrecision )
{
    if( ordmap.size() < 3 )
    {
        error = "WriteVertices(): not enough vertices";
        return false;
    }

    if( aPrecision < 4 )
        aPrecision = 4;

    int i, j;

    VERTEX_3D* vp = getVertexByIndex( ordmap[0], pholes );

    if( !vp )
        return false;

    std::string strx, stry, strz;
1000
    FormatDoublet( vp->x + offsetX, vp->y + offsetY, aPrecision, strx, stry );
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    FormatSinglet( aZcoord, aPrecision, strz );

    aOutFile << strx << " " << stry << " " << strz;

    for( i = 1, j = ordmap.size(); i < j; ++i )
    {
        vp = getVertexByIndex( ordmap[i], pholes );

        if( !vp )
            return false;

1012
        FormatDoublet( vp->x + offsetX, vp->y + offsetY, aPrecision, strx, stry );
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

        if( i & 1 )
            aOutFile << ", " << strx << " " << stry << " " << strz;
        else
            aOutFile << ",\n" << strx << " " << stry << " " << strz;
    }

    return !aOutFile.fail();
}


// writes out the vertex list for a 3D feature; top and bottom are the
// Z values for the top and bottom; top must be > bottom
bool VRML_LAYER::Write3DVertices( double aTopZ, double aBottomZ,
                                  std::ofstream& aOutFile, int aPrecision )
{
    if( ordmap.size() < 3 )
    {
        error = "Write3DVertices(): insufficient vertices";
        return false;
    }

    if( aPrecision < 4 )
        aPrecision = 4;

    if( aTopZ <= aBottomZ )
    {
        error = "Write3DVertices(): top <= bottom";
        return false;
    }

    int i, j;

    VERTEX_3D* vp = getVertexByIndex( ordmap[0], pholes );

    if( !vp )
        return false;

    std::string strx, stry, strz;
1052
    FormatDoublet( vp->x + offsetX, vp->y + offsetY, aPrecision, strx, stry );
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    FormatSinglet( aTopZ, aPrecision, strz );

    aOutFile << strx << " " << stry << " " << strz;

    for( i = 1, j = ordmap.size(); i < j; ++i )
    {
        vp = getVertexByIndex( ordmap[i], pholes );

        if( !vp )
            return false;

1064
        FormatDoublet( vp->x + offsetX, vp->y + offsetY, aPrecision, strx, stry );
1065 1066 1067 1068 1069 1070 1071 1072 1073

        if( i & 1 )
            aOutFile << ", " << strx << " " << stry << " " << strz;
        else
            aOutFile << ",\n" << strx << " " << stry << " " << strz;
    }

    // repeat for the bottom layer
    vp = getVertexByIndex( ordmap[0], pholes );
1074
    FormatDoublet( vp->x + offsetX, vp->y + offsetY, aPrecision, strx, stry );
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    FormatSinglet( aBottomZ, aPrecision, strz );

    bool endl;

    if( i & 1 )
    {
        aOutFile << ", " << strx << " " << stry << " " << strz;
        endl = false;
    }
    else
    {
        aOutFile << ",\n" << strx << " " << stry << " " << strz;
        endl = true;
    }

    for( i = 1, j = ordmap.size(); i < j; ++i )
    {
        vp = getVertexByIndex( ordmap[i], pholes );
1093
        FormatDoublet( vp->x + offsetX, vp->y + offsetY, aPrecision, strx, stry );
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

        if( endl )
        {
            aOutFile << ", " << strx << " " << stry << " " << strz;
            endl = false;
        }
        else
        {
            aOutFile << ",\n" << strx << " " << stry << " " << strz;
            endl = true;
        }
    }

    return !aOutFile.fail();
}


// writes out the index list;
// 'top' indicates the vertex ordering and should be
// true for a polygon visible from above the PCB
bool VRML_LAYER::WriteIndices( bool aTopFlag, std::ofstream& aOutFile )
{
    if( triplets.empty() )
    {
        error = "WriteIndices(): no triplets (triangular facets) to write";
        return false;
    }

    // go through the triplet list and write out the indices based on order
    std::list<TRIPLET_3D>::const_iterator   tbeg    = triplets.begin();
    std::list<TRIPLET_3D>::const_iterator   tend    = triplets.end();

    int i = 1;

    if( aTopFlag )
        aOutFile << tbeg->i1 << ", " << tbeg->i2 << ", " << tbeg->i3  << ", -1";
    else
        aOutFile << tbeg->i2 << ", " << tbeg->i1 << ", " << tbeg->i3  << ", -1";

    ++tbeg;

    while( tbeg != tend )
    {
        if( (i++ & 7) == 4 )
        {
            i = 1;

            if( aTopFlag )
                aOutFile << ",\n" << tbeg->i1 << ", " << tbeg->i2 << ", " << tbeg->i3  << ", -1";
            else
                aOutFile << ",\n" << tbeg->i2 << ", " << tbeg->i1 << ", " << tbeg->i3  << ", -1";
        }
        else
        {
            if( aTopFlag )
                aOutFile << ", " << tbeg->i1 << ", " << tbeg->i2 << ", " << tbeg->i3  << ", -1";
            else
                aOutFile << ", " << tbeg->i2 << ", " << tbeg->i1 << ", " << tbeg->i3  << ", -1";
        }

        ++tbeg;
    }

    return !aOutFile.fail();
}


// writes out the index list for a 3D feature
1162
bool VRML_LAYER::Write3DIndices( std::ofstream& aOutFile, bool aIncludePlatedHoles )
1163 1164 1165 1166 1167 1168 1169
{
    if( outline.empty() )
    {
        error = "WriteIndices(): no outline available";
        return false;
    }

1170 1171
    char mark;
    bool holes_only = triplets.empty();
1172 1173 1174 1175

    int i = 1;
    int idx2 = ordmap.size();    // index to the bottom vertices

1176
    if( !holes_only )
1177
    {
1178
        mark = ',';
1179

1180 1181 1182
        // go through the triplet list and write out the indices based on order
        std::list<TRIPLET_3D>::const_iterator   tbeg    = triplets.begin();
        std::list<TRIPLET_3D>::const_iterator   tend    = triplets.end();
1183

1184 1185 1186
        // print out the top vertices
        aOutFile << tbeg->i1 << ", " << tbeg->i2 << ", " << tbeg->i3  << ", -1";
        ++tbeg;
1187

1188
        while( tbeg != tend )
1189
        {
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
            if( (i++ & 7) == 4 )
            {
                i = 1;
                aOutFile << ",\n" << tbeg->i1 << ", " << tbeg->i2 << ", " << tbeg->i3  << ", -1";
            }
            else
            {
                aOutFile << ", " << tbeg->i1 << ", " << tbeg->i2 << ", " << tbeg->i3  << ", -1";
            }

            ++tbeg;
1201
        }
1202 1203 1204 1205 1206

        // print out the bottom vertices
        tbeg = triplets.begin();

        while( tbeg != tend )
1207
        {
1208 1209 1210 1211 1212 1213 1214 1215 1216
            if( (i++ & 7) == 4 )
            {
                i = 1;
                aOutFile << ",\n" << (tbeg->i2 + idx2) << ", " << (tbeg->i1 + idx2) << ", " << (tbeg->i3  + idx2) << ", -1";
            }
            else
            {
                aOutFile << ", " << (tbeg->i2 + idx2) << ", " << (tbeg->i1 + idx2) << ", " << (tbeg->i3  + idx2) << ", -1";
            }
1217

1218 1219
            ++tbeg;
        }
1220
    }
1221 1222 1223
    else
        mark = ' ';

1224 1225 1226 1227

    // print out indices for the walls joining top to bottom
    int lastPoint;
    int curPoint;
1228
    int curContour = 0;
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

    std::list<std::list<int>*>::const_iterator  obeg    = outline.begin();
    std::list<std::list<int>*>::const_iterator  oend    = outline.end();
    std::list<int>* cp;
    std::list<int>::const_iterator  cbeg;
    std::list<int>::const_iterator  cend;

    i = 2;
    while( obeg != oend )
    {
        cp = *obeg;

        if( cp->size() < 3 )
        {
            ++obeg;
1244
            ++curContour;
1245 1246 1247
            continue;
        }

1248 1249 1250
        cbeg      = cp->begin();
        cend      = cp->end();
        lastPoint = *(cbeg++);
1251

1252 1253 1254 1255 1256 1257 1258 1259
        // skip all PTH vertices which are not in a solid outline
        if( !aIncludePlatedHoles && !solid[curContour]
            && getVertexByIndex( ordmap[lastPoint], pholes )->pth )
        {
            ++obeg;
            ++curContour;
            continue;
        }
1260 1261 1262 1263 1264

        while( cbeg != cend )
        {
            curPoint = *(cbeg++);

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
            if( !holes_only )
            {
                if( (i++ & 3) == 2 )
                {
                    i = 1;
                    aOutFile << mark << "\n" << curPoint << ", " << lastPoint << ", " << curPoint + idx2;
                    aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint << ", " << lastPoint + idx2 << ", -1";
                }
                else
                {
                    aOutFile << mark << " " << curPoint << ", " << lastPoint << ", " << curPoint + idx2;
                    aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint << ", " << lastPoint + idx2 << ", -1";
                }
            }
            else
            {
                if( (i++ & 3) == 2 )
                {
                    i = 1;
                    aOutFile << mark << "\n" << curPoint << ", " << curPoint + idx2 << ", " << lastPoint;
                    aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint + idx2 << ", " << lastPoint << ", -1";
                }
                else
                {
                    aOutFile << mark << " " << curPoint << ", " << curPoint + idx2 << ", " << lastPoint;
                    aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint + idx2 << ", " << lastPoint << ", -1";
                }
            }

            mark = ',';
            lastPoint = curPoint;
        }

        // check if the loop needs to be closed
        cbeg = cp->begin();
        cend = --cp->end();

        curPoint = *(cbeg);
        lastPoint  = *(cend);

        if( !holes_only )
        {
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
            if( (i++ & 3) == 2 )
            {
                aOutFile << ",\n" << curPoint << ", " << lastPoint << ", " << curPoint + idx2;
                aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint << ", " << lastPoint + idx2 << ", -1";
            }
            else
            {
                aOutFile << ", " << curPoint << ", " << lastPoint << ", " << curPoint + idx2;
                aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint << ", " << lastPoint + idx2 << ", -1";
            }
        }
        else
        {
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
            if( (i++ & 3) == 2 )
            {
                aOutFile << ",\n" << curPoint << ", " << curPoint + idx2 << ", " << lastPoint;
                aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint + idx2 << ", " << lastPoint << ", -1";
            }
            else
            {
                aOutFile << ", " << curPoint << ", " << curPoint + idx2 << ", " << lastPoint;
                aOutFile << ", -1, " << curPoint + idx2 << ", " << lastPoint + idx2 << ", " << lastPoint << ", -1";
            }
1330 1331 1332
        }

        ++obeg;
1333
        ++curContour;
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
    }

    return !aOutFile.fail();
}


// add a triangular facet (triplet) to the ouptut index list
bool VRML_LAYER::addTriplet( VERTEX_3D* p0, VERTEX_3D* p1, VERTEX_3D* p2 )
{
    double  dx0 = p1->x - p0->x;
    double  dx1 = p2->x - p0->x;

    double  dy0 = p1->y - p0->y;
    double  dy1 = p2->y - p0->y;

unknown's avatar
unknown committed
1349 1350 1351
    // this number is chosen because we shall only write 9 decimal places
    // at most on the VRML output
    double err = 0.000000001;
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

    // test if the triangles are degenerate (parallel sides)

    if( dx0 < err && dx0 > -err && dx1 < err && dx1 > -err )
        return false;

    if( dy0 < err && dy0 > -err && dy1 < err && dy1 > -err )
        return false;

    double  sl0 = dy0 / dx0;
    double  sl1 = dy1 / dx1;

    double dsl = sl1 - sl0;

    if( dsl < err && dsl > -err )
        return false;

    triplets.push_back( TRIPLET_3D( p0->o, p1->o, p2->o ) );

    return true;
}


// add an extra vertex (to be called only by the COMBINE callback)
1376
VERTEX_3D* VRML_LAYER::AddExtraVertex( double aXpos, double aYpos, bool aPlatedHole )
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
{
    VERTEX_3D* vertex = new VERTEX_3D;

    if( !vertex )
    {
        error = "AddExtraVertex(): could not allocate a new vertex";
        return NULL;
    }

    if( eidx == 0 )
        eidx = idx + hidx;

    vertex->x   = aXpos;
    vertex->y   = aYpos;
    vertex->i   = eidx++;
    vertex->o   = -1;
1393
    vertex->pth = aPlatedHole;
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

    extra_verts.push_back( vertex );

    return vertex;
}


// start a GL command list
void VRML_LAYER::glStart( GLenum cmd )
{
    glcmd = cmd;

    while( !vlist.empty() )
        vlist.pop_back();
}


// process a vertex
void VRML_LAYER::glPushVertex( VERTEX_3D* vertex )
{
    if( vertex->o < 0 )
    {
        vertex->o = ord++;
        ordmap.push_back( vertex->i );
    }

    vlist.push_back( vertex );
}


// end a GL command list
void VRML_LAYER::glEnd( void )
{
    switch( glcmd )
    {
    case GL_LINE_LOOP:
        {
            // add the loop to the list of outlines
            std::list<int>* loop = new std::list<int>;

            if( !loop )
                break;

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
            double firstX = 0.0;
            double firstY = 0.0;
            double lastX, lastY;
            double curX, curY;
            double area = 0.0;

            if( vlist.size() > 0 )
            {
                loop->push_back( vlist[0]->o );
                firstX = vlist[0]->x;
                firstY = vlist[0]->y;
                lastX = firstX;
                lastY = firstY;
            }

            for( size_t i = 1; i < vlist.size(); ++i )
1453 1454
            {
                loop->push_back( vlist[i]->o );
1455 1456 1457 1458 1459
                curX = vlist[i]->x;
                curY = vlist[i]->y;
                area += ( curX - lastX ) * ( curY + lastY );
                lastX = curX;
                lastY = curY;
1460 1461
            }

1462 1463
            area += ( firstX - lastX ) * ( firstY + lastY );

1464
            outline.push_back( loop );
1465 1466 1467 1468 1469

            if( area <= 0.0 )
                solid.push_back( true );
            else
                solid.push_back( false );
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
        }
        break;

    case GL_TRIANGLE_FAN:
        processFan();
        break;

    case GL_TRIANGLE_STRIP:
        processStrip();
        break;

    case GL_TRIANGLES:
        processTri();
        break;

    default:
        break;
    }

    while( !vlist.empty() )
        vlist.pop_back();

    glcmd = 0;
}


// set the error message
void VRML_LAYER::SetGLError( GLenum errorID )
{
    error = "";
    error = (const char*)gluGetString( errorID );

    if( error.empty() )
    {
        std::ostringstream ostr;
        ostr << "Unknown OpenGL error: " << errorID;
        error = ostr.str();
    }
}


// process a GL_TRIANGLE_FAN list
void VRML_LAYER::processFan( void )
{
    if( vlist.size() < 3 )
        return;

    VERTEX_3D* p0 = vlist[0];

    int i;
    int end = vlist.size();

    for( i = 2; i < end; ++i )
    {
        addTriplet( p0, vlist[i - 1], vlist[i] );
    }
}


// process a GL_TRIANGLE_STRIP list
void VRML_LAYER::processStrip( void )
{
    // note: (source: http://www.opengl.org/wiki/Primitive)
    // GL_TRIANGLE_STRIP​: Every group of 3 adjacent vertices forms a triangle.
    // The face direction of the strip is determined by the winding of the
    // first triangle. Each successive triangle will have its effective face
    // order reverse, so the system compensates for that by testing it in the
    // opposite way. A vertex stream of n length will generate n-2 triangles.

    if( vlist.size() < 3 )
        return;

    int i;
    int end = vlist.size();
    bool flip = false;

    for( i = 2; i < end; ++i )
    {
        if( flip )
        {
            addTriplet( vlist[i - 1], vlist[i - 2], vlist[i] );
            flip = false;
        }
        else
        {
            addTriplet( vlist[i - 2], vlist[i - 1], vlist[i] );
            flip = true;
        }
    }
}


// process a GL_TRIANGLES list
void VRML_LAYER::processTri( void )
{
    // notes:
    // 1. each successive group of 3 vertices is a triangle
    // 2. as per OpenGL specification, any incomplete triangles are to be ignored

    if( vlist.size() < 3 )
        return;

    int i;
    int end = vlist.size();

    for( i = 2; i < end; i += 3 )
        addTriplet( vlist[i - 2], vlist[i - 1], vlist[i] );
}


1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
int VRML_LAYER::checkNContours( bool holes )
{
    int nc = 0;     // number of contours

    if( contours.empty() )
        return 0;

    std::list<int>::const_iterator  begin;
    std::list<int>::const_iterator  end;

    for( size_t i = 0; i < contours.size(); ++i )
    {
        if( contours[i]->size() < 3 )
            continue;

        if( ( holes && areas[i] <= 0.0 ) || ( !holes && areas[i] > 0.0 ) )
            continue;

        ++nc;
    }

    return nc;
}


1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
// push the internally held vertices
void VRML_LAYER::pushVertices( bool holes )
{
    // push the internally held vertices
    unsigned int i;

    std::list<int>::const_iterator  begin;
    std::list<int>::const_iterator  end;
    GLdouble pt[3];
    VERTEX_3D* vp;

    for( i = 0; i < contours.size(); ++i )
    {
        if( contours[i]->size() < 3 )
            continue;

        if( ( holes && areas[i] <= 0.0 ) || ( !holes && areas[i] > 0.0 ) )
            continue;

        gluTessBeginContour( tess );

        begin = contours[i]->begin();
        end = contours[i]->end();

        while( begin != end )
        {
            vp = vertices[ *begin ];
            pt[0]   = vp->x;
            pt[1]   = vp->y;
            pt[2]   = 0.0;
            gluTessVertex( tess, pt, vp );
            ++begin;
        }

        gluTessEndContour( tess );
    }
1641 1642

    return;
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
}


VERTEX_3D* VRML_LAYER::getVertexByIndex( int aPointIndex, VRML_LAYER* holes )
{
    if( aPointIndex < 0 || (unsigned int) aPointIndex >= ( idx + hidx + extra_verts.size() ) )
    {
        error = "getVertexByIndex():BUG: invalid index";
        return NULL;
    }

    if( aPointIndex < idx )
    {
        // vertex is in the vertices[] list
        return vertices[ aPointIndex ];
    }
    else if( aPointIndex >= idx + hidx )
    {
        // vertex is in the extra_verts[] list
        return extra_verts[aPointIndex - idx - hidx];
    }

    // vertex is in the holes object
    if( !holes )
    {
        error = "getVertexByIndex():BUG: invalid index";
        return NULL;
    }

    VERTEX_3D* vp = holes->GetVertexByIndex( aPointIndex );

    if( !vp )
    {
        std::ostringstream ostr;
        ostr << "getVertexByIndex():FAILED: " << holes->GetError();
        error = ostr.str();
        return NULL;
    }

    return vp;
}


// retrieve the total number of vertices
int VRML_LAYER::GetSize( void )
{
    return vertices.size();
}


// Inserts all contours into the given tesselator; this results in the
// renumbering of all vertices from 'start'. Returns the end number.
// Take care when using this call since tesselators cannot work on
// the internal data concurrently
int VRML_LAYER::Import( int start, GLUtesselator* tess )
{
    if( start < 0 )
    {
        error = "Import(): invalid index ( start < 0 )";
        return -1;
    }

    if( !tess )
    {
        error = "Import(): NULL tesselator pointer";
        return -1;
    }

    unsigned int i, j;

    // renumber from 'start'
    for( i = 0, j = vertices.size(); i < j; ++i )
    {
        vertices[i]->i = start++;
        vertices[i]->o = -1;
    }

    // push each contour to the tesselator
    VERTEX_3D* vp;
    GLdouble pt[3];

    std::list<int>::const_iterator cbeg;
    std::list<int>::const_iterator cend;

    for( i = 0; i < contours.size(); ++i )
    {
        if( contours[i]->size() < 3 )
            continue;

        cbeg = contours[i]->begin();
        cend = contours[i]->end();

        gluTessBeginContour( tess );

        while( cbeg != cend )
        {
            vp = vertices[ *cbeg++ ];
            pt[0] = vp->x;
            pt[1] = vp->y;
            pt[2] = 0.0;
            gluTessVertex( tess, pt, vp );
        }

        gluTessEndContour( tess );
    }

    return start;
}


// return the vertex identified by index
VERTEX_3D* VRML_LAYER::GetVertexByIndex( int aPointIndex )
{
    int i0 = vertices[0]->i;

    if( aPointIndex < i0 || aPointIndex >= ( i0 + (int) vertices.size() ) )
    {
        error = "GetVertexByIndex(): invalid index";
        return NULL;
    }

    return vertices[aPointIndex - i0];
}


// return the error string
const std::string& VRML_LAYER::GetError( void )
{
    return error;
}
1773 1774 1775 1776 1777 1778 1779 1780


void VRML_LAYER::SetVertexOffsets( double aXoffset, double aYoffset )
{
    offsetX = aXoffset;
    offsetY = aYoffset;
    return;
}