KiCad PCB EDA Suite
gendrill_gerber_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) 2017 Jean_Pierre Charras <jp.charras at wanadoo.fr>
5  * Copyright (C) 1992-2021 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
30 #include <vector>
31 
32 #include <plotter.h>
33 #include <plotters_specific.h>
34 #include <kicad_string.h>
35 #include <locale_io.h>
36 #include <pcb_edit_frame.h>
37 #include <board.h>
38 #include <footprint.h>
39 #include <pcb_track.h>
40 #include <pad.h>
41 #include <pcbplot.h>
42 #include <gendrill_gerber_writer.h>
43 #include <reporter.h>
44 #include <gbr_metadata.h>
45 
46 // set to 1 to use flashed oblong holes, 0 to draw them by a line.
47 #define FLASH_OVAL_HOLE 1
48 
49 
51  : GENDRILL_WRITER_BASE( aPcb )
52 {
54  m_conversionUnits = 1.0;
55  m_unitsMetric = true;
56  m_drillFileExtension = "gbr";
57  m_merge_PTH_NPTH = false;
58 }
59 
60 
61 void GERBER_WRITER::CreateDrillandMapFilesSet( const wxString& aPlotDirectory, bool aGenDrill,
62  bool aGenMap, REPORTER* aReporter )
63 {
64  // Note: In Gerber drill files, NPTH and PTH are always separate files
65  m_merge_PTH_NPTH = false;
66 
67  wxFileName fn;
68  wxString msg;
69 
70  std::vector<DRILL_LAYER_PAIR> hole_sets = getUniqueLayerPairs();
71 
72  // append a pair representing the NPTH set of holes, for separate drill files.
73  // (Gerber drill files are separate files for PTH and NPTH)
74  hole_sets.emplace_back( F_Cu, B_Cu );
75 
76  for( std::vector<DRILL_LAYER_PAIR>::const_iterator it = hole_sets.begin();
77  it != hole_sets.end(); ++it )
78  {
79  DRILL_LAYER_PAIR pair = *it;
80  // For separate drill files, the last layer pair is the NPTH drill file.
81  bool doing_npth = ( it == hole_sets.end() - 1 );
82 
83  buildHolesList( pair, doing_npth );
84 
85  // The file is created if it has holes, or if it is the non plated drill file
86  // to be sure the NPTH file is up to date in separate files mode.
87  // Also a PTH drill/map file is always created, to be sure at least one plated hole drill
88  // file is created (do not create any PTH drill file can be seen as not working drill
89  // generator).
90  if( getHolesCount() > 0 || doing_npth || pair == DRILL_LAYER_PAIR( F_Cu, B_Cu ) )
91  {
92  fn = getDrillFileName( pair, doing_npth, false );
93  fn.SetPath( aPlotDirectory );
94 
95  if( aGenDrill )
96  {
97  wxString fullFilename = fn.GetFullPath();
98 
99  int result = createDrillFile( fullFilename, doing_npth, pair );
100 
101  if( result < 0 )
102  {
103  if( aReporter )
104  {
105  msg.Printf( _( "Failed to create file '%s'." ), fullFilename );
106  aReporter->Report( msg, RPT_SEVERITY_ERROR );
107  }
108 
109  break;
110  }
111  else
112  {
113  if( aReporter )
114  {
115  msg.Printf( _( "Created file '%s'." ), fullFilename );
116  aReporter->Report( msg, RPT_SEVERITY_INFO );
117  }
118  }
119 
120  }
121  }
122  }
123 
124  if( aGenMap )
125  CreateMapFilesSet( aPlotDirectory, aReporter );
126 }
127 
128 
129 #if !FLASH_OVAL_HOLE
130 // A helper class to transform an oblong hole to a segment
131 static void convertOblong2Segment( wxSize aSize, double aOrient, wxPoint& aStart, wxPoint& aEnd );
132 #endif
133 
134 
135 int GERBER_WRITER::createDrillFile( wxString& aFullFilename, bool aIsNpth,
136  DRILL_LAYER_PAIR aLayerPair )
137 {
138  int holes_count;
139 
140  LOCALE_IO dummy; // Use the standard notation for double numbers
141 
142  GERBER_PLOTTER plotter;
143 
144  // Gerber drill file imply X2 format:
145  plotter.UseX2format( true );
146  plotter.UseX2NetAttributes( true );
147  plotter.DisableApertMacros( false );
148 
149  // Add the standard X2 header, without FileFunction
150  AddGerberX2Header( &plotter, m_pcb );
151  plotter.SetViewport( m_offset, IU_PER_MILS/10, /* scale */ 1.0, /* mirror */false );
152 
153  // has meaning only for gerber plotter. Must be called only after SetViewport
154  plotter.SetGerberCoordinatesFormat( 6 );
155  plotter.SetCreator( wxT( "PCBNEW" ) );
156 
157  // Add the standard X2 FileFunction for drill files
158  // %TF.FileFunction,Plated[NonPlated],layer1num,layer2num,PTH[NPTH][Blind][Buried],Drill[Route][Mixed]*%
159  wxString text = BuildFileFunctionAttributeString( aLayerPair,
160  aIsNpth
161  ? TYPE_FILE::NPTH_FILE
162  : TYPE_FILE::PTH_FILE );
163  plotter.AddLineToHeader( text );
164 
165  // Add file polarity (positive)
166  text = "%TF.FilePolarity,Positive*%";
167  plotter.AddLineToHeader( text );
168 
169  if( !plotter.OpenFile( aFullFilename ) )
170  return -1;
171 
172  plotter.StartPlot();
173 
174  holes_count = 0;
175 
176  wxPoint hole_pos;
177  bool last_item_is_via = true; // a flag to clear object attributes when a via hole is created.
178 
179  for( unsigned ii = 0; ii < m_holeListBuffer.size(); ii++ )
180  {
181  HOLE_INFO& hole_descr = m_holeListBuffer[ii];
182  hole_pos = hole_descr.m_Hole_Pos;
183 
184  // Manage the aperture attributes: in drill files 3 attributes can be used:
185  // "ViaDrill", only for vias, not pads
186  // "ComponentDrill", only for Through Holes pads
187  // "Slot" for oblong holes;
188  GBR_METADATA gbr_metadata;
189 
190  if( dyn_cast<const PCB_VIA*>( hole_descr.m_ItemParent ) )
191  {
193 
194  if( !last_item_is_via )
195  {
196  // be sure the current object attribute is cleared for vias
197  plotter.EndBlock( nullptr );
198  }
199 
200  last_item_is_via = true;
201  }
202  else if( dyn_cast<const PAD*>( hole_descr.m_ItemParent ) )
203  {
204  last_item_is_via = false;
205  const PAD* pad = dyn_cast<const PAD*>( hole_descr.m_ItemParent );
206 
207  if( pad->GetProperty() == PAD_PROP::CASTELLATED )
208  {
210  }
211  else
212  {
213  // Good practice of oblong pad holes (slots) is to use a specific aperture for
214  // routing, not used in drill commands.
215  if( hole_descr.m_Hole_Shape )
217  else
219  }
220 
221  // Add object attribute: component reference to pads (mainly useful for users)
222  wxString ref = pad->GetParent()->GetReference();
223 
224  gbr_metadata.SetCmpReference( ref );
226  }
227 
228  if( hole_descr.m_Hole_Shape )
229  {
230 #if FLASH_OVAL_HOLE // set to 1 to use flashed oblong holes,
231  // 0 to draw them as a line.
232  plotter.FlashPadOval( hole_pos, hole_descr.m_Hole_Size,
233  hole_descr.m_Hole_Orient, FILLED, &gbr_metadata );
234 #else
235  // Use routing for oblong hole (Slots)
236  wxPoint start, end;
237  convertOblong2Segment( hole_descr.m_Hole_Size, hole_descr.m_Hole_Orient, start, end );
238  int width = std::min( hole_descr.m_Hole_Size.x, hole_descr.m_Hole_Size.y );
239 
240  if ( width == 0 )
241  continue;
242 
243  plotter.ThickSegment( start+hole_pos, end+hole_pos, width, FILLED, &gbr_metadata );
244 #endif
245  }
246  else
247  {
248  int diam = std::min( hole_descr.m_Hole_Size.x, hole_descr.m_Hole_Size.y );
249  plotter.FlashPadCircle( hole_pos, diam, FILLED, &gbr_metadata );
250  }
251 
252  holes_count++;
253  }
254 
255  plotter.EndPlot();
256 
257  return holes_count;
258 }
259 
260 
261 #if !FLASH_OVAL_HOLE
262 void convertOblong2Segment( wxSize aSize, double aOrient, wxPoint& aStart, wxPoint& aEnd )
263 {
264  wxSize size( aSize );
265  double orient = aOrient;
266 
267  /* The pad will be drawn as an oblong shape with size.y > size.x
268  * (Oval vertical orientation 0)
269  */
270  if( size.x > size.y )
271  {
272  std::swap( size.x, size.y );
273  orient = AddAngles( orient, 900 );
274  }
275 
276  int deltaxy = size.y - size.x; // distance between centers of the oval
277 
278  int cx = 0;
279  int cy = deltaxy / 2;
280  RotatePoint( &cx, &cy, orient );
281  aStart = wxPoint( cx, cy );
282  cx = 0; cy = -deltaxy / 2;
283  RotatePoint( &cx, &cy, orient );
284  aEnd = wxPoint( cx, cy );
285 }
286 #endif
287 
288 
289 void GERBER_WRITER::SetFormat( int aRightDigits )
290 {
291  /* Set conversion scale depending on drill file units */
292  m_conversionUnits = 1.0 / IU_PER_MM; // Gerber units = mm
293 
294  // Set precision (unit is mm).
295  m_precision.m_Lhs = 4;
296  m_precision.m_Rhs = aRightDigits == 6 ? 6 : 5;
297 }
298 
299 
300 const wxString GERBER_WRITER::getDrillFileName( DRILL_LAYER_PAIR aPair, bool aNPTH,
301  bool aMerge_PTH_NPTH ) const
302 {
303  // Gerber files extension is always .gbr.
304  // Therefore, to mark drill files, add "-drl" to the filename.
305  wxFileName fname( GENDRILL_WRITER_BASE::getDrillFileName( aPair, aNPTH, aMerge_PTH_NPTH ) );
306  fname.SetName( fname.GetName() + "-drl" );
307 
308  return fname.GetFullPath();
309 }
Handle special data (items attributes) during plot.
BOARD_ITEM * m_ItemParent
virtual const wxString getDrillFileName(DRILL_LAYER_PAIR aPair, bool aNPTH, bool aMerge_PTH_NPTH) const
Plot settings, and plotting engines (PostScript, Gerber, HPGL and DXF)
virtual void SetCreator(const wxString &aCreator)
Definition: plotter.h:174
void UseX2NetAttributes(bool aEnable)
aperture used for flashed cmp position in placement files.
Definition: gbr_metadata.h:143
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:40
virtual void EndBlock(void *aData) override
Define the end of a group of drawing items the group is started by StartBlock().
print info associated to a component (TO.C attribute)
Plotting engines (PostScript, Gerber, HPGL and DXF)
static constexpr double IU_PER_MM
Mock up a conversion function.
virtual void ThickSegment(const wxPoint &start, const wxPoint &end, int width, OUTLINE_MODE tracemode, void *aData) override
virtual bool OpenFile(const wxString &aFullFilename)
Open or create the plot file aFullFilename.
Definition: plotter.cpp:76
void CreateMapFilesSet(const wxString &aPlotDirectory, REPORTER *aReporter=nullptr)
Create the full set of map files for the board, in PS, PDF ...
void SetNetAttribType(int aNetAttribType)
Definition: gbr_metadata.h:219
void AddGerberX2Header(PLOTTER *aPlotter, const BOARD *aBoard, bool aUseX1CompatibilityMode)
Calculate some X2 attributes as defined in the Gerber file format specification J4 (chapter 5) and ad...
Definition: pcbplot.cpp:282
void UseX2format(bool aEnable)
aperture used for via holes in drill files.
Definition: gbr_metadata.h:139
void SetFormat(int aRightDigits=6)
Initialize internal parameters to match the given format.
void AddLineToHeader(const wxString &aExtraString)
Add a line to the list of free lines to print at the beginning of the file.
Definition: plotter.h:183
std::vector< DRILL_LAYER_PAIR > getUniqueLayerPairs() const
Get unique layer pairs by examining the micro and blind_buried vias.
void RotatePoint(int *pX, int *pY, double angle)
Definition: trigo.cpp:228
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:64
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
virtual bool StartPlot() override
Write GERBER header to file initialize global variable g_Plot_PlotOutputFile.
Board plot function definition file.
static LIB_SYMBOL * dummy()
Used to draw a dummy shape when a LIB_SYMBOL is not found in library.
Definition: sch_symbol.cpp:71
T AddAngles(T a1, T2 a2)
Add two angles (keeping the result normalized). T2 is here.
Definition: trigo.h:335
aperture used for pad holes in drill files.
Definition: gbr_metadata.h:140
void CreateDrillandMapFilesSet(const wxString &aPlotDirectory, bool aGenDrill, bool aGenMap, REPORTER *aReporter=nullptr)
Create the full set of Excellon drill file for the board filenames are computed from the board name,...
const wxString BuildFileFunctionAttributeString(DRILL_LAYER_PAIR aLayerPair, TYPE_FILE aHoleType, bool aCompatNCdrill=false) const
virtual void SetViewport(const wxPoint &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
#define _(s)
Handle hole which must be drilled (diameter, position and layers).
std::pair< PCB_LAYER_ID, PCB_LAYER_ID > DRILL_LAYER_PAIR
Metadata which can be added in a gerber file as attribute in X2 format.
Definition: gbr_metadata.h:204
virtual void FlashPadOval(const wxPoint &aPadPos, const wxSize &size, double orient, OUTLINE_MODE trace_mode, void *aData) override
void buildHolesList(DRILL_LAYER_PAIR aLayerPair, bool aGenerateNPTH_list)
Create the list of holes and tools for a given board.
void DisableApertMacros(bool aDisable)
Disable Aperture Macro (AM) command, only for broken Gerber Readers.
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
virtual const wxString getDrillFileName(DRILL_LAYER_PAIR aPair, bool aNPTH, bool aMerge_PTH_NPTH) const override
virtual bool EndPlot() override
#define IU_PER_MILS
Definition: plotter.cpp:137
virtual void SetGerberCoordinatesFormat(int aResolution, bool aUseInches=false) override
Selection of Gerber units and resolution (number of digits in mantissa).
void SetApertureAttrib(GBR_APERTURE_METADATA::GBR_APERTURE_ATTRIB aApertAttribute)
Definition: gbr_metadata.h:209
a pad with a castellated through hole
virtual void FlashPadCircle(const wxPoint &pos, int diametre, OUTLINE_MODE trace_mode, void *aData) override
Filled circular flashes are stored as apertures.
Classes used in drill files, map files and report files generation.
GERBER_WRITER(BOARD *aPcb)
Definition: pad.h:57
std::vector< HOLE_INFO > m_holeListBuffer
void SetCmpReference(const wxString &aComponentRef)
Definition: gbr_metadata.h:241
int createDrillFile(wxString &aFullFilename, bool aIsNpth, DRILL_LAYER_PAIR aLayerPair)
Create an Excellon drill file.
Create drill maps and drill reports and drill files.