You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

508 lines
15 KiB

// Dick Hollenbeck's KiROUND R&D // This provides better project control over rounding to int from double // than wxRound() did. This scheme provides better logging in Debug builds // and it provides for compile time calculation of constants. #include <stdio.h> #include <assert.h> #include <limits.h> //-----<KiROUND KIT>------------------------------------------------------------ /** * KiROUND * rounds a floating point number to an int using * "round halfway cases away from zero". * In Debug build an assert fires if will not fit into an int. */ #if defined( DEBUG ) // DEBUG: a macro to capture line and file, then calls this inline static inline int KiRound( double v, int line, const char* filename ) { v = v < 0 ? v - 0.5 : v + 0.5; if( v > INT_MAX + 0.5 ) { printf( "%s: in file %s on line %d, val: %.16g too ' > 0 ' for int\n", __FUNCTION__, filename, line, v ); } else if( v < INT_MIN - 0.5 ) { printf( "%s: in file %s on line %d, val: %.16g too ' < 0 ' for int\n", __FUNCTION__, filename, line, v ); } return int( v ); } #define KiROUND( v ) KiRound( v, __LINE__, __FILE__ ) #else // RELEASE: a macro so compile can pre-compute constants. #define KiROUND( v ) int( (v) < 0 ? (v) - 0.5 : (v) + 0.5 ) #endif //-----</KiROUND KIT>----------------------------------------------------------- // Only a macro is compile time calculated, an inline function causes a static constructor // in a situation like this. // Therefore the Release build is best done with a MACRO not an inline function. int Computed = KiROUND( 14.3 * 8 ); int main( int argc, char** argv ) { for( double d = double(INT_MAX)-1; d < double(INT_MAX)+8; d += 2.0 ) { int i = KiROUND( d ); printf( "t: %d %.16g\n", i, d ); } return 0; }
14 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2017 jean-pierre.charras
  5. * Copyright The 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. #include "bitmap_base.h"
  25. #include <gr_basic.h>
  26. #include <math/util.h> // for KiROUND
  27. #include <memory> // for make_unique, unique_ptr
  28. #include <plotters/plotter.h>
  29. #include <richio.h>
  30. #include <wx/bitmap.h> // for wxBitmap
  31. #include <wx/mstream.h>
  32. #include <wx/stream.h> // for wxInputStream, wxOutputStream
  33. #include <wx/string.h> // for wxString
  34. #include <wx/wfstream.h> // for wxFileInputStream
  35. BITMAP_BASE::BITMAP_BASE( const VECTOR2I& pos )
  36. {
  37. m_scale = 1.0; // 1.0 = original bitmap size
  38. m_imageType = wxBITMAP_TYPE_INVALID;
  39. m_bitmap = nullptr;
  40. m_image = nullptr;
  41. m_originalImage = nullptr;
  42. m_ppi = 300; // the bitmap definition. the default is 300PPI
  43. m_pixelSizeIu = 254000.0 / m_ppi; // a pixel size value OK for bitmaps using 300 PPI
  44. // for Eeschema which uses currently 254000PPI
  45. m_isMirroredX = false;
  46. m_isMirroredY = false;
  47. m_rotation = ANGLE_0;
  48. }
  49. BITMAP_BASE::BITMAP_BASE( const BITMAP_BASE& aSchBitmap )
  50. {
  51. m_scale = aSchBitmap.m_scale;
  52. m_ppi = aSchBitmap.m_ppi;
  53. m_pixelSizeIu = aSchBitmap.m_pixelSizeIu;
  54. m_isMirroredX = aSchBitmap.m_isMirroredX;
  55. m_isMirroredY = aSchBitmap.m_isMirroredY;
  56. m_rotation = aSchBitmap.m_rotation;
  57. m_imageType = aSchBitmap.m_imageType;
  58. m_image = nullptr;
  59. m_bitmap = nullptr;
  60. m_originalImage = nullptr;
  61. if( aSchBitmap.m_image )
  62. {
  63. m_image = new wxImage( *aSchBitmap.m_image );
  64. m_bitmap = new wxBitmap( *m_image );
  65. m_originalImage = new wxImage( *aSchBitmap.m_originalImage );
  66. m_imageType = aSchBitmap.m_imageType;
  67. m_imageData = aSchBitmap.m_imageData;
  68. m_imageId = aSchBitmap.m_imageId;
  69. }
  70. }
  71. void BITMAP_BASE::rebuildBitmap( bool aResetID )
  72. {
  73. if( m_bitmap )
  74. delete m_bitmap;
  75. m_bitmap = new wxBitmap( *m_image );
  76. if( aResetID )
  77. m_imageId = KIID();
  78. }
  79. void BITMAP_BASE::updatePPI()
  80. {
  81. // Todo: eventually we need to support dpi / scaling in both dimensions
  82. int dpiX = m_originalImage->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
  83. if( dpiX > 1 )
  84. {
  85. if( m_originalImage->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT ) == wxIMAGE_RESOLUTION_CM )
  86. m_ppi = KiROUND( dpiX * 2.54 );
  87. else
  88. m_ppi = dpiX;
  89. }
  90. }
  91. void BITMAP_BASE::ImportData( BITMAP_BASE& aItem )
  92. {
  93. *m_image = *aItem.m_image;
  94. *m_bitmap = *aItem.m_bitmap;
  95. *m_originalImage = *aItem.m_originalImage;
  96. m_imageId = aItem.m_imageId;
  97. m_scale = aItem.m_scale;
  98. m_ppi = aItem.m_ppi;
  99. m_pixelSizeIu = aItem.m_pixelSizeIu;
  100. m_isMirroredX = aItem.m_isMirroredX;
  101. m_isMirroredY = aItem.m_isMirroredY;
  102. m_rotation = aItem.m_rotation;
  103. m_imageType = aItem.m_imageType;
  104. m_imageData = aItem.m_imageData;
  105. }
  106. bool BITMAP_BASE::ReadImageFile( wxInputStream& aInStream )
  107. {
  108. // Store the original image data in m_imageData
  109. size_t dataSize = aInStream.GetLength();
  110. m_imageData.SetBufSize( dataSize );
  111. aInStream.Read( m_imageData.GetData(), dataSize );
  112. m_imageData.SetDataLen( dataSize );
  113. std::unique_ptr<wxImage> new_image = std::make_unique<wxImage>();
  114. // Load the image from the stream into new_image
  115. wxMemoryInputStream mem_stream( m_imageData.GetData(), dataSize );
  116. if( !new_image->LoadFile( mem_stream ) )
  117. return false;
  118. return SetImage( *new_image );
  119. }
  120. bool BITMAP_BASE::ReadImageFile( wxMemoryBuffer& aBuf )
  121. {
  122. // Store the original image data in m_imageData
  123. m_imageData = aBuf;
  124. std::unique_ptr<wxImage> new_image = std::make_unique<wxImage>();
  125. // Load the image from the buffer into new_image
  126. wxMemoryInputStream mem_stream( m_imageData.GetData(), m_imageData.GetBufSize() );
  127. if( !new_image->LoadFile( mem_stream ) )
  128. return false;
  129. return SetImage( *new_image );
  130. }
  131. bool BITMAP_BASE::ReadImageFile(const wxString& aFullFilename)
  132. {
  133. wxFileInputStream file_stream(aFullFilename);
  134. // Check if the file could be opened successfully
  135. if (!file_stream.IsOk())
  136. return false;
  137. return ReadImageFile(file_stream);
  138. }
  139. bool BITMAP_BASE::SetImage( const wxImage& aImage )
  140. {
  141. if( !aImage.IsOk() || aImage.GetWidth() == 0 || aImage.GetHeight() == 0 )
  142. return false;
  143. delete m_image;
  144. m_image = new wxImage( aImage );
  145. // Create a new wxImage object from m_image
  146. delete m_originalImage;
  147. m_originalImage = new wxImage( *m_image );
  148. rebuildBitmap();
  149. updatePPI();
  150. return true;
  151. }
  152. bool BITMAP_BASE::SaveImageData( wxOutputStream& aOutStream ) const
  153. {
  154. if( m_imageData.IsEmpty() )
  155. {
  156. // If m_imageData is empty, use wxImage::Save() method to write m_image contents to
  157. // the stream.
  158. wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG
  159. : wxBITMAP_TYPE_PNG;
  160. if( !m_image->SaveFile( aOutStream, type ) )
  161. {
  162. return false;
  163. }
  164. }
  165. else
  166. {
  167. // Write the contents of m_imageData to the stream.
  168. aOutStream.Write( m_imageData.GetData(), m_imageData.GetDataLen() );
  169. }
  170. return true;
  171. }
  172. bool BITMAP_BASE::LoadLegacyData( LINE_READER& aLine, wxString& aErrorMsg )
  173. {
  174. wxMemoryOutputStream stream;
  175. char* line;
  176. while( true )
  177. {
  178. if( !aLine.ReadLine() )
  179. {
  180. aErrorMsg = wxT( "Unexpected end of data" );
  181. return false;
  182. }
  183. line = aLine.Line();
  184. if( strncasecmp( line, "EndData", 4 ) == 0 )
  185. {
  186. // all the PNG date is read.
  187. // We expect here m_image and m_bitmap are void
  188. m_image = new wxImage();
  189. wxMemoryInputStream istream( stream );
  190. m_image->LoadFile( istream, wxBITMAP_TYPE_ANY );
  191. m_bitmap = new wxBitmap( *m_image );
  192. m_originalImage = new wxImage( *m_image );
  193. updateImageDataBuffer();
  194. break;
  195. }
  196. // Read PNG data, stored in hexadecimal,
  197. // each byte = 2 hexadecimal digits and a space between 2 bytes
  198. // and put it in memory stream buffer
  199. int len = strlen( line );
  200. for( ; len > 0; len -= 3, line += 3 )
  201. {
  202. int value = 0;
  203. if( sscanf( line, "%X", &value ) == 1 )
  204. stream.PutC( (char) value );
  205. else
  206. break;
  207. }
  208. }
  209. return true;
  210. }
  211. const BOX2I BITMAP_BASE::GetBoundingBox() const
  212. {
  213. BOX2I bbox;
  214. VECTOR2I size = GetSize();
  215. bbox.Inflate( size.x / 2, size.y / 2 );
  216. return bbox;
  217. }
  218. void BITMAP_BASE::DrawBitmap( wxDC* aDC, const VECTOR2I& aPos,
  219. const KIGFX::COLOR4D& aBackgroundColor ) const
  220. {
  221. if( m_bitmap == nullptr )
  222. return;
  223. VECTOR2I pos = aPos;
  224. VECTOR2I size = GetSize();
  225. // This fixes a bug in OSX that should be fixed in the 3.0.3 version or later.
  226. if( ( size.x == 0 ) || ( size.y == 0 ) )
  227. return;
  228. // To draw the bitmap, pos is the upper left corner position
  229. pos.x -= size.x / 2;
  230. pos.y -= size.y / 2;
  231. double scale;
  232. int logicalOriginX, logicalOriginY;
  233. aDC->GetUserScale( &scale, &scale );
  234. aDC->GetLogicalOrigin( &logicalOriginX, &logicalOriginY );
  235. // We already have issues to draw a bitmap on the wxDC, depending on wxWidgets version.
  236. // Now we have an issue on wxWidgets 3.1.6 to fix the clip area
  237. // and the bitmap position when using TransformMatrix
  238. // So for version == 3.1.6 do not use it
  239. // Be careful before changing the code.
  240. bool useTransform = aDC->CanUseTransformMatrix();
  241. wxAffineMatrix2D init_matrix = aDC->GetTransformMatrix();
  242. // Note: clipping bitmap area was made to fix a minor issue in old versions of
  243. // KiCad/wxWidgets (5.1 / wx 3.0)
  244. // However SetClippingRegion creates a lot of issues (different ways to fix the
  245. // position and size of the area, depending on wxWidgets version)because it changes with
  246. // each versions of wxWidgets, so it is now disabled
  247. // However the code is still here, just in case
  248. // #define USE_CLIP_AREA
  249. wxPoint clipAreaPos;
  250. if( useTransform )
  251. {
  252. wxAffineMatrix2D matrix = aDC->GetTransformMatrix();
  253. matrix.Translate( pos.x, pos.y );
  254. matrix.Scale( GetScalingFactor(), GetScalingFactor() );
  255. aDC->SetTransformMatrix( matrix );
  256. // Needed on wx <= 3.1.5, and this is strange...
  257. // Nevertheless, this code has problem (the bitmap is not seen)
  258. // with wx version > 3.1.5
  259. clipAreaPos.x = pos.x;
  260. clipAreaPos.y = pos.y;
  261. pos.x = pos.y = 0;
  262. }
  263. else
  264. {
  265. aDC->SetUserScale( scale * GetScalingFactor(), scale * GetScalingFactor() );
  266. aDC->SetLogicalOrigin( logicalOriginX / GetScalingFactor(),
  267. logicalOriginY / GetScalingFactor() );
  268. pos.x = KiROUND( pos.x / GetScalingFactor() );
  269. pos.y = KiROUND( pos.y / GetScalingFactor() );
  270. size.x = KiROUND( size.x / GetScalingFactor() );
  271. size.y = KiROUND( size.y / GetScalingFactor() );
  272. clipAreaPos.x = pos.x;
  273. clipAreaPos.y = pos.y;
  274. }
  275. #ifdef USE_CLIP_AREA
  276. aDC->DestroyClippingRegion();
  277. aDC->SetClippingRegion( clipAreaPos, wxSize( size.x, size.y ) );
  278. #endif
  279. if( aBackgroundColor != COLOR4D::UNSPECIFIED && m_bitmap->HasAlpha() )
  280. {
  281. // Most printers don't support transparent images properly,
  282. // so blend the image with background color.
  283. int w = m_bitmap->GetWidth();
  284. int h = m_bitmap->GetHeight();
  285. wxImage image( w, h );
  286. wxColour bgColor = aBackgroundColor.ToColour();
  287. image.SetRGB( wxRect( 0, 0, w, h ), bgColor.Red(), bgColor.Green(), bgColor.Blue() );
  288. image.Paste( m_bitmap->ConvertToImage(), 0, 0, wxIMAGE_ALPHA_BLEND_COMPOSE );
  289. if( GetGRForceBlackPenState() )
  290. image = image.ConvertToGreyscale();
  291. aDC->DrawBitmap( wxBitmap( image ), pos.x, pos.y, true );
  292. }
  293. else if( GetGRForceBlackPenState() )
  294. {
  295. wxBitmap result( m_bitmap->ConvertToImage().ConvertToGreyscale() );
  296. aDC->DrawBitmap( result, pos.x, pos.y, true );
  297. }
  298. else
  299. {
  300. aDC->DrawBitmap( *m_bitmap, pos.x, pos.y, true );
  301. }
  302. if( useTransform )
  303. aDC->SetTransformMatrix( init_matrix );
  304. else
  305. {
  306. aDC->SetUserScale( scale, scale );
  307. aDC->SetLogicalOrigin( logicalOriginX, logicalOriginY );
  308. }
  309. #ifdef USE_CLIP_AREA
  310. aDC->DestroyClippingRegion();
  311. #endif
  312. }
  313. VECTOR2I BITMAP_BASE::GetSize() const
  314. {
  315. VECTOR2I size;
  316. if( m_bitmap )
  317. {
  318. size.x = m_bitmap->GetWidth();
  319. size.y = m_bitmap->GetHeight();
  320. size.x = KiROUND( size.x * GetScalingFactor() );
  321. size.y = KiROUND( size.y * GetScalingFactor() );
  322. }
  323. return size;
  324. }
  325. void BITMAP_BASE::Mirror( FLIP_DIRECTION aFlipDirection )
  326. {
  327. if( m_image )
  328. {
  329. // wxImage::Mirror() clear some parameters of the original image.
  330. // We need to restore them, especially resolution and unit, to be
  331. // sure image parameters saved in file are the right parameters, not
  332. // the default values
  333. int resX = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
  334. int resY = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY );
  335. int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
  336. *m_image = m_image->Mirror( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT );
  337. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT , unit);
  338. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX);
  339. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY);
  340. if( aFlipDirection == FLIP_DIRECTION::TOP_BOTTOM )
  341. m_isMirroredY = !m_isMirroredY;
  342. else
  343. m_isMirroredX = !m_isMirroredX;
  344. rebuildBitmap( false );
  345. updateImageDataBuffer();
  346. }
  347. }
  348. void BITMAP_BASE::Rotate( bool aRotateCCW )
  349. {
  350. if( m_image )
  351. {
  352. // wxImage::Rotate90() clear some parameters of the original image.
  353. // We need to restore them, especially resolution and unit, to be
  354. // sure image parameters saved in file are the right parameters, not
  355. // the default values
  356. int resX = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
  357. int resY = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY );
  358. int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
  359. *m_image = m_image->Rotate90( aRotateCCW );
  360. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT, unit );
  361. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX );
  362. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY );
  363. m_rotation += ( aRotateCCW ? ANGLE_90 : -ANGLE_90 );
  364. rebuildBitmap( false );
  365. updateImageDataBuffer();
  366. }
  367. }
  368. void BITMAP_BASE::ConvertToGreyscale()
  369. {
  370. if( m_image )
  371. {
  372. *m_image = m_image->ConvertToGreyscale();
  373. *m_originalImage = m_originalImage->ConvertToGreyscale();
  374. rebuildBitmap();
  375. updateImageDataBuffer();
  376. }
  377. }
  378. void BITMAP_BASE::PlotImage( PLOTTER* aPlotter, const VECTOR2I& aPos,
  379. const COLOR4D& aDefaultColor,
  380. int aDefaultPensize ) const
  381. {
  382. if( m_image == nullptr )
  383. return;
  384. // These 2 lines are useful only for plotters that cannot plot a bitmap
  385. // and plot a rectangle instead of.
  386. aPlotter->SetColor( aDefaultColor );
  387. aPlotter->SetCurrentLineWidth( aDefaultPensize );
  388. aPlotter->PlotImage( *m_image, aPos, GetScalingFactor() );
  389. }
  390. void BITMAP_BASE::updateImageDataBuffer()
  391. {
  392. if( m_image )
  393. {
  394. wxMemoryOutputStream stream;
  395. wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG
  396. : wxBITMAP_TYPE_PNG;
  397. if( !m_image->SaveFile( stream, type ) )
  398. return;
  399. m_imageData.GetWriteBuf( stream.GetLength() );
  400. stream.CopyTo( m_imageData.GetData(), stream.GetLength() );
  401. m_imageData.SetDataLen( stream.GetLength() );
  402. }
  403. }