export_vrml.cpp 41.7 KB
Newer Older
1 2 3 4
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2009-2013  Lorenzo Mercantonio
5
 * Copyright (C) 2014  Cirilo Bernado
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * Copyright (C) 2013 Jean-Pierre Charras jp.charras at wanadoo.fr
 * Copyright (C) 2004-2013 KiCad Developers, see change_log.txt for contributors.
 *
 * 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 34 35 36 37 38 39 40 41 42 43 44 45 46

/*
 * NOTE:
 * 1. for improved looks, create a DRILL layer for PTH drills.
 *      To render the improved board, render the vertical outline only
 *      for the board (no added drill holes), then render the
 *      outline only for PTH, and finally render the top and bottom
 *      of the board. NOTE: if we don't want extra eye-candy then
 *      we must maintain the current board export.
 *      Additional bits needed for improved eyecandy:
 *      + CalcOutline: calculates only the outline of a VRML_LAYER or
 *          a VERTICAL_HOLES
 *      + WriteVerticalIndices: writes the indices of only the vertical
 *          facets of a VRML_LAYER or a VRML_HOLES.
 *      + WriteVerticalVertices: writes only the outline vertices to
 *          form vertical walls; applies to VRML_LAYER and VRML_HOLES
 *
 * 2. How can we suppress fiducials such as those in the corners of the pic-programmer demo?
 *
 * 3. Export Graphics to Layer objects (see 3d_draw.cpp for clues) to ensure that custom
 *      tracks/fills/logos are rendered.
47
 *  module->TransformGraphicShapesWithClearanceToPolygonSet
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
 *
 * For mechanical correctness, we should use the following settings with arcs:
 * 1. max. deviation:  the number of edges should be determined by the max.
 *      mechanical deviation and the minimum number of edges shall be 6.
 * 2. for very large features we may introduce too many edges in a circle;
 *      to control this, we should specify a MAX number of edges or a threshold
 *      radius and a deviation for larger features
 *
 * For example, many mechanical fits are to within +/-0.05mm, so specifying
 *      a max. deviation of 0.02mm will yield a hole near the max. material
 *      condition. Calculating sides for a 10mm radius hole will yield about
 *      312 points; such large holes (and arcs) will typically have a specified
 *      tolerance of +/-0.2mm in which case we can set the MAX edges to 32
 *      provided none of the important holes requires > 32 edges.
 *
 */

65 66 67 68 69
#include <fctsys.h>
#include <kicad_string.h>
#include <wxPcbStruct.h>
#include <drawtxt.h>
#include <trigo.h>
70
#include <pgm_base.h>
71 72 73 74 75 76 77 78
#include <3d_struct.h>
#include <macros.h>

#include <pcbnew.h>

#include <class_board.h>
#include <class_module.h>
#include <class_track.h>
79
#include <class_zone.h>
80 81
#include <class_edge_mod.h>
#include <class_pcb_text.h>
82
#include <convert_from_iu.h>
83

84 85
#include "../3d-viewer/modelparsers.h"

86 87
#include <vector>
#include <cmath>
88
#include <vrml_board.h>
89

90 91 92 93
/* helper function:
 * some characters cannot be used in names,
 * this function change them to "_"
 */
94
static void ChangeIllegalCharacters( wxString& aFileName, bool aDirSepIsIllegal );
95

96
struct VRML_COLOR
97
{
98 99 100
    float diffuse_red;
    float diffuse_grn;
    float diffuse_blu;
101

102 103 104
    float spec_red;
    float spec_grn;
    float spec_blu;
105

106 107 108
    float emit_red;
    float emit_grn;
    float emit_blu;
109

110 111 112
    float ambient;
    float transp;
    float shiny;
113

114
    VRML_COLOR()
115
    {
116 117 118 119 120 121 122 123 124 125 126 127 128 129
        // default green
        diffuse_red = 0.13;
        diffuse_grn = 0.81;
        diffuse_blu = 0.22;
        spec_red = 0.13;
        spec_grn = 0.81;
        spec_blu = 0.22;
        emit_red = 0.0;
        emit_grn = 0.0;
        emit_blu = 0.0;

        ambient = 1.0;
        transp  = 0;
        shiny   = 0.2;
130 131
    }

132 133 134 135
    VRML_COLOR( float dr, float dg, float db,
                float sr, float sg, float sb,
                float er, float eg, float eb,
                float am, float tr, float sh )
136
    {
137 138 139 140 141 142 143 144 145 146 147 148 149
        diffuse_red = dr;
        diffuse_grn = dg;
        diffuse_blu = db;
        spec_red = sr;
        spec_grn = sg;
        spec_blu = sb;
        emit_red = er;
        emit_grn = eg;
        emit_blu = eb;

        ambient = am;
        transp  = tr;
        shiny   = sh;
150 151 152
    }
};

153
enum VRML_COLOR_INDEX
154
{
155 156 157 158 159
    VRML_COLOR_PCB = 0,
    VRML_COLOR_TRACK,
    VRML_COLOR_SILK,
    VRML_COLOR_TIN,
    VRML_COLOR_LAST
160 161 162
};


