KiCad PCB EDA Suite
gerber_placefile_writer.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2019 Jean_Pierre Charras <jp.charras at wanadoo.fr>
5  * Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software: you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation, either version 3 of the License, or (at your
10  * option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program. If not, see <http://www.gnu.org/licenses/>.
19  */
20 
26 #include <fctsys.h>
28 
29 #include <vector>
30 
31 #include <plotter.h>
32 #include <kicad_string.h>
33 #include <pcb_edit_frame.h>
34 #include <pgm_base.h>
35 
36 #include <class_board.h>
37 
38 #include <pcbplot.h>
39 #include <pcbnew.h>
41 #include <reporter.h>
42 #include <gbr_metadata.h>
43 #include <class_module.h>
44 
45 
47 {
48  m_pcb = aPcb;
49  /* Set conversion scale depending on drill file units */
50  m_conversionUnits = 1.0 / IU_PER_MM; // Gerber units = mm
51  m_forceSmdItems = false;
52  m_plotPad1Marker = true; // Place a marker to pin 1 (or A1) position
53  m_plotOtherPadsMarker = true; // Place a marker to other pins position
54  m_layer = PCB_LAYER_ID::UNDEFINED_LAYER; // No layer set
55 }
56 
57 
58 int PLACEFILE_GERBER_WRITER::CreatePlaceFile( wxString& aFullFilename, PCB_LAYER_ID aLayer,
59  bool aIncludeBrdEdges )
60 {
61  m_layer = aLayer;
62 
63  PCB_PLOT_PARAMS plotOpts = m_pcb->GetPlotOptions();
64 
65  if( plotOpts.GetUseAuxOrigin() )
67 
68  // Collect footprints on the right layer
69  std::vector<MODULE*> fp_list;
70 
71  for( MODULE* footprint : m_pcb->Modules() )
72  {
73  if( footprint->GetAttributes() & MOD_EXCLUDE_FROM_POS_FILES )
74  continue;
75 
76  if( footprint->GetLayer() == aLayer )
77  fp_list.push_back( footprint );
78  }
79 
80  LOCALE_IO dummy_io; // Use the standard notation for float numbers
81 
82  GERBER_PLOTTER plotter;
83 
84  // Gerber drill file imply X2 format:
85  plotter.UseX2format( true );
86  plotter.UseX2NetAttributes( true );
87 
88  // Add the standard X2 header, without FileFunction
89  AddGerberX2Header( &plotter, m_pcb );
90  plotter.SetViewport( m_offset, IU_PER_MILS/10, /* scale */ 1.0, /* mirror */false );
91  // has meaning only for gerber plotter. Must be called only after SetViewport
92  plotter.SetGerberCoordinatesFormat( 6 );
93  plotter.SetCreator( wxT( "PCBNEW" ) );
94 
95  // Add the standard X2 FileFunction for P&P files
96  // %TF.FileFunction,Component,Ln,[top][bottom]*%
97  wxString text;
98  text.Printf( "%%TF.FileFunction,Component,L%d,%s*%%",
99  aLayer == B_Cu ? m_pcb->GetCopperLayerCount() : 1,
100  aLayer == B_Cu ? "Bot" : "Top" );
101  plotter.AddLineToHeader( text );
102 
103  // Add file polarity (positive)
104  text = "%TF.FilePolarity,Positive*%";
105  plotter.AddLineToHeader( text );
106 
107  if( !plotter.OpenFile( aFullFilename ) )
108  return -1;
109 
110  // We need a BRDITEMS_PLOTTER to plot pads
111  BRDITEMS_PLOTTER brd_plotter( &plotter, m_pcb, plotOpts );
112 
113  plotter.StartPlot();
114 
115  // Some tools in P&P files have the type and size defined.
116  // they are position flash (round), pad1 flash (diamond), other pads flash (round)
117  // and component outline thickness (polyline)
118  int flash_position_shape_diam = Millimeter2iu( 0.3 ); // defined size for position shape (circle)
119  int pad1_mark_size = Millimeter2iu( 0.36 ); // defined size for pad 1 position (diamond)
120  int other_pads_mark_size = 0; // defined size for position shape (circle)
121  int line_thickness = Millimeter2iu( 0.1 ); // defined size for component outlines
122 
123  brd_plotter.SetLayerSet( LSET( aLayer ) );
124  int cmp_count = 0;
125  bool allowUtf8 = true;
126 
127  // Plot components data: position, outlines, pad1 and other pads.
128  for( MODULE* footprint : fp_list )
129  {
130  // Manage the aperture attribute component position:
131  GBR_METADATA gbr_metadata;
133 
134  // Add object attribute: component reference to flash (mainly usefull for users)
135  // using quoted UTF8 string
136  wxString ref = ConvertNotAllowedCharsInGerber( footprint->Reference().GetShownText(),
137  allowUtf8, true );
138 
139  gbr_metadata.SetCmpReference( ref );
141 
142  // Add P&P specific attributes
143  GBR_CMP_PNP_METADATA pnpAttrib;
144 
145  // Add rotation info (rotation is CCW, in degrees):
146  pnpAttrib.m_Orientation = mapRotationAngle( footprint->GetOrientationDegrees() );
147 
149 
150  if( footprint->GetAttributes() & MOD_THROUGH_HOLE )
152  else if( footprint->GetAttributes() & MOD_SMD )
154 
155  // Add component value info:
156  pnpAttrib.m_Value = ConvertNotAllowedCharsInGerber( footprint->Value().GetShownText(),
157  allowUtf8, true );
158 
159  // Add component footprint info:
160  wxString fp_info = FROM_UTF8( footprint->GetFPID().GetLibItemName().c_str() );
161  pnpAttrib.m_Footprint = ConvertNotAllowedCharsInGerber( fp_info, allowUtf8, true );
162 
163  // Add footprint lib name:
164  fp_info = FROM_UTF8( footprint->GetFPID().GetLibNickname().c_str() );
165  pnpAttrib.m_LibraryName = ConvertNotAllowedCharsInGerber( fp_info, allowUtf8, true );
166 
167  gbr_metadata.m_NetlistMetadata.SetExtraData( pnpAttrib.FormatCmpPnPMetadata() );
168 
169  wxPoint flash_pos = footprint->GetPosition();
170 
171  plotter.FlashPadCircle( flash_pos, flash_position_shape_diam, FILLED, &gbr_metadata );
172  gbr_metadata.m_NetlistMetadata.ClearExtraData();
173 
174  // Now some extra metadata is output, avoid blindly clearing the full metadata list
176 
177  // We plot the footprint courtyard when possible.
178  // If not, the pads bounding box will be used.
179  bool useFpPadsBbox = true;
180 
181  if( footprint->BuildPolyCourtyard() )
182  {
184 
185  SHAPE_POLY_SET& courtyard = aLayer == B_Cu ?
186  footprint->GetPolyCourtyardBack():
187  footprint->GetPolyCourtyardFront();
188 
189  for( int ii = 0; ii < courtyard.OutlineCount(); ii++ )
190  {
191  SHAPE_LINE_CHAIN poly = courtyard.Outline( ii );
192 
193  if( !poly.PointCount() )
194  continue;
195 
196  useFpPadsBbox = false;
197  plotter.PLOTTER::PlotPoly( poly, NO_FILL, line_thickness, &gbr_metadata );
198  }
199  }
200 
201  if( useFpPadsBbox )
202  {
204 
205  // bbox of fp pads, pos 0, rot 0, non flipped
206  EDA_RECT bbox = footprint->GetFpPadsLocalBbox();
207 
208  // negate bbox Y values if the fp is flipped (always flipped around X axis
209  // in Gerber P&P files).
210  int y_sign = aLayer == B_Cu ? -1 : 1;
211 
212  SHAPE_LINE_CHAIN poly;
213  poly.Append( bbox.GetLeft(), y_sign*bbox.GetTop() );
214  poly.Append( bbox.GetLeft(), y_sign*bbox.GetBottom() );
215  poly.Append( bbox.GetRight(), y_sign*bbox.GetBottom() );
216  poly.Append( bbox.GetRight(), y_sign*bbox.GetTop() );
217  poly.SetClosed( true );
218 
219  poly.Rotate( -footprint->GetOrientationRadians(), VECTOR2I( 0, 0 ) );
220  poly.Move( footprint->GetPosition() );
221  plotter.PLOTTER::PlotPoly( poly, NO_FILL, line_thickness, &gbr_metadata );
222  }
223 
224  std::vector<D_PAD*>pad_key_list;
225 
226  if( m_plotPad1Marker )
227  {
228  findPads1( pad_key_list, footprint );
229 
230  for( D_PAD* pad1 : pad_key_list )
231  {
232  gbr_metadata.SetApertureAttrib(
234 
235  gbr_metadata.SetPadName( pad1->GetName(), allowUtf8, true );
236 
237  gbr_metadata.SetPadPinFunction( pad1->GetPinFunction(), allowUtf8, true );
238 
240 
241  // Flashes a diamond at pad position:
242  plotter.FlashRegularPolygon( pad1->GetPosition(),
243  pad1_mark_size,
244  4, 0.0, FILLED, &gbr_metadata );
245  }
246  }
247 
249  {
250 
251  gbr_metadata.SetApertureAttrib(
254 
255  for( D_PAD* pad: footprint->Pads() )
256  {
257  bool skip_pad = false;
258 
259  for( D_PAD* pad1 : pad_key_list )
260  {
261  if( pad == pad1 ) // Already plotted
262  {
263  skip_pad = true;
264  break;
265  }
266  }
267 
268  if( skip_pad )
269  continue;
270 
271  // Skip also pads not on the current layer, like pads only
272  // on a tech layer
273  if( !pad->IsOnLayer( aLayer ) )
274  continue;
275 
276  gbr_metadata.SetPadName( pad->GetName(), allowUtf8, true );
277 
278  gbr_metadata.SetPadPinFunction( pad->GetPinFunction(), allowUtf8, true );
279 
280  // Flashes a round, 0 sized round shape at pad position
281  plotter.FlashPadCircle( pad->GetPosition(),
282  other_pads_mark_size,
283  FILLED, &gbr_metadata );
284  }
285  }
286 
287  plotter.ClearAllAttributes(); // Unconditionally close all .TO attributes
288 
289  cmp_count++;
290  }
291 
292  // Plot board outlines, if requested
293  if( aIncludeBrdEdges )
294  {
295  brd_plotter.SetLayerSet( LSET( Edge_Cuts ) );
296 
297  // Plot edge layer and graphic items
298  brd_plotter.PlotBoardGraphicItems();
299 
300  // Draw footprint other graphic items:
301  for( MODULE* footprint : fp_list )
302  {
303  for( auto item : footprint->GraphicalItems() )
304  {
305  if( item->Type() == PCB_MODULE_EDGE_T && item->GetLayer() == Edge_Cuts )
306  brd_plotter.PlotFootprintGraphicItem((EDGE_MODULE*) item );
307  }
308  }
309  }
310 
311 
312  plotter.EndPlot();
313 
314  return cmp_count;
315 }
316 
317 
319 {
320  // convert a kicad footprint orientation to gerber rotation, depending on the layer
321  // Currently, same notation as kicad
322  return aAngle;
323 }
324 
325 
326 void PLACEFILE_GERBER_WRITER::findPads1( std::vector<D_PAD*>& aPadList, MODULE* aFootprint ) const
327 {
328  // Fint the pad "1" or pad "A1"
329  // this is possible only if only one pad is found
330  // Usefull to place a marker in this position
331 
332  for( D_PAD* pad : aFootprint->Pads() )
333  {
334  if( !pad->IsOnLayer( m_layer ) )
335  continue;
336 
337  if( pad->GetName() == "1" || pad->GetName() == "A1")
338  aPadList.push_back( pad );
339  }
340 }
341 
342 
343 const wxString PLACEFILE_GERBER_WRITER::GetPlaceFileName( const wxString& aFullBaseFilename,
344  PCB_LAYER_ID aLayer ) const
345 {
346  // Gerber files extension is always .gbr.
347  // Therefore, to mark pnp files, add "-pnp" to the filename, and a layer id.
348  wxFileName fn = aFullBaseFilename;
349 
350  wxString post_id = "-pnp_";
351  post_id += aLayer == B_Cu ? "bottom" : "top";
352  fn.SetName( fn.GetName() + post_id );
353  fn.SetExt( GerberFileExtension );
354 
355  return fn.GetFullPath();
356 }
a class to handle special data (items attributes) during plot.
Classes used in place file generation.
int CreatePlaceFile(wxString &aFullFilename, PCB_LAYER_ID aLayer, bool aIncludeBrdEdges)
Creates an pnp gerber file.
void findPads1(std::vector< D_PAD * > &aPadList, MODULE *aFootprint) const
Find the pad(s) 1 (or pad "A1") of a footprint Usefull to plot a marker at this (these) position(s)
aperture used to draw component footprint bounding box in placement files
Definition: gbr_metadata.h:113
virtual void SetCreator(const wxString &aCreator)
Definition: plotter.h:164
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition: class_board.h:533
int OutlineCount() const
Returns the number of outlines in the set
void UseX2NetAttributes(bool aEnable)
Definition: plotter.h:1309
static wxString FROM_UTF8(const char *cstring)
function FROM_UTF8 converts a UTF8 encoded C string to a wxString for all wxWidgets build modes.
Definition: macros.h:114
aperture used for flashed pin 1 (or A1 or AA1) position in placement files
Definition: gbr_metadata.h:107
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: common.h:216
aperture used for flashed pads position in placement files
Definition: gbr_metadata.h:108
print info associated to a component (TO.C attribute)
int GetTop() const
Definition: eda_rect.h:123
static constexpr double IU_PER_MM
Mock up a conversion function.
virtual bool OpenFile(const wxString &aFullFilename)
Open or create the plot file aFullFilename.
Definition: plotter.cpp:77
void SetNetAttribType(int aNetAttribType)
Definition: gbr_metadata.h:170
int GetLeft() const
Definition: eda_rect.h:122
void Move(const VECTOR2I &aVector) override
virtual void FlashRegularPolygon(const wxPoint &aShapePos, int aDiameter, int aCornerCount, double aOrient, EDA_DRAW_MODE_T aTraceMode, void *aData) override
Flash a regular polygon.
PADS & Pads()
Definition: class_module.h:181
void AddGerberX2Header(PLOTTER *aPlotter, const BOARD *aBoard, bool aUseX1CompatibilityMode)
Calculates some X2 attributes, as defined in the Gerber file format specification J4 (chapter 5) and ...
Definition: pcbplot.cpp:282
void UseX2format(bool aEnable)
Definition: plotter.h:1308
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: class_board.h:515
const std::string GerberFileExtension
void AddLineToHeader(const wxString &aExtraString)
Function AddLineToHeader Add a line to the list of free lines to print at the beginning of the file.
Definition: plotter.h:179
VECTOR2< int > VECTOR2I
Definition: vector2d.h:594
int PointCount() const
Function PointCount()
class EDGE_MODULE, a footprint edge
Definition: typeinfo.h:94
virtual bool StartPlot() override
Function StartPlot Write GERBER header to file initialize global variable g_Plot_PlotOutputFile.
this class handle info which can be added in a gerber P&P file as attribute of a component Only appli...
void Append(int aX, int aY, bool aAllowDuplication=false)
Function Append()
int GetBottom() const
Definition: eda_rect.h:124
void SetPadPinFunction(const wxString &aPadPinFunction, bool aUseUTF8, bool aEscapeString)
Definition: gbr_metadata.h:187
Board plot function definition file.
void SetClosed(bool aClosed)
Function SetClosed()
PCB_LAYER_ID
A quick note on layer IDs:
LSET is a set of PCB_LAYER_IDs.
void SetLayerSet(LSET aLayerMask)
Definition: pcbplot.h:92
void ClearAllAttributes()
Remove (clear) all attributes from object attributes dictionary (TO.
void SetExtraData(const wxString &aExtraData)
Set the extra data string printed at end of net attributes.
MODULES & Modules()
Definition: class_board.h:247
SHAPE_POLY_SET.
void SetPadName(const wxString &aPadname, bool aUseUTF8=false, bool aEscapeString=false)
Definition: gbr_metadata.h:182
SHAPE_LINE_CHAIN & Outline(int aIndex)
Returns the reference to aIndex-th outline in the set
void PlotBoardGraphicItems()
plot items like text and graphics, but not tracks and modules
void PlotFootprintGraphicItem(EDGE_MODULE *aEdge)
int GetRight() const
Definition: eda_rect.h:121
PCB_LAYER_ID m_layer
The board layer currently used (typically F_Cu or B_Cu)
Definition of file extensions used in Kicad.
virtual void SetViewport(const wxPoint &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
aperture used to draw component outline courtyard in placement files
Definition: gbr_metadata.h:115
PCB_PLOT_PARAMS handles plot parameters and options when plotting/printing a board.
virtual void FlashPadCircle(const wxPoint &pos, int diametre, EDA_DRAW_MODE_T trace_mode, void *aData) override
Filled circular flashes are stored as apertures.
void Rotate(double aAngle, const VECTOR2I &aCenter=VECTOR2I(0, 0)) override
Function Rotate rotates all vertices by a given angle.
aperture used for flashed cmp position in placement files
Definition: gbr_metadata.h:106
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
see class PGM_BASE
wxString FormatCmpPnPMetadata()
Information pertinent to a Pcbnew printed circuit board.
Definition: class_board.h:176
virtual bool EndPlot() override
SHAPE_LINE_CHAIN.
int GetCopperLayerCount() const
EDA_RECT handles the component boundary box.
Definition: eda_rect.h:44
#define IU_PER_MILS
Definition: plotter.cpp:138
bool m_TryKeepPreviousAttributes
If true, do not clear all attributes when a atribute has changed Usefull when some attributes need to...
wxString ConvertNotAllowedCharsInGerber(const wxString &aString, bool aAllowUtf8Chars, bool aQuoteString)
Similar to FormatStringToGerber.
virtual void SetGerberCoordinatesFormat(int aResolution, bool aUseInches=false) override
Function SetGerberCoordinatesFormat selection of Gerber units and resolution (number of digits in man...
print info associated to a flashed pad (TO.P attribute)
double mapRotationAngle(double aAngle)
convert a kicad footprint orientation to gerber rotation both are in degrees
void SetApertureAttrib(GBR_APERTURE_METADATA::GBR_APERTURE_ATTRIB aApertAttribute)
Definition: gbr_metadata.h:160
GBR_NETLIST_METADATA m_NetlistMetadata
a item to handle object attribute:
Definition: gbr_metadata.h:212
bool GetUseAuxOrigin() const
static constexpr int Millimeter2iu(double mm)
void SetCmpReference(const wxString &aComponentRef)
Definition: gbr_metadata.h:192
wxPoint m_AuxOrigin
origin for plot exports
void ClearExtraData()
Clear the extra data string printed at end of net attributes.