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.

504 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 (C) 2011-2024 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 the stream.
  157. wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG;
  158. if( !m_image->SaveFile( aOutStream, type ) )
  159. {
  160. return false;
  161. }
  162. }
  163. else
  164. {
  165. // Write the contents of m_imageData to the stream.
  166. aOutStream.Write( m_imageData.GetData(), m_imageData.GetBufSize() );
  167. }
  168. return true;
  169. }
  170. bool BITMAP_BASE::LoadLegacyData( LINE_READER& aLine, wxString& aErrorMsg )
  171. {
  172. wxMemoryOutputStream stream;
  173. char* line;
  174. while( true )
  175. {
  176. if( !aLine.ReadLine() )
  177. {
  178. aErrorMsg = wxT("Unexpected end of data");
  179. return false;
  180. }
  181. line = aLine.Line();
  182. if( strncasecmp( line, "EndData", 4 ) == 0 )
  183. {
  184. // all the PNG date is read.
  185. // We expect here m_image and m_bitmap are void
  186. m_image = new wxImage();
  187. wxMemoryInputStream istream( stream );
  188. m_image->LoadFile( istream, wxBITMAP_TYPE_ANY );
  189. m_bitmap = new wxBitmap( *m_image );
  190. m_originalImage = new wxImage( *m_image );
  191. UpdateImageDataBuffer();
  192. break;
  193. }
  194. // Read PNG data, stored in hexadecimal,
  195. // each byte = 2 hexadecimal digits and a space between 2 bytes
  196. // and put it in memory stream buffer
  197. int len = strlen( line );
  198. for( ; len > 0; len -= 3, line += 3 )
  199. {
  200. int value = 0;
  201. if( sscanf( line, "%X", &value ) == 1 )
  202. stream.PutC( (char) value );
  203. else
  204. break;
  205. }
  206. }
  207. return true;
  208. }
  209. const BOX2I BITMAP_BASE::GetBoundingBox() const
  210. {
  211. BOX2I bbox;
  212. VECTOR2I size = GetSize();
  213. bbox.Inflate( size.x / 2, size.y / 2 );
  214. return bbox;
  215. }
  216. void BITMAP_BASE::DrawBitmap( wxDC* aDC, const VECTOR2I& aPos,
  217. const KIGFX::COLOR4D& aBackgroundColor ) const
  218. {
  219. if( m_bitmap == nullptr )
  220. return;
  221. VECTOR2I pos = aPos;
  222. VECTOR2I size = GetSize();
  223. // This fixes a bug in OSX that should be fixed in the 3.0.3 version or later.
  224. if( ( size.x == 0 ) || ( size.y == 0 ) )
  225. return;
  226. // To draw the bitmap, pos is the upper left corner position
  227. pos.x -= size.x / 2;
  228. pos.y -= size.y / 2;
  229. double scale;
  230. int logicalOriginX, logicalOriginY;
  231. aDC->GetUserScale( &scale, &scale );
  232. aDC->GetLogicalOrigin( &logicalOriginX, &logicalOriginY );
  233. // We already have issues to draw a bitmap on the wxDC, depending on wxWidgets version.
  234. // Now we have an issue on wxWidgets 3.1.6 to fix the clip area
  235. // and the bitmap position when using TransformMatrix
  236. // So for version == 3.1.6 do not use it
  237. // Be carefull before changing the code.
  238. bool useTransform = aDC->CanUseTransformMatrix();
  239. wxAffineMatrix2D init_matrix = aDC->GetTransformMatrix();
  240. // Note: clipping bitmap area was made to fix a minor issue in old versions of
  241. // Kicad/wxWidgets (5.1 / wx 3.0)
  242. // However SetClippingRegion creates a lot of issues (different ways to fix the
  243. // position and size of the area, depending on wxWidget version)because it changes with
  244. // each versions of wxWigets, so it is now disabled
  245. // However the code is still here, just in case
  246. // #define USE_CLIP_AREA
  247. wxPoint clipAreaPos;
  248. if( useTransform )
  249. {
  250. wxAffineMatrix2D matrix = aDC->GetTransformMatrix();
  251. matrix.Translate( pos.x, pos.y );
  252. matrix.Scale( GetScalingFactor(), GetScalingFactor() );
  253. aDC->SetTransformMatrix( matrix );
  254. // Needed on wx <= 3.1.5, and this is strange...
  255. // Nevertheless, this code has problem (the bitmap is not seen)
  256. // with wx version > 3.1.5
  257. clipAreaPos.x = pos.x;
  258. clipAreaPos.y = pos.y;
  259. pos.x = pos.y = 0;
  260. }
  261. else
  262. {
  263. aDC->SetUserScale( scale * GetScalingFactor(), scale * GetScalingFactor() );
  264. aDC->SetLogicalOrigin( logicalOriginX / GetScalingFactor(),
  265. logicalOriginY / GetScalingFactor() );
  266. pos.x = KiROUND( pos.x / GetScalingFactor() );
  267. pos.y = KiROUND( pos.y / GetScalingFactor() );
  268. size.x = KiROUND( size.x / GetScalingFactor() );
  269. size.y = KiROUND( size.y / GetScalingFactor() );
  270. clipAreaPos.x = pos.x;
  271. clipAreaPos.y = pos.y;
  272. }
  273. #ifdef USE_CLIP_AREA
  274. aDC->DestroyClippingRegion();
  275. aDC->SetClippingRegion( clipAreaPos, wxSize( size.x, size.y ) );
  276. #endif
  277. if( aBackgroundColor != COLOR4D::UNSPECIFIED && m_bitmap->HasAlpha() )
  278. {
  279. // Most printers don't support transparent images properly,
  280. // so blend the image with background color.
  281. int w = m_bitmap->GetWidth();
  282. int h = m_bitmap->GetHeight();
  283. wxImage image( w, h );
  284. wxColour bgColor = aBackgroundColor.ToColour();
  285. image.SetRGB( wxRect( 0, 0, w, h ), bgColor.Red(), bgColor.Green(), bgColor.Blue() );
  286. image.Paste( m_bitmap->ConvertToImage(), 0, 0, wxIMAGE_ALPHA_BLEND_COMPOSE );
  287. if( GetGRForceBlackPenState() )
  288. image = image.ConvertToGreyscale();
  289. aDC->DrawBitmap( wxBitmap( image ), pos.x, pos.y, true );
  290. }
  291. else if( GetGRForceBlackPenState() )
  292. {
  293. wxBitmap result( m_bitmap->ConvertToImage().ConvertToGreyscale() );
  294. aDC->DrawBitmap( result, pos.x, pos.y, true );
  295. }
  296. else
  297. {
  298. aDC->DrawBitmap( *m_bitmap, pos.x, pos.y, true );
  299. }
  300. if( useTransform )
  301. aDC->SetTransformMatrix( init_matrix );
  302. else
  303. {
  304. aDC->SetUserScale( scale, scale );
  305. aDC->SetLogicalOrigin( logicalOriginX, logicalOriginY );
  306. }
  307. #ifdef USE_CLIP_AREA
  308. aDC->DestroyClippingRegion();
  309. #endif
  310. }
  311. VECTOR2I BITMAP_BASE::GetSize() const
  312. {
  313. VECTOR2I size;
  314. if( m_bitmap )
  315. {
  316. size.x = m_bitmap->GetWidth();
  317. size.y = m_bitmap->GetHeight();
  318. size.x = KiROUND( size.x * GetScalingFactor() );
  319. size.y = KiROUND( size.y * GetScalingFactor() );
  320. }
  321. return size;
  322. }
  323. void BITMAP_BASE::Mirror( FLIP_DIRECTION aFlipDirection )
  324. {
  325. if( m_image )
  326. {
  327. // wxImage::Mirror() clear some parameters of the original image.
  328. // We need to restore them, especially resolution and unit, to be
  329. // sure image parameters saved in file are the right parameters, not
  330. // the defualt values
  331. int resX = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
  332. int resY = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY );
  333. int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
  334. *m_image = m_image->Mirror( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT );
  335. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT , unit);
  336. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX);
  337. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY);
  338. if( aFlipDirection == FLIP_DIRECTION::TOP_BOTTOM )
  339. m_isMirroredY = !m_isMirroredY;
  340. else
  341. m_isMirroredX = !m_isMirroredX;
  342. rebuildBitmap( false );
  343. UpdateImageDataBuffer();
  344. }
  345. }
  346. void BITMAP_BASE::Rotate( bool aRotateCCW )
  347. {
  348. if( m_image )
  349. {
  350. // wxImage::Rotate90() clear some parameters of the original image.
  351. // We need to restore them, especially resolution and unit, to be
  352. // sure image parameters saved in file are the right parameters, not
  353. // the defualt values
  354. int resX = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
  355. int resY = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY );
  356. int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
  357. *m_image = m_image->Rotate90( aRotateCCW );
  358. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT , unit);
  359. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX);
  360. m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY);
  361. m_rotation += ( aRotateCCW ? ANGLE_90 : -ANGLE_90 );
  362. rebuildBitmap( false );
  363. UpdateImageDataBuffer();
  364. }
  365. }
  366. void BITMAP_BASE::ConvertToGreyscale()
  367. {
  368. if( m_image )
  369. {
  370. *m_image = m_image->ConvertToGreyscale();
  371. *m_originalImage = m_originalImage->ConvertToGreyscale();
  372. rebuildBitmap();
  373. UpdateImageDataBuffer();
  374. }
  375. }
  376. void BITMAP_BASE::PlotImage( PLOTTER* aPlotter, const VECTOR2I& aPos,
  377. const COLOR4D& aDefaultColor,
  378. int aDefaultPensize ) const
  379. {
  380. if( m_image == nullptr )
  381. return;
  382. // These 2 lines are useful only for plotters that cannot plot a bitmap
  383. // and plot a rectangle instead of.
  384. aPlotter->SetColor( aDefaultColor );
  385. aPlotter->SetCurrentLineWidth( aDefaultPensize );
  386. aPlotter->PlotImage( *m_image, aPos, GetScalingFactor() );
  387. }
  388. void BITMAP_BASE::UpdateImageDataBuffer()
  389. {
  390. if( m_image )
  391. {
  392. wxMemoryOutputStream stream;
  393. wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG;
  394. if( !m_image->SaveFile( stream, type ) )
  395. return;
  396. m_imageData.GetWriteBuf( stream.GetLength() );
  397. stream.CopyTo( m_imageData.GetData(), stream.GetLength() );
  398. m_imageData.SetDataLen( stream.GetLength() );
  399. }
  400. }