163
class MODEL_VRML
164
{
165
private:
166

167 168
    double layer_z[NB_LAYERS];
    VRML_COLOR colors[VRML_COLOR_LAST];
169

170
public:
171

172 173 174 175 176 177 178 179
    VRML_LAYER  holes;
    VRML_LAYER  board;
    VRML_LAYER  top_copper;
    VRML_LAYER  bot_copper;
    VRML_LAYER  top_silk;
    VRML_LAYER  bot_silk;
    VRML_LAYER  top_tin;
    VRML_LAYER  bot_tin;
180

181
    double scale;           // board internal units to output scaling
182

183 184
    double  tx;             // global translation along X
    double  ty;             // global translation along Y
185

186
    double board_thickness; // depth of the PCB
187

188 189
    LAYER_NUM s_text_layer;
    int s_text_width;
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    MODEL_VRML()
    {
        for( int i = 0; i < NB_LAYERS; ++i )
            layer_z[i] = 0;

        // this default only makes sense if the output is in mm
        board_thickness = 1.6;

        // pcb green
        colors[ VRML_COLOR_PCB ]    = VRML_COLOR( .07, .3, .12, .07, .3, .12,
                                                  0, 0, 0, 1, 0, 0.2 );
        // track green
        colors[ VRML_COLOR_TRACK ]  = VRML_COLOR( .08, .5, .1, .08, .5, .1,
                                                  0, 0, 0, 1, 0, 0.2 );
        // silkscreen white
        colors[ VRML_COLOR_SILK ]   = VRML_COLOR( .9, .9, .9, .9, .9, .9,
                                                  0, 0, 0, 1, 0, 0.2 );
        // pad silver
        colors[ VRML_COLOR_TIN ] = VRML_COLOR( .749, .756, .761, .749, .756, .761,
                                                  0, 0, 0, 0.8, 0, 0.8 );
    }
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    VRML_COLOR& GetColor( VRML_COLOR_INDEX aIndex )
    {
        return colors[aIndex];
    }

    void SetOffset( double aXoff, double aYoff )
    {
        tx  = aXoff;
        ty  = aYoff;
    }

    double GetLayerZ( LAYER_NUM aLayer )
    {
        if( aLayer >= NB_LAYERS )
            return 0;

        return layer_z[ aLayer ];
    }
231

232 233 234 235
    void SetLayerZ( LAYER_NUM aLayer, double aValue )
    {
        layer_z[aLayer] = aValue;
    }
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    void SetMaxDev( double dev )
    {
        holes.SetMaxDev( dev );
        board.SetMaxDev( dev );
        top_copper.SetMaxDev( dev );
        bot_copper.SetMaxDev( dev );
        top_silk.SetMaxDev( dev );
        bot_silk.SetMaxDev( dev );
        top_tin.SetMaxDev( dev );
        bot_tin.SetMaxDev( dev );
    }
};


// static var. for dealing with text
namespace VRMLEXPORT
253
{
254 255
    static MODEL_VRML* model_vrml;
    bool GetLayer( MODEL_VRML& aModel, LAYER_NUM layer, VRML_LAYER** vlayer );
256 257 258
}


259 260 261
// select the VRML layer object to draw on; return true if
// a layer has been selected.
bool VRMLEXPORT::GetLayer( MODEL_VRML& aModel, LAYER_NUM layer, VRML_LAYER** vlayer )
262
{
263 264 265 266 267 268 269 270 271
    switch( layer )
    {
    case FIRST_COPPER_LAYER:
        *vlayer = &aModel.bot_copper;
        break;

    case LAST_COPPER_LAYER:
        *vlayer = &aModel.top_copper;
        break;
272

273 274 275 276 277 278 279 280 281 282 283
    case SILKSCREEN_N_BACK:
        *vlayer = &aModel.bot_silk;
        break;

    case SILKSCREEN_N_FRONT:
        *vlayer = &aModel.top_silk;
        break;

    default:
        return false;
    }
284

285
    return true;
286 287 288
}


289 290 291
static void write_triangle_bag( FILE* output_file, VRML_COLOR& color,
        VRML_LAYER* layer, bool plane, bool top,
        double top_z, double bottom_z )
292 293 294 295 296 297 298 299 300 301 302 303
{
    /* A lot of nodes are not required, but blender sometimes chokes
     * without them */
    static const char* shape_boiler[] =
    {
        "Transform {\n",
        "  children [\n",
        "    Group {\n",
        "      children [\n",
        "        Shape {\n",
        "          appearance Appearance {\n",
        "            material Material {\n",
304
        0,                                      // Material marker
305 306 307
        "            }\n",
        "          }\n",
        "          geometry IndexedFaceSet {\n",
308
        "            solid TRUE\n",
309 310
        "            coord Coordinate {\n",
        "              point [\n",
311
        0,                                      // Coordinates marker
312 313 314
        "              ]\n",
        "            }\n",
        "            coordIndex [\n",
315
        0,                                      // Index marker
316 317 318 319 320 321 322
        "            ]\n",
        "          }\n",
        "        }\n",
        "      ]\n",
        "    }\n",
        "  ]\n",
        "}\n",
323
        0    // End marker
324
    };
325

326 327 328 329 330 331 332 333 334
    int marker_found = 0, lineno = 0;

    while( marker_found < 4 )
    {
        if( shape_boiler[lineno] )
            fputs( shape_boiler[lineno], output_file );
        else
        {
            marker_found++;
335

336 337
            switch( marker_found )
            {
338 339 340 341 342 343 344 345 346 347 348
            case 1:    // Material marker
                fprintf( output_file,
                        "              diffuseColor %g %g %g\n",
                         color.diffuse_red,
                         color.diffuse_grn,
                         color.diffuse_blu );
                fprintf( output_file,
                        "              specularColor %g %g %g\n",
                         color.spec_red,
                         color.spec_grn,
                         color.spec_blu );
349
                fprintf( output_file,
350 351 352 353
                        "              emissiveColor %g %g %g\n",
                         color.emit_red,
                         color.emit_grn,
                         color.emit_blu );
354
                fprintf( output_file,
355
                         "              ambientIntensity %g\n", color.ambient );
356
                fprintf( output_file,
357 358 359
                         "              transparency %g\n", color.transp );
                fprintf( output_file,
                         "              shininess %g\n", color.shiny );
360 361 362
                break;

            case 2:
363 364 365 366 367 368 369 370

                if( plane )
                    layer->WriteVertices( top_z, output_file );
                else
                    layer->Write3DVertices( top_z, bottom_z, output_file );

                fprintf( output_file, "\n" );
                break;
371 372

            case 3:
373 374 375 376 377 378 379 380

                if( plane )
                    layer->WriteIndices( top, output_file );
                else
                    layer->Write3DIndices( output_file );

                fprintf( output_file, "\n" );
                break;
381 382 383 384 385

            default:
                break;
            }
        }
386

387 388 389 390 391
        lineno++;
    }
}


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
static void write_layers( MODEL_VRML& aModel, FILE* output_file, BOARD* aPcb )
{
    // VRML_LAYER board;
    aModel.board.Tesselate( &aModel.holes );
    double brdz = aModel.board_thickness / 2.0 - 40000 * aModel.scale;
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_PCB ),
            &aModel.board, false, false, brdz, -brdz );

    // VRML_LAYER top_copper;
    aModel.top_copper.Tesselate( &aModel.holes );
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_TRACK ),
            &aModel.top_copper, true, true,
            aModel.GetLayerZ( LAST_COPPER_LAYER ), 0 );

    // VRML_LAYER top_tin;
    aModel.top_tin.Tesselate( &aModel.holes );
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_TIN ),
                        &aModel.top_tin, true, true,
                        aModel.GetLayerZ( LAST_COPPER_LAYER ), 0 );

    // VRML_LAYER bot_copper;
    aModel.bot_copper.Tesselate( &aModel.holes );
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_TRACK ),
            &aModel.bot_copper, true, false,
            aModel.GetLayerZ( FIRST_COPPER_LAYER ), 0 );

    // VRML_LAYER bot_tin;
    aModel.bot_tin.Tesselate( &aModel.holes );
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_TIN ),
                        &aModel.bot_tin, true, false,
                        aModel.GetLayerZ( FIRST_COPPER_LAYER ), 0 );

    // VRML_LAYER top_silk;
    aModel.top_silk.Tesselate( &aModel.holes );
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_SILK ),
            &aModel.top_silk, true, true,
            aModel.GetLayerZ( SILKSCREEN_N_FRONT ), 0 );

    // VRML_LAYER bot_silk;
    aModel.bot_silk.Tesselate( &aModel.holes );
    write_triangle_bag( output_file, aModel.GetColor( VRML_COLOR_SILK ),
            &aModel.bot_silk, true, false,
            aModel.GetLayerZ( SILKSCREEN_N_BACK ), 0 );
}


