KiCad PCB EDA Suite
Loading...
Searching...
No Matches
place_file_exporter.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20/*
21 * 1 - create ascii/csv files for automatic placement of smd components
22 * 2 - create a footprint report (pos and footprint descr) (ascii file)
23 */
24
25#include <string_utils.h>
26#include <macros.h>
27#include <locale_io.h>
29#include <build_version.h>
31#include <footprint.h>
32#include <pad.h>
33
34#include <fmt/format.h>
35
36#include <wx/dirdlg.h>
37
38class LIST_MOD // An helper class used to build a list of useful footprints.
39{
40public:
41 FOOTPRINT* m_Footprint; // Link to the actual footprint
42 wxString m_Reference; // Its schematic reference
43 wxString m_Value; // Its schematic value
44 int m_Layer; // its side (B_Cu, or F_Cu)
45};
46
47
48// Defined values to write coordinates using inches or mm:
49static const double conv_unit_inch = 0.001 / pcbIUScale.IU_PER_MILS ; // units = in
50static const char unit_text_inch[] = "## Unit = inches, Angle = deg.\n";
51
52static const double conv_unit_mm = 1.0 / pcbIUScale.IU_PER_MM; // units = mm
53static const char unit_text_mm[] = "## Unit = mm, Angle = deg.\n";
54
55// Sort function use by GenerefootprintsPosition()
56// sort is made by side (layer) top layer first
57// then by reference increasing order
58static bool sortFPlist( const LIST_MOD& ref, const LIST_MOD& tst )
59{
60 if( ref.m_Layer == tst.m_Layer )
61 return StrNumCmp( ref.m_Reference, tst.m_Reference ) < 0;
62
63 return ref.m_Layer > tst.m_Layer;
64}
65
66
74
75PLACE_FILE_EXPORTER::PLACE_FILE_EXPORTER( BOARD* aBoard, bool aUnitsMM, bool aOnlySMD,
76 bool aExcludeAllTH, bool aExcludeDNP, bool aExcludeBOM,
77 bool aTopSide, bool aBottomSide, bool aFormatCSV,
78 bool aUseAuxOrigin, bool aNegateBottomX )
79{
80 m_board = aBoard;
81 m_unitsMM = aUnitsMM;
82 m_onlySMD = aOnlySMD;
83 m_excludeAllTH = aExcludeAllTH;
84 m_excludeDNP = aExcludeDNP;
85 m_excludeBOM = aExcludeBOM;
86 m_fpCount = 0;
87 m_negateBottomX = aNegateBottomX;
88
89 if( aTopSide && aBottomSide )
91 else if( aTopSide )
93 else if( aBottomSide )
95 else
97
98 m_formatCSV = aFormatCSV;
99
100 if( aUseAuxOrigin )
101 m_place_Offset = m_board->GetDesignSettings().GetAuxOrigin();
102 else
103 m_place_Offset = VECTOR2I( 0, 0 );
104}
105
106
108{
109 std::string buffer;
110 char line[1024]; // A line to print intermediate data
111 wxString wxLine; // wxString used for UTF-8 line
112
113 // Minimal text lengths:
114 m_fpCount = 0;
115 int lenRefText = 8;
116 int lenValText = 8;
117 int lenPkgText = 16;
118
119 // Calculating the number of useful footprints (CMS attribute, not VIRTUAL)
120 m_fpCount = 0;
121
122 // Select units:
123 double conv_unit = m_unitsMM ? conv_unit_mm : conv_unit_inch;
124 const char *unit_text = m_unitsMM ? unit_text_mm : unit_text_inch;
125
126 // Build and sort the list of footprints alphabetically
127 std::vector<LIST_MOD> list;
128
129 for( FOOTPRINT* footprint : m_board->Footprints() )
130 {
131 if( m_side != PCB_BOTH_SIDES )
132 {
133 if( footprint->GetLayer() == B_Cu && m_side != PCB_BACK_SIDE )
134 continue;
135 if( footprint->GetLayer() == F_Cu && m_side != PCB_FRONT_SIDE )
136 continue;
137 }
138
139 if( footprint->GetExcludedFromPosFilesForVariant( m_variant ) )
140 continue;
141
142 if( m_onlySMD && !( footprint->GetAttributes() & FP_SMD ) )
143 continue;
144
145 if( m_excludeAllTH && footprint->HasThroughHolePads() )
146 continue;
147
148 if( m_excludeDNP && footprint->GetDNPForVariant( m_variant ) )
149 continue;
150
151 if( m_excludeBOM && footprint->GetExcludedFromBOMForVariant( m_variant ) )
152 continue;
153
154 m_fpCount++;
155
156 LIST_MOD item;
157 item.m_Footprint = footprint;
158 item.m_Reference = footprint->Reference().GetShownText( false );
159 item.m_Value = UnescapeString( footprint->GetFieldValueForVariant( m_variant,
161 item.m_Layer = footprint->GetLayer();
162
163 lenRefText = std::max( lenRefText, (int) item.m_Reference.length() );
164 lenValText = std::max( lenValText, (int) item.m_Value.length() );
165 lenPkgText = std::max( lenPkgText, (int) item.m_Footprint->GetFPID().GetLibItemName().length() );
166
167 list.push_back( std::move( item ) );
168 }
169
170 if( list.size() > 1 )
171 sort( list.begin(), list.end(), sortFPlist );
172
173 // Switch the locale to standard C (needed to print floating point numbers)
174 LOCALE_IO toggle;
175
176 if( m_formatCSV )
177 {
178 wxChar csv_sep = ',';
179
180 // Set first line:;
181 snprintf( line, sizeof(line), "Ref%cVal%cPackage%cPosX%cPosY%cRot%cSide\n",
182 csv_sep, csv_sep, csv_sep, csv_sep, csv_sep, csv_sep );
183
184 buffer += line;
185
186 for( int ii = 0; ii < m_fpCount; ii++ )
187 {
188 VECTOR2I footprint_pos;
189 footprint_pos = list[ii].m_Footprint->GetPosition();
190 footprint_pos -= m_place_Offset;
191
192 int layer = list[ii].m_Footprint->GetLayer();
193 wxASSERT( IsExternalCopperLayer( layer ) );
194
195 if( layer == B_Cu && m_negateBottomX )
196 footprint_pos.x = - footprint_pos.x;
197
198 wxLine = wxT( "\"" ) + list[ii].m_Reference;
199 wxLine << wxT( "\"" ) << csv_sep;
200 wxLine << wxT( "\"" ) << list[ii].m_Value;
201 wxLine << wxT( "\"" ) << csv_sep;
202 wxLine << wxT( "\"" ) << list[ii].m_Footprint->GetFPID().GetLibItemName().wx_str();
203 wxLine << wxT( "\"" ) << csv_sep;
204
205 wxLine << wxString::Format( wxT( "%f%c%f%c%f" ),
206 footprint_pos.x * conv_unit,
207 csv_sep,
208 // Keep the Y axis oriented from bottom to top,
209 // ( change y coordinate sign )
210 -footprint_pos.y * conv_unit,
211 csv_sep,
212 list[ii].m_Footprint->GetOrientation().AsDegrees() );
213 wxLine << csv_sep;
214
215 wxLine << ( (layer == F_Cu ) ? PLACE_FILE_EXPORTER::GetFrontSideName()
217 wxLine << '\n';
218
219 buffer += TO_UTF8( wxLine );
220 }
221 }
222 else
223 {
224 // Write file header
225 snprintf( line, sizeof(line), "### Footprint positions - created on %s ###\n",
227
228 buffer += line;
229
230 wxString Title = GetBuildVersion();
231 snprintf( line, sizeof(line), "### Printed by KiCad version %s\n", TO_UTF8( Title ) );
232 buffer += line;
233
234 buffer += unit_text;
235 buffer += "## Side : ";
236
237 if( m_side == PCB_BACK_SIDE )
238 buffer += GetBackSideName();
239 else if( m_side == PCB_FRONT_SIDE )
240 buffer += GetFrontSideName();
241 else if( m_side == PCB_BOTH_SIDES )
242 buffer += "All";
243 else
244 buffer += "---";
245
246 buffer += "\n";
247
248 snprintf( line, sizeof(line), "%-*s %-*s %-*s %9.9s %9.9s %8.8s %s\n",
249 lenRefText, "# Ref",
250 lenValText, "Val",
251 lenPkgText, "Package",
252 "PosX", "PosY", "Rot", "Side" );
253 buffer += line;
254
255 for( int ii = 0; ii < m_fpCount; ii++ )
256 {
257 VECTOR2I footprint_pos;
258 footprint_pos = list[ii].m_Footprint->GetPosition();
259 footprint_pos -= m_place_Offset;
260
261 int layer = list[ii].m_Footprint->GetLayer();
262 wxASSERT( IsExternalCopperLayer( layer ) );
263
264 if( layer == B_Cu && m_negateBottomX )
265 footprint_pos.x = - footprint_pos.x;
266
267 wxString ref = list[ii].m_Reference;
268 wxString val = list[ii].m_Value;
269 wxString pkg = list[ii].m_Footprint->GetFPID().GetLibItemName();
270 ref.Replace( wxT( " " ), wxT( "_" ) );
271 val.Replace( wxT( " " ), wxT( "_" ) );
272 pkg.Replace( wxT( " " ), wxT( "_" ) );
273 wxLine.Printf( wxT( "%-*s %-*s %-*s %9.4f %9.4f %8.4f %s\n" ),
274 lenRefText, std::move( ref ),
275 lenValText, std::move( val ),
276 lenPkgText, std::move( pkg ),
277 footprint_pos.x * conv_unit,
278 // Keep the coordinates in the first quadrant, (i.e. change y sign)
279 -footprint_pos.y * conv_unit,
280 list[ii].m_Footprint->GetOrientation().AsDegrees(),
281 ( layer == F_Cu ) ? GetFrontSideName() : GetBackSideName() );
282 buffer += TO_UTF8( wxLine );
283 }
284
285 // Write EOF
286 buffer += "## End\n";
287 }
288
289 return buffer;
290}
291
292
294{
295 std::string buffer;
296
297 m_place_Offset = VECTOR2I( 0, 0 );
298
299 // Select units:
300 double conv_unit = m_unitsMM ? conv_unit_mm : conv_unit_inch;
301 const char *unit_text = m_unitsMM ? unit_text_mm : unit_text_inch;
302
303 LOCALE_IO toggle;
304
305 // Generate header file comments.)
306
307 buffer += fmt::format( "## Footprint report - date {}\n", TO_UTF8( GetISO8601CurrentDateTime() ) );
308
309 wxString Title = GetBuildVersion();
310 buffer += fmt::format( "## Printed by KiCad version {}\n", TO_UTF8( Title ) );
311
312 buffer += unit_text;
313
314 buffer += "\n$BeginDESCRIPTION\n";
315
316 BOX2I bbbox = m_board->ComputeBoundingBox( false, true );
317
318 buffer += "\n$BOARD\n";
319
320 buffer += fmt::format( "upper_left_corner {:9.6f} {:9.6f}\n",
321 bbbox.GetX() * conv_unit,
322 bbbox.GetY() * conv_unit );
323
324 buffer += "$EndBOARD\n\n";
325
326 std::vector<FOOTPRINT*> sortedFootprints;
327
328 for( FOOTPRINT* footprint : m_board->Footprints() )
329 sortedFootprints.push_back( footprint );
330
331 std::sort( sortedFootprints.begin(), sortedFootprints.end(),
332 []( FOOTPRINT* a, FOOTPRINT* b ) -> bool
333 {
334 return StrNumCmp( a->GetReference(), b->GetReference(), true ) < 0;
335 });
336
337 for( FOOTPRINT* footprint : sortedFootprints )
338 {
339 wxString ref = footprint->Reference().GetShownText( false );
340 wxString value = UnescapeString(
341 footprint->GetFieldValueForVariant( m_variant,
343
344 buffer += fmt::format( "$MODULE {}\n", TO_UTF8( ref ) );
345
346 buffer += fmt::format( "reference {}\n", TO_UTF8( ref ) );
347 buffer += fmt::format( "value {}\n", TO_UTF8( value ) );
348 buffer += fmt::format( "footprint {}\n", footprint->GetFPID().Format().c_str() );
349
350 buffer += "attribut";
351
352 if(( footprint->GetAttributes() & ( FP_THROUGH_HOLE | FP_SMD ) ) == 0 )
353 buffer += " virtual";
354
355 if( footprint->GetAttributes() & FP_SMD )
356 buffer += " smd";
357
358 if( footprint->GetAttributes() & FP_THROUGH_HOLE )
359 buffer += " none";
360
361 buffer += "\n";
362
363 VECTOR2I footprint_pos = footprint->GetPosition();
364 footprint_pos -= m_place_Offset;
365
366 buffer += fmt::format( "position {:9.6f} {:9.6f} orientation {:.2f}\n",
367 footprint_pos.x * conv_unit,
368 footprint_pos.y * conv_unit,
369 footprint->GetOrientation().AsDegrees() );
370
371 if( footprint->GetLayer() == F_Cu )
372 buffer += "layer front\n";
373 else if( footprint->GetLayer() == B_Cu )
374 buffer += "layer back\n";
375 else
376 buffer += "layer other\n";
377
378 std::vector<PAD*> sortedPads;
379
380 for( PAD* pad : footprint->Pads() )
381 sortedPads.push_back( pad );
382
383 std::sort( sortedPads.begin(), sortedPads.end(),
384 []( PAD* a, PAD* b ) -> bool
385 {
386 return StrNumCmp( a->GetNumber(), b->GetNumber(), true ) < 0;
387 });
388
389 for( PAD* pad : sortedPads )
390 {
391 buffer += fmt::format( "$PAD \"{}\"\n", TO_UTF8( pad->GetNumber() ) );
392
393 int layer = 0;
394
395 if( pad->GetLayerSet()[B_Cu] )
396 layer = 1;
397
398 if( pad->GetLayerSet()[F_Cu] )
399 layer |= 2;
400
401 // TODO(JE) padstacks
402 static const char* layer_name[4] = { "nocopper", "back", "front", "both" };
403 buffer += fmt::format( "Shape {} Layer {}\n",
404 TO_UTF8( pad->ShowLegacyPadShape( PADSTACK::ALL_LAYERS ) ),
405 layer_name[layer] );
406
407 VECTOR2I padPos = pad->GetFPRelativePosition();
408
409 buffer += fmt::format( "position {:9.6f} {:9.6f} size {:9.6f} {:9.6f} orientation {:.2f}\n",
410 padPos.x * conv_unit,
411 padPos.y * conv_unit,
412 pad->GetSize( PADSTACK::ALL_LAYERS ).x * conv_unit,
413 pad->GetSize( PADSTACK::ALL_LAYERS ).y * conv_unit,
414 pad->GetOrientation().AsDegrees() );
415
416 buffer += fmt::format( "drill {:9.6f}\n", pad->GetDrillSize().x * conv_unit );
417
418 buffer += fmt::format( "shape_offset {:9.6f} {:9.6f}\n",
419 pad->GetOffset( PADSTACK::ALL_LAYERS ).x * conv_unit,
420 pad->GetOffset( PADSTACK::ALL_LAYERS ).y * conv_unit );
421
422 buffer += "$EndPAD\n";
423 }
424
425 buffer += fmt::format( "$EndMODULE {}\n\n", TO_UTF8( ref ) );
426 }
427
428 // Generate EOF.
429 buffer += "$EndDESCRIPTION\n";
430
431 return buffer;
432}
433
434
435wxString PLACE_FILE_EXPORTER::DecorateFilename( const wxString& aBaseName, bool aFront, bool aBack )
436{
437 if( aFront && aBack )
438 return aBaseName + wxT( "-" ) + wxT( "all" );
439 else if( aFront )
440 return aBaseName + wxT( "-" ) + GetFrontSideName();
441 else if( aBack )
442 return aBaseName + wxT( "-" ) + GetBackSideName();
443 else
444 return aBaseName;
445}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:121
BOX2< VECTOR2I > BOX2I
Definition box2.h:918
wxString GetBuildVersion()
Get the full KiCad version string.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:372
constexpr coord_type GetY() const
Definition box2.h:204
constexpr coord_type GetX() const
Definition box2.h:203
const LIB_ID & GetFPID() const
Definition footprint.h:441
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
FOOTPRINT * m_Footprint
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition locale_io.h:37
static constexpr PCB_LAYER_ID ALL_LAYERS
! Temporary layer identifier to identify code that is not padstack-aware
Definition padstack.h:177
Definition pad.h:61
PLACE_FILE_EXPORTER(BOARD *aBoard, bool aUnitsMM, bool aOnlySMD, bool aExcludeAllTH, bool aExcludeDNP, bool aExcludeBOM, bool aTopSide, bool aBottomSide, bool aFormatCSV, bool aUseAuxOrigin, bool aNegateBottomX)
Create a PLACE_FILE_EXPORTER.
static std::string GetFrontSideName()
static wxString DecorateFilename(const wxString &aBaseName, bool aFront, bool aBack)
std::string GenPositionData()
build a string filled with the position data
static std::string GetBackSideName()
std::string GenReportData()
build a string filled with the pad report data This report does not used options aForceSmdItems,...
std::string::size_type length() const
Definition utf8.h:111
@ FP_SMD
Definition footprint.h:84
@ FP_THROUGH_HOLE
Definition footprint.h:83
bool IsExternalCopperLayer(int aLayerId)
Test whether a layer is an external (F_Cu or B_Cu) copper layer.
Definition layer_ids.h:686
@ B_Cu
Definition layer_ids.h:61
@ F_Cu
Definition layer_ids.h:60
This file contains miscellaneous commonly used macros and functions.
static const double conv_unit_mm
static bool sortFPlist(const LIST_MOD &ref, const LIST_MOD &tst)
static const double conv_unit_inch
static const char unit_text_mm[]
@ PCB_BACK_SIDE
@ PCB_BOTH_SIDES
@ PCB_FRONT_SIDE
static const char unit_text_inch[]
int StrNumCmp(const wxString &aString1, const wxString &aString2, bool aIgnoreCase)
Compare two strings with alphanumerical content.
wxString UnescapeString(const wxString &aSource)
wxString GetISO8601CurrentDateTime()
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
@ VALUE
Field Value of part, i.e. "3.3K".
wxString GetCanonicalFieldName(FIELD_T aFieldType)
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683