static void compute_layer_Zs( MODEL_VRML& aModel, BOARD* pcb )
439
{
440
    int copper_layers = pcb->GetCopperLayerCount();
441 442

    // We call it 'layer' thickness, but it's the whole board thickness!
443 444
    aModel.board_thickness = pcb->GetDesignSettings().GetBoardThickness() * aModel.scale;
    double half_thickness = aModel.board_thickness / 2;
445

Dick Hollenbeck's avatar
Dick Hollenbeck committed
446
    // Compute each layer's Z value, more or less like the 3d view
447
    for( LAYER_NUM i = FIRST_LAYER; i <= LAYER_N_FRONT; ++i )
448 449
    {
        if( i < copper_layers )
450
            aModel.SetLayerZ( i, aModel.board_thickness * i / (copper_layers - 1) - half_thickness );
451
        else
452
            aModel.SetLayerZ( i, half_thickness );  // component layer
453 454 455 456
    }

    /* To avoid rounding interference, we apply an epsilon to each
     * successive layer */
457 458 459 460 461 462 463 464 465 466 467 468 469 470
    double epsilon_z = Millimeter2iu( 0.02 ) * aModel.scale;
    aModel.SetLayerZ( SOLDERPASTE_N_BACK, -half_thickness - epsilon_z * 4 );
    aModel.SetLayerZ( ADHESIVE_N_BACK, -half_thickness - epsilon_z * 3 );
    aModel.SetLayerZ( SILKSCREEN_N_BACK, -half_thickness - epsilon_z * 2 );
    aModel.SetLayerZ( SOLDERMASK_N_BACK, -half_thickness - epsilon_z );
    aModel.SetLayerZ( SOLDERMASK_N_FRONT, half_thickness + epsilon_z );
    aModel.SetLayerZ( SILKSCREEN_N_FRONT, half_thickness + epsilon_z * 2 );
    aModel.SetLayerZ( ADHESIVE_N_FRONT, half_thickness + epsilon_z * 3 );
    aModel.SetLayerZ( SOLDERPASTE_N_FRONT, half_thickness + epsilon_z * 4 );
    aModel.SetLayerZ( DRAW_N, half_thickness + epsilon_z * 5 );
    aModel.SetLayerZ( COMMENT_N, half_thickness + epsilon_z * 6 );
    aModel.SetLayerZ( ECO1_N, half_thickness + epsilon_z * 7 );
    aModel.SetLayerZ( ECO2_N, half_thickness + epsilon_z * 8 );
    aModel.SetLayerZ( EDGE_N, 0 );
471 472 473
}


474 475 476
static void export_vrml_line( MODEL_VRML& aModel, LAYER_NUM layer,
        double startx, double starty,
        double endx, double endy, double width )
477
{
478
    VRML_LAYER* vlayer;
479

480 481
    if( !VRMLEXPORT::GetLayer( aModel, layer, &vlayer ) )
        return;
482

483 484
    starty = -starty;
    endy = -endy;
485

486 487 488 489
    double  angle   = atan2( endy - starty, endx - startx );
    double  length  = Distance( startx, starty, endx, endy ) + width;
    double  cx  = ( startx + endx ) / 2.0;
    double  cy  = ( starty + endy ) / 2.0;
490

491
    vlayer->AddSlot( cx, cy, length, width, angle, 1, false );
492 493 494
}


495 496 497
static void export_vrml_circle( MODEL_VRML& aModel, LAYER_NUM layer,
        double startx, double starty,
        double endx, double endy, double width )
498
{
499
    VRML_LAYER* vlayer;
500

501 502
    if( !VRMLEXPORT::GetLayer( aModel, layer, &vlayer ) )
        return;
503

504 505
    starty = -starty;
    endy = -endy;
506

507
    double hole, radius;
508

509 510
    radius = Distance( startx, starty, endx, endy ) + ( width / 2);
    hole = radius - width;
511

512
    vlayer->AddCircle( startx, starty, radius, 1, false );
513

514
    if( hole > 0.0001 )
515
    {
516
        vlayer->AddCircle( startx, starty, hole, 1, true );
517 518 519
    }
}

520

521 522 523 524
static void export_vrml_arc( MODEL_VRML& aModel, LAYER_NUM layer,
        double centerx, double centery,
        double arc_startx, double arc_starty,
        double width, double arc_angle )
525
{
526
    VRML_LAYER* vlayer;
527

528 529
    if( !VRMLEXPORT::GetLayer( aModel, layer, &vlayer ) )
        return;
530

531 532
    centery = -centery;
    arc_starty = -arc_starty;
533

534
    arc_angle *= -M_PI / 180;
535

536 537
    vlayer->AddArc( centerx, centery, arc_startx, arc_starty,
            width, arc_angle, 1, false );
538 539
}

540

541
static void export_vrml_drawsegment( MODEL_VRML& aModel, DRAWSEGMENT* drawseg )
542
{
543
    LAYER_NUM layer = drawseg->GetLayer();
544 545 546 547 548
    double  w   = drawseg->GetWidth() * aModel.scale;
    double  x   = drawseg->GetStart().x * aModel.scale + aModel.tx;
    double  y   = drawseg->GetStart().y * aModel.scale + aModel.ty;
    double  xf  = drawseg->GetEnd().x * aModel.scale + aModel.tx;
    double  yf  = drawseg->GetEnd().y * aModel.scale + aModel.ty;
549

550
    // Items on the edge layer are handled elsewhere; just return
551
    if( layer == EDGE_N )
552
        return;
553

554
    switch( drawseg->GetShape() )
555
    {
556 557 558 559 560 561 562 563
    case S_ARC:
        export_vrml_arc( aModel, layer,
                (double) drawseg->GetCenter().x,
                (double) drawseg->GetCenter().y,
                (double) drawseg->GetArcStart().x,
                (double) drawseg->GetArcStart().y,
                w, drawseg->GetAngle() / 10 );
        break;
564

565 566 567
    case S_CIRCLE:
        export_vrml_circle( aModel, layer, x, y, xf, yf, w );
        break;
568

569 570 571
    default:
        export_vrml_line( aModel, layer, x, y, xf, yf, w );
        break;
572 573 574 575 576 577 578 579
    }
}


/* C++ doesn't have closures and neither continuation forms... this is
 * for coupling the vrml_text_callback with the common parameters */
static void vrml_text_callback( int x0, int y0, int xf, int yf )
{
580 581 582 583 584 585 586 587 588 589
    LAYER_NUM s_text_layer = VRMLEXPORT::model_vrml->s_text_layer;
    int s_text_width = VRMLEXPORT::model_vrml->s_text_width;
    double  scale = VRMLEXPORT::model_vrml->scale;
    double  tx  = VRMLEXPORT::model_vrml->tx;
    double  ty  = VRMLEXPORT::model_vrml->ty;

    export_vrml_line( *VRMLEXPORT::model_vrml, s_text_layer,
            x0 * scale + tx, y0 * scale + ty,
            xf * scale + tx, yf * scale + ty,
            s_text_width * scale );
590 591 592
}


593
static void export_vrml_pcbtext( MODEL_VRML& aModel, TEXTE_PCB* text )
594
{
595 596
    VRMLEXPORT::model_vrml->s_text_layer    = text->GetLayer();
    VRMLEXPORT::model_vrml->s_text_width    = text->GetThickness();
597

598 599 600
    wxSize size = text->GetSize();

    if( text->IsMirrored() )
601
        NEGATE( size.x );
602

603 604
    EDA_COLOR_T color = BLACK;  // not actually used, but needed by DrawGraphicText

605
    if( text->IsMultilineAllowed() )
606
    {
607
        wxArrayString* list = wxStringSplit( text->GetText(), '\n' );
608 609 610
        std::vector<wxPoint> positions;
        positions.reserve( list->Count() );
        text->GetPositionsOfLinesOfMultilineText( positions, list->Count() );
611

612
        for( unsigned ii = 0; ii < list->Count(); ii++ )
613
        {
614 615 616 617 618 619 620
            wxString txt = list->Item( ii );
            DrawGraphicText( NULL, NULL, positions[ii], color,
                             txt, text->GetOrientation(), size,
                             text->GetHorizJustify(), text->GetVertJustify(),
                             text->GetThickness(), text->IsItalic(),
                             true,
                             vrml_text_callback );
621 622 623 624 625 626
        }

        delete (list);
    }
    else
    {
627 628 629 630 631 632
        DrawGraphicText( NULL, NULL, text->GetTextPosition(), color,
                         text->GetText(), text->GetOrientation(), size,
                         text->GetHorizJustify(), text->GetVertJustify(),
                         text->GetThickness(), text->IsItalic(),
                         true,
                         vrml_text_callback );
633 634 635 636
    }
}


637
static void export_vrml_drawings( MODEL_VRML& aModel, BOARD* pcb )
638
{
Dick Hollenbeck's avatar
Dick Hollenbeck committed
639
    // draw graphic items
640
    for( EDA_ITEM* drawing = pcb->m_Drawings; drawing != 0; drawing = drawing->Next() )
641
    {
642 643 644 645 646 647
        LAYER_NUM layer = ( (DRAWSEGMENT*) drawing )->GetLayer();

        if( layer != FIRST_COPPER_LAYER && layer != LAST_COPPER_LAYER
            && layer != SILKSCREEN_N_BACK && layer != SILKSCREEN_N_FRONT )
            continue;

648 649
        switch( drawing->Type() )
        {
650
        case PCB_LINE_T:
651
            export_vrml_drawsegment( aModel, (DRAWSEGMENT*) drawing );
652 653
            break;

654
        case PCB_TEXT_T:
655
            export_vrml_pcbtext( aModel, (TEXTE_PCB*) drawing );
656 657 658 659 660 661 662 663 664
            break;

        default:
            break;
        }
    }
}


665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 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 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
// board edges and cutouts
static void export_vrml_board( MODEL_VRML& aModel, BOARD* pcb )
{
    CPOLYGONS_LIST  bufferPcbOutlines;      // stores the board main outlines
    CPOLYGONS_LIST  allLayerHoles;          // Contains through holes, calculated only once

    allLayerHoles.reserve( 20000 );

    // Build a polygon from edge cut items
    wxString msg;

    if( !pcb->GetBoardPolygonOutlines( bufferPcbOutlines,
                allLayerHoles, &msg ) )
    {
        msg << wxT( "\n\n" ) <<
        _( "Unable to calculate the board outlines;\n"
           "fall back to using the board boundary box." );
        wxMessageBox( msg );
    }

    double  scale = aModel.scale;
    double  dx  = aModel.tx;
    double  dy  = aModel.ty;

    int i = 0;
    int seg;

    // deal with the solid outlines
    int nvert = bufferPcbOutlines.GetCornersCount();

    while( i < nvert )
    {
        seg = aModel.board.NewContour();

        if( seg < 0 )
        {
            msg << wxT( "\n\n" ) <<
                _( "VRML Export Failed:\nCould not add outline to contours." );
            wxMessageBox( msg );

            return;
        }

        while( i < nvert )
        {
            aModel.board.AddVertex( seg, bufferPcbOutlines[i].x * scale + dx,
                    -(bufferPcbOutlines[i].y * scale + dy) );

            if( bufferPcbOutlines[i].end_contour )
                break;

            ++i;
        }

        aModel.board.EnsureWinding( seg, false );
        ++i;
    }

    // deal with the holes
    nvert = allLayerHoles.GetCornersCount();

    i = 0;
    while( i < nvert )
    {
        seg = aModel.holes.NewContour();

        if( seg < 0 )
        {
            msg << wxT( "\n\n" ) <<
            _( "VRML Export Failed:\nCould not add holes to contours." );
            wxMessageBox( msg );

            return;
        }

        while( i < nvert )
        {
            aModel.holes.AddVertex( seg, allLayerHoles[i].x * scale + dx,
                                    -(allLayerHoles[i].y * scale + dy) );

            if( allLayerHoles[i].end_contour )
                break;

            ++i;
        }

        aModel.holes.EnsureWinding( seg, true );
        ++i;
    }
}


static void export_round_padstack( MODEL_VRML& aModel, BOARD* pcb,
        double x, double y, double r,
        LAYER_NUM bottom_layer, LAYER_NUM top_layer,
        double hole )
761
{
762 763
    LAYER_NUM layer = top_layer;
    bool thru = true;
764

765 766 767 768 769
    // if not a thru hole do not put a hole in the board
    if( top_layer != LAST_COPPER_LAYER || bottom_layer != FIRST_COPPER_LAYER )
        thru = false;

    while( 1 )
770
    {
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
        if( layer == FIRST_COPPER_LAYER )
        {
            aModel.bot_copper.AddCircle( x, -y, r, 1 );

            if( hole > 0 )
            {
                if( thru )
                    aModel.holes.AddCircle( x, -y, hole, 1, true );
                else
                    aModel.bot_copper.AddCircle( x, -y, hole, 1, true );
            }
        }
        else if( layer == LAST_COPPER_LAYER )
        {
            aModel.top_copper.AddCircle( x, -y, r, 1 );

            if( hole > 0 )
            {
                if( thru )
                    aModel.holes.AddCircle( x, -y, hole, 1, true );
                else
                    aModel.top_copper.AddCircle( x, -y, hole, 1, true );
            }
        }
795

796 797 798 799
        if( layer == bottom_layer )
            break;

        layer = bottom_layer;
800 801 802 803
    }
}


804
static void export_vrml_via( MODEL_VRML& aModel, BOARD* pcb, const VIA* via )
805 806
{
    double x, y, r, hole;
807
    LAYER_NUM top_layer, bottom_layer;
808

809 810 811 812
    hole = via->GetDrillValue() * aModel.scale / 2.0;
    r   = via->GetWidth() * aModel.scale / 2.0;
    x   = via->GetStart().x * aModel.scale + aModel.tx;
    y   = via->GetStart().y * aModel.scale + aModel.ty;
813
    via->LayerPair( &top_layer, &bottom_layer );
814

815 816 817
    // do not render a buried via
    if( top_layer != LAST_COPPER_LAYER && bottom_layer != FIRST_COPPER_LAYER )
        return;
818

819 820
    // Export the via padstack
    export_round_padstack( aModel, pcb, x, y, r, bottom_layer, top_layer, hole );
821 822 823
}


824
static void export_vrml_tracks( MODEL_VRML& aModel, BOARD* pcb )
825 826 827
{
    for( TRACK* track = pcb->m_Track; track != NULL; track = track->Next() )
    {
828
        if( track->Type() == PCB_VIA_T )
829
        {
830
            export_vrml_via( aModel, pcb, (const VIA*) track );
831 832 833 834 835 836 837 838 839
        }
        else if( track->GetLayer() == FIRST_COPPER_LAYER
                 || track->GetLayer() == LAST_COPPER_LAYER )
            export_vrml_line( aModel, track->GetLayer(),
                    track->GetStart().x * aModel.scale + aModel.tx,
                    track->GetStart().y * aModel.scale + aModel.ty,
                    track->GetEnd().x * aModel.scale + aModel.tx,
                    track->GetEnd().y * aModel.scale + aModel.ty,
                    track->GetWidth() * aModel.scale );
840 841 842 843
    }
}


844
static void export_vrml_zones( MODEL_VRML& aModel, BOARD* aPcb )
845 846
{

847 848 849 850 851 852 853
    double scale = aModel.scale;
    double dx = aModel.tx;
    double dy = aModel.ty;

    double x, y;

    for( int ii = 0; ii < aPcb->GetAreaCount(); ii++ )
854
    {
855 856 857
        ZONE_CONTAINER* zone = aPcb->GetArea( ii );

        VRML_LAYER* vl;
858

859
        if( !VRMLEXPORT::GetLayer( aModel, zone->GetLayer(), &vl ) )
860
            continue;
861

862 863 864 865 866 867 868 869 870
        if( !zone->IsFilled() )
        {
            zone->SetFillMode( 0 ); // use filled polygons
            zone->BuildFilledSolidAreasPolygons( aPcb );
        }
        const CPOLYGONS_LIST& poly = zone->GetFilledPolysList();

        int nvert = poly.GetCornersCount();
        int i = 0;
871

872
        while( i < nvert )
873
        {
874 875
            int seg = vl->NewContour();
            bool first = true;
876

877 878
            if( seg < 0 )
                break;
879

880 881 882 883 884
            while( i < nvert )
            {
                x = poly.GetX(i) * scale + dx;
                y = -(poly.GetY(i) * scale + dy);
                vl->AddVertex( seg, x, y );
885

886 887
                if( poly.IsEndContour(i) )
                    break;
888

889
                ++i;
890
            }
891 892 893 894 895 896 897 898 899

            // KiCad ensures that the first polygon is the outline
            // and all others are holes
             vl->EnsureWinding( seg, first ? false : true );

            if( first )
                first = false;

            ++i;
900 901 902 903
        }
    }
}

904 905

static void export_vrml_text_module( TEXTE_MODULE* module )
906
{
Dick Hollenbeck's avatar
Dick Hollenbeck committed
907
    if( module->IsVisible() )
908
    {
909
        wxSize size = module->GetSize();
910

911
        if( module->IsMirrored() )
912 913 914 915
            NEGATE( size.x );  // Text is mirrored

        VRMLEXPORT::model_vrml->s_text_layer    = module->GetLayer();
        VRMLEXPORT::model_vrml->s_text_width    = module->GetThickness();
916

917
        DrawGraphicText( NULL, NULL, module->GetTextPosition(), BLACK,
918 919 920 921 922
                module->GetText(), module->GetDrawRotation(), size,
                module->GetHorizJustify(), module->GetVertJustify(),
                module->GetThickness(), module->IsItalic(),
                true,
                vrml_text_callback );
923 924 925 926
    }
}


927 928
static void export_vrml_edge_module( MODEL_VRML& aModel, EDGE_MODULE* aOutline,
                                     double aOrientation )
929
{
930
    LAYER_NUM layer = aOutline->GetLayer();
931 932 933 934 935
    double  x   = aOutline->GetStart().x * aModel.scale + aModel.tx;
    double  y   = aOutline->GetStart().y * aModel.scale + aModel.ty;
    double  xf  = aOutline->GetEnd().x * aModel.scale + aModel.tx;
    double  yf  = aOutline->GetEnd().y * aModel.scale + aModel.ty;
    double  w   = aOutline->GetWidth() * aModel.scale;
936 937

    switch( aOutline->GetShape() )
938
    {
939 940 941 942
    case S_SEGMENT:
        export_vrml_line( aModel, layer, x, y, xf, yf, w );
        break;

943
    case S_ARC:
944
        export_vrml_arc( aModel, layer, x, y, xf, yf, w, aOutline->GetAngle() / 10 );
945 946 947
        break;

    case S_CIRCLE:
948
        export_vrml_circle( aModel, layer, x, y, xf, yf, w );
949 950
        break;

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    case S_POLYGON:
        {
            VRML_LAYER* vl;

            if( !VRMLEXPORT::GetLayer( aModel, layer, &vl ) )
                break;

            int nvert = aOutline->GetPolyPoints().size();
            int i = 0;

            if( nvert < 3 ) break;

            int seg = vl->NewContour();

            if( seg < 0 )
                break;

            while( i < nvert )
            {
                CPolyPt corner( aOutline->GetPolyPoints()[i] );
                RotatePoint( &corner.x, &corner.y, aOrientation );
                corner.x += aOutline->GetPosition().x;
                corner.y += aOutline->GetPosition().y;

                x = corner.x * aModel.scale + aModel.tx;
                y = - ( corner.y * aModel.scale + aModel.ty );
                vl->AddVertex( seg, x, y );

                ++i;
            }
            vl->EnsureWinding( seg, false );
        }
        break;

985 986 987 988 989 990
    default:
        break;
    }
}


991 992
static void export_vrml_padshape( MODEL_VRML& aModel, VRML_LAYER* aLayer,
                                  VRML_LAYER* aTinLayer, D_PAD* aPad )
993
{
994
    // The (maybe offset) pad position
995
    wxPoint pad_pos = aPad->ShapePos();
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 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 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    double  pad_x   = pad_pos.x * aModel.scale + aModel.tx;
    double  pad_y   = pad_pos.y * aModel.scale + aModel.ty;
    wxSize  pad_delta = aPad->GetDelta();

    double  pad_dx  = pad_delta.x * aModel.scale / 2.0;
    double  pad_dy  = pad_delta.y * aModel.scale / 2.0;

    double  pad_w   = aPad->GetSize().x * aModel.scale / 2.0;
    double  pad_h   = aPad->GetSize().y * aModel.scale / 2.0;

    switch( aPad->GetShape() )
    {
    case PAD_CIRCLE:
        aLayer->AddCircle( pad_x, -pad_y, pad_w, 1, true );
        aTinLayer->AddCircle( pad_x, -pad_y, pad_w, 1, false );
        break;

    case PAD_OVAL:
        aLayer->AddSlot( pad_x, -pad_y, pad_w * 2.0, pad_h * 2.0,
                DECIDEG2RAD( aPad->GetOrientation() ), 1, true );
        aTinLayer->AddSlot( pad_x, -pad_y, pad_w * 2.0, pad_h * 2.0,
                         DECIDEG2RAD( aPad->GetOrientation() ), 1, false );
        break;

    case PAD_RECT:
        // Just to be sure :D
        pad_dx  = 0;
        pad_dy  = 0;

    case PAD_TRAPEZOID:
        {
            double coord[8] =
            {
                -pad_w + pad_dy, -pad_h - pad_dx,
                -pad_w - pad_dy, pad_h + pad_dx,
                +pad_w - pad_dy, -pad_h + pad_dx,
                +pad_w + pad_dy, pad_h - pad_dx
            };

            for( int i = 0; i < 4; i++ )
            {
                RotatePoint( &coord[i * 2], &coord[i * 2 + 1], aPad->GetOrientation() );
                coord[i * 2] += pad_x;
                coord[i * 2 + 1] += pad_y;
            }

            int lines = aLayer->NewContour();

            if( lines < 0 )
                return;

            aLayer->AddVertex( lines, coord[2], -coord[3] );
            aLayer->AddVertex( lines, coord[6], -coord[7] );
            aLayer->AddVertex( lines, coord[4], -coord[5] );
            aLayer->AddVertex( lines, coord[0], -coord[1] );
            aLayer->EnsureWinding( lines, true );

            lines = aTinLayer->NewContour();

            if( lines < 0 )
                return;

            aTinLayer->AddVertex( lines, coord[0], -coord[1] );
            aTinLayer->AddVertex( lines, coord[4], -coord[5] );
            aTinLayer->AddVertex( lines, coord[6], -coord[7] );
            aTinLayer->AddVertex( lines, coord[2], -coord[3] );
            aTinLayer->EnsureWinding( lines, false );
        }
        break;

    default:
        ;
    }
}


static void export_vrml_pad( MODEL_VRML& aModel, BOARD* pcb, D_PAD* aPad )
{
    double  hole_drill_w    = (double) aPad->GetDrillSize().x * aModel.scale / 2.0;
    double  hole_drill_h    = (double) aPad->GetDrillSize().y * aModel.scale / 2.0;
    double  hole_drill = std::min( hole_drill_w, hole_drill_h );
    double  hole_x  = aPad->GetPosition().x * aModel.scale + aModel.tx;
    double  hole_y  = aPad->GetPosition().y * aModel.scale + aModel.ty;
1079

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1080
    // Export the hole on the edge layer
1081 1082
    if( hole_drill > 0 )
    {
1083
        if( aPad->GetDrillShape() == PAD_DRILL_OBLONG )
1084
        {
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1085
            // Oblong hole (slot)
1086 1087
            aModel.holes.AddSlot( hole_x, -hole_y, hole_drill_w * 2.0, hole_drill_h * 2.0,
                    DECIDEG2RAD( aPad->GetOrientation() ), 1, true );
1088 1089 1090 1091
        }
        else
        {
            // Drill a round hole
1092
            aModel.holes.AddCircle( hole_x, -hole_y, hole_drill, 1, true );
1093 1094 1095
        }
    }

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1096
    // The pad proper, on the selected layers
1097
    LAYER_MSK layer_mask = aPad->GetLayerMask();
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1098

1099
    if( layer_mask & LAYER_BACK )
1100
    {
1101 1102
        export_vrml_padshape( aModel, &aModel.bot_copper, &aModel.bot_tin, aPad );
    }
1103

1104 1105 1106
    if( layer_mask & LAYER_FRONT )
    {
        export_vrml_padshape( aModel, &aModel.top_copper, &aModel.top_tin, aPad );
1107 1108 1109 1110
    }
}


Dick Hollenbeck's avatar
Dick Hollenbeck committed
1111
// From axis/rot to quaternion
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
static void build_quat( double x, double y, double z, double a, double q[4] )
{
    double sina = sin( a / 2 );

    q[0] = x * sina;
    q[1] = y * sina;
    q[2] = z * sina;
    q[3] = cos( a / 2 );
}


Dick Hollenbeck's avatar
Dick Hollenbeck committed
1123
// From quaternion to axis/rot
1124 1125 1126
static void from_quat( double q[4], double rot[4] )
{
    rot[3] = acos( q[3] ) * 2;
1127

1128 1129 1130 1131 1132 1133 1134
    for( int i = 0; i < 3; i++ )
    {
        rot[i] = q[i] / sin( rot[3] / 2 );
    }
}


Dick Hollenbeck's avatar
Dick Hollenbeck committed
1135
// Quaternion composition
1136 1137 1138 1139
static void compose_quat( double q1[4], double q2[4], double qr[4] )
{
    double tmp[4];

1140 1141 1142 1143 1144 1145 1146 1147 1148
    tmp[0] = q2[3] * q1[0] + q2[0] * q1[3] + q2[1] * q1[2] - q2[2] * q1[1];
    tmp[1] = q2[3] * q1[1] + q2[1] * q1[3] + q2[2] * q1[0] - q2[0] * q1[2];
    tmp[2] = q2[3] * q1[2] + q2[2] * q1[3] + q2[0] * q1[1] - q2[1] * q1[0];
    tmp[3] = q2[3] * q1[3] - q2[0] * q1[0] - q2[1] * q1[1] - q2[2] * q1[2];

    qr[0] = tmp[0];
    qr[1] = tmp[1];
    qr[2] = tmp[2];
    qr[3] = tmp[3];
1149 1150 1151
}


1152 1153 1154 1155
static void export_vrml_module( MODEL_VRML& aModel, BOARD* aPcb, MODULE* aModule,
        FILE* aOutputFile,
        double aVRMLModelsToBiu,
        bool aExport3DFiles, const wxString& a3D_Subdir )
1156
{
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1157
    // Reference and value
1158 1159 1160 1161 1162
    if( aModule->Reference().IsVisible() )
        export_vrml_text_module( &aModule->Reference() );

    if( aModule->Value().IsVisible() )
        export_vrml_text_module( &aModule->Value() );
1163

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1164
    // Export module edges
1165
    for( EDA_ITEM* item = aModule->GraphicalItems(); item != NULL; item = item->Next() )
1166 1167 1168
    {
        switch( item->Type() )
        {
1169
        case PCB_MODULE_TEXT_T:
1170
            export_vrml_text_module( dynamic_cast<TEXTE_MODULE*>( item ) );
1171 1172
            break;

1173
        case PCB_MODULE_EDGE_T:
1174 1175
            export_vrml_edge_module( aModel, dynamic_cast<EDGE_MODULE*>( item ),
                                     aModule->GetOrientation() );
1176 1177 1178 1179 1180 1181 1182
            break;

        default:
            break;
        }
    }

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1183
    // Export pads
1184 1185
    for( D_PAD* pad = aModule->Pads(); pad; pad = pad->Next() )
        export_vrml_pad( aModel, aPcb, pad );
1186 1187

    bool isFlipped = aModule->GetLayer() == LAYER_N_BACK;
1188

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1189
    // Export the object VRML model(s)
1190
    for( S3D_MASTER* vrmlm = aModule->Models();  vrmlm;  vrmlm = vrmlm->Next() )
1191
    {
1192
        if( !vrmlm->Is3DType( S3D_MASTER::FILE3D_VRML ) )
1193 1194
            continue;

1195
        wxString fname = vrmlm->GetShape3DFullFilename();
1196

1197
        fname.Replace( wxT( "\\" ), wxT( "/" ) );
1198
        wxString source_fname = fname;
1199

1200
        if( aExport3DFiles )
1201
        {
1202
            // Change illegal characters in filenames
1203
            ChangeIllegalCharacters( fname, true );
1204
            fname = a3D_Subdir + wxT( "/" ) + fname;
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214
            if( !wxFileExists( fname ) )
                wxCopyFile( source_fname, fname );
        }

        /* Calculate 3D shape rotation:
         * this is the rotation parameters, with an additional 180 deg rotation
         * for footprints that are flipped
         * When flipped, axis rotation is the horizontal axis (X axis)
         */
1215 1216 1217
        double rotx = -vrmlm->m_MatRotation.x;
        double roty = -vrmlm->m_MatRotation.y;
        double rotz = -vrmlm->m_MatRotation.z;
1218

1219
        if( isFlipped )
1220 1221
        {
            rotx += 180.0;
1222 1223
            NEGATE( roty );
            NEGATE( rotz );
1224
        }
1225

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1226
        // Do some quaternion munching
1227
        double q1[4], q2[4], rot[4];
1228 1229
        build_quat( 1, 0, 0, DEG2RAD( rotx ), q1 );
        build_quat( 0, 1, 0, DEG2RAD( roty ), q2 );
1230
        compose_quat( q1, q2, q1 );
1231
        build_quat( 0, 0, 1, DEG2RAD( rotz ), q2 );
1232
        compose_quat( q1, q2, q1 );
1233

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1234
        // Note here aModule->GetOrientation() is in 0.1 degrees,
1235 1236
        // so module rotation has to be converted to radians
        build_quat( 0, 0, 1, DECIDEG2RAD( aModule->GetOrientation() ), q2 );
1237 1238 1239 1240
        compose_quat( q1, q2, q1 );
        from_quat( q1, rot );

        fprintf( aOutputFile, "Transform {\n" );
1241

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1242
        // A null rotation would fail the acos!
1243 1244
        if( rot[3] != 0.0 )
        {
1245
            fprintf( aOutputFile, "  rotation %g %g %g %g\n", rot[0], rot[1], rot[2], rot[3] );
1246
        }
1247

1248 1249 1250 1251 1252
        // adjust 3D shape local offset position
        // they are given in inch, so they are converted in board IU.
        double offsetx = vrmlm->m_MatPosition.x * IU_PER_MILS * 1000.0;
        double offsety = vrmlm->m_MatPosition.y * IU_PER_MILS * 1000.0;
        double offsetz = vrmlm->m_MatPosition.z * IU_PER_MILS * 1000.0;
1253

1254
        if( isFlipped )
1255 1256 1257
            NEGATE( offsetz );
        else // In normal mode, Y axis is reversed in Pcbnew.
            NEGATE( offsety );
1258

1259
        RotatePoint( &offsetx, &offsety, aModule->GetOrientation() );
1260

1261
        fprintf( aOutputFile, "  translation %g %g %g\n",
1262 1263 1264
                (offsetx + aModule->GetPosition().x) * aModel.scale + aModel.tx,
                -(offsety + aModule->GetPosition().y) * aModel.scale - aModel.ty,
                (offsetz * aModel.scale ) + aModel.GetLayerZ( aModule->GetLayer() ) );
1265 1266

        fprintf( aOutputFile, "  scale %g %g %g\n",
1267 1268 1269
                vrmlm->m_MatScale.x * aVRMLModelsToBiu,
                vrmlm->m_MatScale.y * aVRMLModelsToBiu,
                vrmlm->m_MatScale.z * aVRMLModelsToBiu );
1270

1271 1272
        if( fname.EndsWith( wxT( "x3d" ) ) )
        {
1273
            X3D_MODEL_PARSER* parser = new X3D_MODEL_PARSER( vrmlm );
1274

1275
            if( parser )
1276 1277
            {
                // embed x3d model in vrml format
1278
                parser->Load( fname );
1279
                fprintf( aOutputFile,
1280
                        "  children [\n %s ]\n", TO_UTF8( parser->VRML_representation() ) );
1281 1282 1283 1284 1285 1286 1287
                fprintf( aOutputFile, "  }\n" );
                delete parser;
            }
        }
        else
        {
            fprintf( aOutputFile,
1288 1289
                    "  children [\n    Inline {\n      url \"%s\"\n    } ]\n",
                    TO_UTF8( fname ) );
1290 1291
            fprintf( aOutputFile, "  }\n" );
        }
1292 1293 1294 1295
    }
}


1296 1297 1298
bool PCB_EDIT_FRAME::ExportVRML_File( const wxString& aFullFileName,
        double aMMtoWRMLunit, bool aExport3DFiles,
        const wxString& a3D_Subdir )
1299
{
1300 1301 1302
    wxString    msg;
    FILE*       output_file;
    BOARD*      pcb = GetBoard();
1303

1304
    MODEL_VRML model3d;
1305

1306
    VRMLEXPORT::model_vrml = &model3d;
1307 1308

    output_file = wxFopen( aFullFileName, wxT( "wt" ) );
1309

1310 1311 1312 1313 1314 1315
    if( output_file == NULL )
        return false;

    // Switch the locale to standard C (needed to print floating point numbers like 1.3)
    SetLocaleTo_C_standard();

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1316
    // Begin with the usual VRML boilerplate
1317 1318
    wxString name = aFullFileName;

1319
    name.Replace( wxT( "\\" ), wxT( "/" ) );
1320
    ChangeIllegalCharacters( name, false );
1321 1322
    fprintf( output_file, "#VRML V2.0 utf8\n"
                          "WorldInfo {\n"
1323
                          "  title \"%s - Generated by Pcbnew\"\n"
1324
                          "}\n", TO_UTF8( name ) );
1325

1326
    // Global VRML scale to export to a different scale.
1327
    model3d.scale = aMMtoWRMLunit / MM_PER_IU;
1328

1329 1330 1331 1332
    // Set the mechanical deviation limit (in this case 0.02mm)
    // XXX - NOTE: the value should be set via the GUI
    model3d.SetMaxDev( 20000 * model3d.scale );

1333
    fprintf( output_file, "Transform {\n" );
1334

1335 1336
    // compute the offset to center the board on (0, 0, 0)
    // XXX - NOTE: we should allow the user a GUI option to specify the offset
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1337 1338
    EDA_RECT bbbox = pcb->ComputeBoundingBox();

1339
    model3d.SetOffset( -model3d.scale * bbbox.Centre().x, -model3d.scale * bbbox.Centre().y );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1340

1341
    fprintf( output_file, "  children [\n" );
1342

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1343
    // Preliminary computation: the z value for each layer
1344
    compute_layer_Zs( model3d, pcb );
1345

1346 1347 1348 1349 1350
    // board edges and cutouts
    export_vrml_board( model3d, pcb );

    // Drawing and text on the board
    export_vrml_drawings( model3d, pcb );
1351

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1352
    // Export vias and trackage
1353
    export_vrml_tracks( model3d, pcb );
1354

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1355
    // Export zone fills
1356
    export_vrml_zones( model3d, pcb);
1357

1358 1359 1360 1361
    /* scaling factor to convert 3D models to board units (decimils)
     * Usually we use Wings3D to create thems.
     * One can consider the 3D units is 0.1 inch (2.54 mm)
     * So the scaling factor from 0.1 inch to board units
1362
     * is 2.54 * aMMtoWRMLunit
1363
     */
1364
    double wrml_3D_models_scaling_factor = 2.54 * aMMtoWRMLunit;
1365

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1366
    // Export footprints
1367
    for( MODULE* module = pcb->m_Modules; module != 0; module = module->Next() )
1368 1369 1370 1371 1372 1373
        export_vrml_module( model3d, pcb, module, output_file,
                wrml_3D_models_scaling_factor,
                aExport3DFiles, a3D_Subdir );

    // write out the board and all layers
    write_layers( model3d, output_file, pcb );
1374

Dick Hollenbeck's avatar
Dick Hollenbeck committed
1375
    // Close the outer 'transform' node
1376 1377 1378 1379 1380 1381 1382 1383
    fputs( "]\n}\n", output_file );

    // End of work
    fclose( output_file );
    SetLocaleTo_Default();       // revert to the current  locale

    return true;
}
1384

1385

1386 1387 1388 1389
/*
 * some characters cannot be used in filenames,
 * this function change them to "_"
 */
1390
static void ChangeIllegalCharacters( wxString& aFileName, bool aDirSepIsIllegal )
1391 1392
{
    if( aDirSepIsIllegal )
1393
        aFileName.Replace( wxT( "/" ), wxT( "_" ) );
1394

1395 1396
    aFileName.Replace( wxT( " " ), wxT( "_" ) );
    aFileName.Replace( wxT( ":" ), wxT( "_" ) );
1397
}