Debian Codegraph @

cuneiform_src/Kern/rimage/sources/main/crrotator.cpp

raw
1 /*
2 Copyright (c) 1993-2008, Cognitive Technologies
3 All rights reserved.
4
5 Разрешается повторное распространение и использование как в виде исходного кода,
6 так и в двоичной форме, с изменениями или без, при соблюдении следующих условий:
7
8 * При повторном распространении исходного кода должны оставаться указанное
9 выше уведомление об авторском праве, этот список условий и последующий
10 отказ от гарантий.
11 * При повторном распространении двоичного кода в документации и/или в
12 других материалах, поставляемых при распространении, должны сохраняться
13 указанная выше информация об авторском праве, этот список условий и
14 последующий отказ от гарантий.
15 * Ни название Cognitive Technologies, ни имена ее сотрудников не могут
16 быть использованы в качестве средства поддержки и/или продвижения
17 продуктов, основанных на этом ПО, без предварительного письменного
18 разрешения.
19
20 ЭТА ПРОГРАММА ПРЕДОСТАВЛЕНА ВЛАДЕЛЬЦАМИ АВТОРСКИХ ПРАВ И/ИЛИ ДРУГИМИ ЛИЦАМИ "КАК
21 ОНА ЕСТЬ" БЕЗ КАКОГО-ЛИБО ВИДА ГАРАНТИЙ, ВЫРАЖЕННЫХ ЯВНО ИЛИ ПОДРАЗУМЕВАЕМЫХ,
22 ВКЛЮЧАЯ ГАРАНТИИ КОММЕРЧЕСКОЙ ЦЕННОСТИ И ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ, НО НЕ
23 ОГРАНИЧИВАЯСЬ ИМИ. НИ ВЛАДЕЛЕЦ АВТОРСКИХ ПРАВ И НИ ОДНО ДРУГОЕ ЛИЦО, КОТОРОЕ
24 МОЖЕТ ИЗМЕНЯТЬ И/ИЛИ ПОВТОРНО РАСПРОСТРАНЯТЬ ПРОГРАММУ, НИ В КОЕМ СЛУЧАЕ НЕ
25 НЕСЁТ ОТВЕТСТВЕННОСТИ, ВКЛЮЧАЯ ЛЮБЫЕ ОБЩИЕ, СЛУЧАЙНЫЕ, СПЕЦИАЛЬНЫЕ ИЛИ
26 ПОСЛЕДОВАВШИЕ УБЫТКИ, СВЯЗАННЫЕ С ИСПОЛЬЗОВАНИЕМ ИЛИ ПОНЕСЕННЫЕ ВСЛЕДСТВИЕ
27 НЕВОЗМОЖНОСТИ ИСПОЛЬЗОВАНИЯ ПРОГРАММЫ (ВКЛЮЧАЯ ПОТЕРИ ДАННЫХ, ИЛИ ДАННЫЕ,
28 СТАВШИЕ НЕГОДНЫМИ, ИЛИ УБЫТКИ И/ИЛИ ПОТЕРИ ДОХОДОВ, ПОНЕСЕННЫЕ ИЗ-ЗА ДЕЙСТВИЙ
29 ТРЕТЬИХ ЛИЦ И/ИЛИ ОТКАЗА ПРОГРАММЫ РАБОТАТЬ СОВМЕСТНО С ДРУГИМИ ПРОГРАММАМИ,
30 НО НЕ ОГРАНИЧИВАЯСЬ ЭТИМИ СЛУЧАЯМИ), НО НЕ ОГРАНИЧИВАЯСЬ ИМИ, ДАЖЕ ЕСЛИ ТАКОЙ
31 ВЛАДЕЛЕЦ ИЛИ ДРУГОЕ ЛИЦО БЫЛИ ИЗВЕЩЕНЫ О ВОЗМОЖНОСТИ ТАКИХ УБЫТКОВ И ПОТЕРЬ.
32
33 Redistribution and use in source and binary forms, with or without modification,
34 are permitted provided that the following conditions are met:
35
36 * Redistributions of source code must retain the above copyright notice,
37 this list of conditions and the following disclaimer.
38 * Redistributions in binary form must reproduce the above copyright notice,
39 this list of conditions and the following disclaimer in the documentation
40 and/or other materials provided with the distribution.
41 * Neither the name of the Cognitive Technologies nor the names of its
42 contributors may be used to endorse or promote products derived from this
43 software without specific prior written permission.
44
45 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
46 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
47 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
49 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
51 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
52 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
53 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
54 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
55 */
56
57 // CRRotator.cpp: implementation of the CRRotator class.
58 //
59 //////////////////////////////////////////////////////////////////////
60 #include <memory.h>
61 #include <math.h>
62 #include <stdlib.h>
63
64 #include "ctdib.h"
65 #include "crrotator.h"
66 #include "crimemory.h"
67 #include "resource.h"
68 #include "minmax.h"
69
70 //////////////////////////////////////////////////////////////////////
71
72 static uint32_t BitsInHalfByte[16] =
73 {//0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc x0d 0xe 0xf
74 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
75
76 static uint32_t HalfBytetoFourBytes[16] =
77 {// 0x0 0x01 0x02 0x03
78 0x00000000, 0x000000ff, 0x0000ff00, 0x0000ffff,
79 // 0x04 0x05 0x06 0x07
80 0x00ff0000, 0x00ff00ff, 0x00ffff00, 0x00ffffff,
81 // 0x08 0x09 0x0a 0x0b
82 0xff000000, 0xff0000ff, 0xff00ff00, 0xff00ffff,
83 // 0x0c 0x0d 0x0e 0x0f
84 0xffff0000, 0xffff00ff, 0xffffff00, 0xffffffff,
85 };
86 static uchar FourBytestoLeftHalfByte[16] =
87 { 0x00, 0x10, 0x20, 0x30,
88 0x40, 0x50, 0x60, 0x70,
89 0x80, 0x90, 0xa0, 0xb0,
90 0xc0, 0xd0, 0xe0, 0xf0
91 };
92 static uchar FourBytestoRightHalfByte[16] =
93 { 0x00, 0x01, 0x02, 0x03,
94 0x04, 0x05, 0x06, 0x07,
95 0x08, 0x09, 0x0a, 0x0b,
96 0x0c, 0x0d, 0x0e, 0x0f
97 };
98 static uchar MaskForRightShift[9] =
99 {
100 // 00000000 00000001 00000011 00000111 00001111
101 0x00, 0x01, 0x03, 0x07, 0xf,
102 // 00011111 00111111 01111111 11111111
103 0x1f, 0x3f, 0x7f, 0xff
104 };
105 static uchar MaskForLeftShift[9] =
106 {
107 // 00000000 10000000 11000000 11100000 11110000
108 0x00, 0x80, 0xc0, 0xe0, 0xf0,
109 // 11111000 11111100 11111110 11111111
110 0xf8, 0xfc, 0xfe, 0xff
111 };
112 static uchar OneBitMask[8] =
113 {
114 // 1-й вариант
115 // 00000001 00000010 00000100 00001000
116 // 0x01, 0x02, 0x04, 0x08,
117 // 00010000 00100000 01000000 10000000
118 // 0x10, 0x20, 0x40, 0x80
119 // 2-й вариант
120 // 10000000 01000000 00100000 00010000
121 0x80, 0x40, 0x20, 0x10,
122 // 00001000 00000100 00000010 00000001
123 0x08, 0x04, 0x02, 0x01
124 };
125 //////////////////////////////////////////////////////////////////////
126 // Construction/Destruction
127 //////////////////////////////////////////////////////////////////////
128 //
129
130 void CRRotator::ResetItself()
131 {
132 AtX = 0;
133 AtY = 0;
134 ToX = 0;
135 ToY = 0;
136 mfCos = 0.0;
137 mfSin = 0.0;
138 mfTang = 0.0;
139 mwDescewedHeight = 0;
140 mwDescewedWidth = 0;
141 mwOriginalHeight = 0;
142 mwOriginalWidth = 0;
143 mwTablesRange = 0;
144 mbEnableHS = TRUE;
145 mbEnableVS = TRUE;
146 mbEnableVSS = TRUE;
147 mpProgressor = NULL;
148 BufferForGray = NULL;
149 hBufferForGray = NULL;
150 HShiftTable = NULL;
151 hHShiftTable = NULL;
152 VShiftTable = NULL;
153 hVShiftTable = NULL;
154 VShiftLenght = NULL;
155 hVShiftLenght = NULL;
156
157 }
158
159 CRRotator::CRRotator()
160 {
161 ResetItself();
162 }
163 //////////////////////////////////////////////////////////////////////
164 //
165 CRRotator::CRRotator(PCRProgressor pProgressIndicator)
166 {
167 ResetItself();
168 mpProgressor = pProgressIndicator;
169 }
170 ///////////////////////////////////////////////////////////////////////////////////////
171 //
172 CRRotator::~CRRotator()
173 {
174 FreeWorkBuffers();
175 }
176 ///////////////////////////////////////////////////////////////////////////////////////
177 //
178
179 Bool32 CRRotator::Rotate(PCTDIB cDIBIn, PCTDIB cDIBOut, int32_t Num, int32_t Denum)
180 {
181 Bool32 Ret = FALSE;
182 long double fNum = (long double)Num;
183 long double fDenum = (long double)Denum;
184 long double fG = sqrt( fNum * fNum + fDenum * fDenum );
185
186 if ( Num == 0 || Denum == 0)
187 {
188 SetReturnCode_rimage(IDS_RIMAGE_ZERO_NUMERATOR_OR_DENUMERATOR);
189 return FALSE;
190 }
191
192 /*
193 if ( cDIBIn->GetPixelSize() == 4 )
194 {
195 SetReturnCode_rimage(IDS_RIMAGE_UNDER_CONSTRUCTION);
196 return FALSE;
197 }
198 */
199
200 mfTang= fNum / fDenum;
201 mfCos = fDenum / fG;
202 mfSin = fNum / fG;
203
204 if ( fabs(mfTang) > CTROTATOR_MAX_TANG )
205 {
206 SetReturnCode_rimage(IDS_RIMAGE_ANGLE_GREAT_MAXIMUM);
207 return FALSE;
208 }
209
210 if ( fabs(mfTang) < CTROTATOR_MIN_TANG )
211 {
212 SetReturnCode_rimage(IDS_RIMAGE_ANGLE_LEAST_MINIMUM);
213 return FALSE;
214 }
215
216 if ( !ConstructOutDIB(cDIBIn, cDIBOut, FALSE) )
217 return FALSE;
218 try
219 {
220 FreeWorkBuffers();
221 Ret = Descew(cDIBIn, cDIBOut);
222 }
223
224 catch ( uint32_t wExit )
225 {
226 if ( wExit = IDS_RIMAGE_EXIT_BY_USER)
227 {
228 SetReturnCode_rimage(IDS_RIMAGE_EXIT_BY_USER);
229 }
230 else
231 {
232 SetReturnCode_rimage(IDS_RIMAGE_UNKNOWN_ERROR);
233 }
234
235 FreeWorkBuffers();
236 Ret = FALSE;
237 }
238
239 return Ret;
240 }
241 /////////////////////////////////////////////////////////////////////////////////////////////////////
242 Bool32 CRRotator::Descew(PCTDIB cDIBIn, PCTDIB cDIBOut )
243 {
244 # ifndef max
245 # define MAX(a,b) ( (a) > (b) ? (a) : (b) )
246 # endif
247 Bool32 Ret = TRUE;
248 uint32_t Line;
249 uint32_t wBitLenght = cDIBIn->GetPixelSize();
250 // uint32_t wLines = cDIBIn->GetLinesNumber();
251 // uint32_t wLineW = cDIBIn->GetLineWidth();
252 uint32_t wLineBytesW = cDIBIn->GetLineWidthInBytes();
253 uint32_t wLineBytesWTo = cDIBOut->GetLineWidthInBytes();
254 uint32_t HorisontalShiftInBytes = (((wBitLenght * HorisontalShift) + 7) / 8);
255 int32_t Direction = (mfTang > 0 ? 1 : -1);
256 int32_t ToShift;
257 puchar pToCopy;
258
259 mwOriginalHeight = cDIBIn->GetLinesNumber();
260 mwOriginalWidth = cDIBIn->GetLineWidth();
261 mwDescewedHeight = cDIBOut->GetLinesNumber();
262 mwDescewedWidth = cDIBOut->GetLineWidth();
263 mwTablesRange = MAX (mwDescewedHeight, mwDescewedWidth);
264
265
266 AllocWorkBuffers(TRUE);
267 PrepareTables(mwTablesRange, mwDescewedWidth - 1);
268
269 /////////////
270 //начинаем сдвигать.
271 mpProgressor->Start();
272
273 for ( Line = 0; Line < mwDescewedHeight; Line++)
274 {
275
276 if ( mpProgressor->SetStep( (Line / mwDescewedHeight) * 100 ) )
277 {
278 mpProgressor->Finish();
279 throw IDS_RIMAGE_EXIT_BY_USER;
280 }
281
282 memset(BufferForGray, BitFillforGray, HorisontalShiftInBytes);
283 memset(BufferForGray + wLineBytesWTo - HorisontalShiftInBytes, BitFillforGray, HorisontalShiftInBytes);
284
285 switch ( wBitLenght )
286 {
287 case 8:
288 case 24:
289 case 32:
290 ComposeLineG(cDIBIn, Direction, Line, mwDescewedWidth);
291 break;
292 case 1:
293 //// состовляем строку с учетом сдвигов
294 // внимание! строка составляется неточно!!!!!
295 ComposeLineLA(cDIBIn, Direction, Line, mwDescewedWidth);
296 //забиваем конец строки
297 SetEndLineLA(Line, mwOriginalWidth, wLineBytesWTo);
298 //// сдвигаем по горизонтали
299 ToShift = HShiftTable[Line]%8; //(int32_t)( (i * dTan) + 0.5) % 8
300
301 if ( ToShift != 0 )
302 {
303 ShiftLineLA(ToShift, wLineBytesWTo + HorisontalShiftInBytes - 1);
304 }
305 break;
306 case 4:
307 ComposeLine4(cDIBIn, Direction, Line, mwDescewedWidth);
308 default:
309 break;
310 }
311 // копируем строку в конечный диб
312 pToCopy = (puchar)(Direction > 0 ? cDIBOut->GetPtrToLine(Line) :
313 cDIBOut->GetPtrToLine(mwDescewedHeight - Line - 1));
314 if (pToCopy )
315 {
316 memcpy(pToCopy, BufferForGray, wLineBytesWTo);
317 }
318 }
319
320 mpProgressor->Finish();
321
322 return Ret;
323 }
324
325 void CRRotator::ComposeLineLA(PCTDIB cDIBIn, int32_t iDirect, uint32_t wLine, uint32_t wBuffLen)
326 {
327 uint32_t j;
328 uint32_t StartByte;
329 uint32_t EndByte;
330 uint32_t FulBytes;
331 uint32_t Bits;
332 int32_t PosInBuff;
333 uint32_t Copy = 0;
334 puchar PixFrom;
335 uchar LastByte;
336 uint32_t wLines = cDIBIn->GetLinesNumber();
337
338 for ( j = 0; j < wBuffLen; )
339 {
340 StartByte = j / 8; //откуда начнем
341 // EndByte = (j + VShiftLenght[j])/8; //последний копируемый
342 EndByte = (j - 1 + VShiftLenght[j])/8; //последний копируемый
343
344 FulBytes = EndByte - StartByte + 1;
345 // Bits = (j + VShiftLenght[j]) - EndByte * 8;
346 Bits = j - StartByte * 8;
347
348 if ( VShiftLenght[j] == 0 )
349 {
350 j++;
351 continue;
352 }
353
354 // если есть строка исходной картинки
355 PixFrom = NULL;
356 PosInBuff = ( HShiftTable[wLine]) / 8 + StartByte;
357 if ( wLine + VShiftTable[j] >= AtY && wLine + VShiftTable[j] < ToY )
358 {
359 if ( iDirect > 0 )
360 {
361 PixFrom = (puchar)cDIBIn->GetPtrToPixel(j,wLine + VShiftTable[j] - AtY);
362 }
363 else
364 {
365 PixFrom = (puchar)cDIBIn->GetPtrToPixel(j,wLines - (wLine + VShiftTable[j] - AtY));
366 }
367 }
368 //перед копированием дальше запоминаем первый байт
369 if ( j != 0 && Bits > 0 && mbEnableVSS)
370 {
371 LastByte = 0x00;
372 LastByte |= *(BufferForGray + PosInBuff)&MaskForLeftShift[Bits];
373 }
374
375 if ( PixFrom )
376 {
377 // копируем следующий кусок
378 if (EndByte > cDIBIn->GetUsedLineWidthInBytes() - 1)
379 {
380 EndByte = cDIBIn->GetUsedLineWidthInBytes() - 1;
381 FulBytes = EndByte - StartByte + 1;
382 }
383
384 memcpy(BufferForGray + PosInBuff,PixFrom, FulBytes );
385 }
386 else // if ( pixfrom )
387 {
388 memset(BufferForGray + PosInBuff,BitFillforGray, FulBytes );
389 }
390 //на стыке совмещаем побитно
391 if ( Bits > 0 && j != 0 && mbEnableVSS)
392 {
393 LastByte |= *(BufferForGray + PosInBuff)&MaskForRightShift[8 - Bits];
394 *(BufferForGray + PosInBuff) = LastByte;
395 }
396
397 Copy += FulBytes * 8;
398 j+= VShiftLenght[j];
399 }
400 }
401
402 void CRRotator::ComposeLine4(PCTDIB cDIBIn, int32_t iDirect, uint32_t wLine, uint32_t wBuffLen)
403 {
404 uint32_t j;
405 uint32_t StartByte;
406 uint32_t EndByte;
407 uint32_t FulBytes;
408 uint32_t Pixels;
409 int32_t PosInBuff;
410 uint32_t Copy = 0;
411 puchar PixFrom;
412 uchar LastByte;
413 uint32_t wLines = cDIBIn->GetLinesNumber();
414
415 for ( j = 0; j < wBuffLen; )
416 {
417 StartByte = j / 2; //откуда начнем
418 EndByte = (j + VShiftLenght[j])/2; //последний копируемый
419
420 FulBytes = EndByte - StartByte + 1;
421 Pixels = (j + VShiftLenght[j]) - EndByte * 2;
422
423
424 if ( VShiftLenght[j] == 0 )
425 {
426 j++;
427 continue;
428 }
429
430 // если есть строка исходной картинки
431 PixFrom = NULL;
432 PosInBuff = ( HShiftTable[wLine]) / 2 + StartByte;
433
434 if ( wLine + VShiftTable[j] >= AtY && wLine + VShiftTable[j] < ToY )
435 {
436 if ( iDirect > 0 )
437 {
438 PixFrom = (puchar)cDIBIn->GetPtrToPixel(j,wLine + VShiftTable[j] - AtY);
439 }
440 else
441 {
442 PixFrom = (puchar)cDIBIn->GetPtrToPixel(j,wLines - (wLine + VShiftTable[j] - AtY));
443 }
444 }
445 //перед копированием дальше запоминаем первый байт
446 if ( j != 0 && Pixels > 0 && mbEnableVSS)
447 {
448 LastByte = 0x00;
449 LastByte |= *(BufferForGray + PosInBuff)&MaskForLeftShift[Pixels];
450 }
451
452 if ( PixFrom )
453 {
454 // копируем следующий кусок
455 memcpy(BufferForGray + PosInBuff,PixFrom, FulBytes );
456 }
457 else // if ( pixfrom )
458 {
459 memset(BufferForGray + PosInBuff,BitFillforGray, FulBytes );
460 }
461 //на стыке совмещаем побитно
462 if ( Pixels > 0 && j != 0 && mbEnableVSS)
463 {
464 LastByte |= *(BufferForGray + PosInBuff)&MaskForRightShift[8 - Pixels];
465 *(BufferForGray + PosInBuff) = LastByte;
466 }
467
468 Copy += FulBytes * 2;
469 j+= VShiftLenght[j];
470 }
471 }
472
473 void CRRotator::SetEndLineLA(uint32_t Line, uint32_t wLineW, uint32_t wLineBytes)
474 {
475 uint32_t StartByte = wLineW/8 + HShiftTable[Line]/8;
476 uint32_t EndByte = wLineBytes;
477 uint32_t Bits = wLineW + (HShiftTable[Line]/8)*8 - StartByte*8;
478 uchar LastByte;
479
480 if ( Bits > 0 )
481 {
482 LastByte = 0x00;
483 LastByte |= *(BufferForGray + StartByte)&MaskForLeftShift[Bits];
484 LastByte |= BitFillforGray&MaskForRightShift[8 - Bits];
485 }
486
487 if ( (int32_t)(EndByte - StartByte) > 0)
488 memset(BufferForGray + StartByte, BitFillforGray, (EndByte - StartByte));
489
490 if ( Bits > 0 )
491 *(BufferForGray + StartByte) = LastByte;
492 }
493
494 void CRRotator::PrepareTables( uint32_t wMax, uint32_t wCheck)
495 {
496 uint32_t i;
497 int32_t Shift;
498 int32_t PrevS;
499 int32_t PrevI;
500 long double dmTan = (mfTang > 0 ? mfTang : -mfTang);
501
502 for (PrevS = PrevI = i = 0; i < wMax; i++ )
503 {
504 Shift = (int32_t)( (i * dmTan) + 0.5) ;
505
506 if ( i < AtY )
507 HShiftTable[i] = Shift;
508 else
509 Shift = (Shift < 0 ? 0 : Shift);
510
511 HShiftTable[i] = Shift /*( Shift < HorisontalShift ? Shift : HorisontalShift )*/;
512
513 VShiftTable[i] = ( Shift < VerticalShift ? Shift : VerticalShift );
514
515 VShiftLenght[i] = 0;
516 if ( PrevS != Shift || i == wCheck)
517 {
518 VShiftLenght[PrevI] = i - PrevI;
519 PrevI = i;
520 }
521
522 PrevS = Shift;
523 }
524 }
525
526 void CRRotator::ShiftLineLA(uint32_t LocalShift, uint32_t wBytesTo )
527 {
528 uint32_t LocalUnshift = 8 - LocalShift;
529 uint32_t ShiftedByte;
530
531 for ( ShiftedByte = wBytesTo;
532 ShiftedByte > 0;
533 ShiftedByte-- )
534 {
535 BufferForGray[ShiftedByte] = BufferForGray[ShiftedByte]>>LocalShift;
536 BufferForGray[ShiftedByte] &= MaskForRightShift[LocalUnshift];
537 BufferForGray[ShiftedByte] |= ( BufferForGray[ShiftedByte - 1]<<LocalUnshift )&MaskForLeftShift[LocalShift];
538 }
539
540 BufferForGray[0] |= BitFillforGray&MaskForLeftShift[LocalShift];
541
542
543 }
544 ///////////////////////////////////////////////////////////////////////////////////////
545 //
546 ///////////////////////////////////////////////////////////////////////////////////////////////////
547 Bool32 CRRotator::Roll(PCTDIB cDIBIn, PCTDIB cDIBOut, int32_t Num, int32_t Denum)
548 {
549 long double fNum = (long double)Num;
550 long double fDenum = (long double)Denum;
551 long double fG = sqrt( fNum * fNum + fDenum * fDenum );
552
553 mfTang = fNum / fDenum;
554 mfCos = fDenum / fG;
555 mfSin = fNum / fG;
556 mdDIBOut = cDIBOut;
557
558 /*
559 if ( mfTang > CTROTATOR_MAX_TANG || mfTang < CTROTATOR_MIN_TANG )
560 return FALSE;
561 */
562
563 if ( !ConstructOutDIB(cDIBIn, cDIBOut, TRUE) )
564 return FALSE;
565
566 if ( !DescewGray( cDIBIn, cDIBOut) )
567 {
568 return FALSE;
569 }
570
571 return TRUE;
572 }
573 /////////////////////////////////////////////////////////////////////////////////////////////////////
574 Bool32 CRRotator::ConstructOutDIB(PCTDIB cDIBIn, PCTDIB cDIBOut, Bool32 Gray)
575 {
576 uint32_t NewWidth;
577 uint32_t NewHeigth;
578 uint32_t dpmX;
579 uint32_t dpmY;
580 CTDIBRGBQUAD Quad;
581
582 if ( Gray )
583 {
584 HorisontalShift = (int32_t)((cDIBIn->GetLinesNumber() * mfSin) + 0.5);
585 HorisontalShift -= (int32_t)((cDIBIn->GetLineWidth() * (1.0 - mfCos)) + 0.5);
586 VerticalShift = (int32_t)((cDIBIn->GetLineWidth() * mfSin) + 0.5);
587 VerticalShift -= (int32_t)((cDIBIn->GetLinesNumber() * (1.0 - mfCos)) + 0.5);
588
589 NewHeigth = (uint32_t)((cDIBIn->GetLineWidth() * mfSin) + 0.5 ) +
590 (uint32_t)((cDIBIn->GetLinesNumber() * mfCos) + 0.5 );
591 NewWidth = (uint32_t)((cDIBIn->GetLineWidth() * mfCos) + 0.5 ) +
592 (uint32_t)((cDIBIn->GetLinesNumber() * mfSin) + 0.5 );
593
594 if ( mfTang > 0 )
595 {
596 AtX = 0;
597 AtY = (int32_t)(cDIBIn->GetLineWidth() * mfSin); //VerticalShift;
598 }
599 else
600 {
601 AtX = (int32_t)(cDIBIn->GetLinesNumber() * mfSin); //HorisontalShift;
602 AtY = 0;
603 }
604 ToX = NewWidth;
605 ToY = NewHeigth;
606 }
607 else
608 {
609 HorisontalShift = (uint32_t)((cDIBIn->GetLinesNumber() * fabs(mfTang)) + 0.5);
610 VerticalShift = (uint32_t)((cDIBIn->GetLineWidth() * fabs(mfTang)) + 0.5);
611
612 AtX = 0;
613 AtY = VerticalShift;
614 ToX = AtX + cDIBIn->GetLineWidth();
615 ToY = AtY + cDIBIn->GetLinesNumber();
616
617 NewWidth = cDIBIn->GetLineWidth() + HorisontalShift;
618 NewHeigth = cDIBIn->GetLinesNumber() + VerticalShift;
619 }
620
621 RIMAGEComment("ConstructOutDIB - out DIB");
622 if ( !cDIBOut->SetExternals(RIMAGEAlloc, RIMAGEFree, RIMAGELock, RIMAGEUnlock) ||
623 !cDIBOut->CreateDIBBegin(NewWidth,
624 NewHeigth,
625 Gray ? 8 : cDIBIn->GetPixelSize(),
626 0,
627 cDIBIn->GetVersion()) )
628 return FALSE;
629
630 cDIBIn->GetResolutionDPM( &dpmX, &dpmY );
631 cDIBOut->SetResolutionDPM( dpmX, dpmY );
632
633 cDIBOut->CreateDIBEnd();
634
635 cDIBOut->CopyPalleteFromDIB(cDIBIn);
636
637 BitFillforGray = (uchar)cDIBIn->GetWhitePixel();
638
639 //для однобитного изображения растягиваем его на весь байт
640 if ( cDIBOut->GetPixelSize() == 1 )
641 BitFillforGray += ( BitFillforGray << 1 ) +
642 ( BitFillforGray << 2 ) +
643 ( BitFillforGray << 3 ) +
644 ( BitFillforGray << 4 ) +
645 ( BitFillforGray << 5 ) +
646 ( BitFillforGray << 6 ) +
647 ( BitFillforGray << 7 );
648
649 if ( Gray )
650 {
651 int32_t wQuadN;
652
653 for ( wQuadN = 255; wQuadN >= 0; wQuadN--)
654 {
655 Quad.rgbBlue = Quad.rgbGreen = Quad.rgbRed = (uchar)wQuadN;
656 cDIBOut->SetRGBQuad(wQuadN,Quad);
657 }
658 }
659
660 return TRUE;
661 }
662
663 Bool32 CRRotator::DescewGray(PCTDIB cDIBIn, PCTDIB cDIBOut)
664 {
665 Bool32 bRet = TRUE;
666 // размеры
667 uint32_t OutLineLenght = cDIBOut->GetLineWidth();
668 uint32_t OunLines = cDIBOut->GetLinesNumber();
669 uint32_t InLineLenght = cDIBIn->GetLineWidth();
670 uint32_t InLines = cDIBIn->GetLinesNumber();
671 //координаты
672 int32_t CurrLAX;
673 int32_t CurrLAY;
674 int32_t CurrGX;
675 int32_t CurrGY;
676 int32_t OldPointX;
677 int32_t OldPointY;
678 int32_t NewPointX;
679 int32_t NewPointY;
680 int32_t GShiftX;
681 int32_t GShiftY;
682 // пикселы
683 puchar pLAPix = NULL;
684 puchar pGrayPix = NULL;
685 puchar pGrayLine = NULL;
686 uint32_t LABitInByte;
687 uchar Decrement;
688 uchar Corner = 1;
689 // маска
690 Handle hMask = NULL;
691 puchar pMask = NULL;
692
693 hMask = RIMAGEDAlloc(OutLineLenght * OunLines, "Rotator::DescewGray - mask");
694 pMask = (puchar)RIMAGELock(hMask);
695
696
697 if ( cDIBOut->GetPixelSize() != 8 )
698 {
699 return FALSE;
700 }
701
702 if ( pMask )
703 {
704 for ( CurrGY = OunLines - 1; CurrGY >= 0; CurrGY-- )
705 {
706 pGrayLine = (puchar)cDIBOut->GetPtrToLine(CurrGY);
707 memset(pGrayLine, 127, OutLineLenght);
708 memset((pMask + (CurrGY * OutLineLenght)), 1, OutLineLenght);
709 }
710 }
711 else
712 {
713 for ( CurrGY = OunLines - 1; CurrGY >= 0; CurrGY-- )
714 {
715 pGrayLine = (puchar)cDIBOut->GetPtrToLine(CurrGY);
716 memset(pGrayLine, 255, OutLineLenght);
717 }
718 }
719
720 for ( CurrLAY = 0; CurrLAY < (int32_t)InLines; CurrLAY++)
721 {
722 for ( CurrLAX = 0; CurrLAX < (int32_t)InLineLenght; CurrLAX++)
723 {
724 GetExtCoord(CurrLAX, CurrLAY, &OldPointX, &OldPointY);
725 RollPoint(OldPointX, OldPointY, &NewPointX, &NewPointY);
726
727 NewPointX += AtX * 256;
728 NewPointY += AtY * 256;
729
730 GetGrayCoord(NewPointX, NewPointY, &CurrGX, &CurrGY, &GShiftX, &GShiftY);
731
732 //CurrGX += AtX;
733 //CurrGY += AtY;
734
735 if ( CurrGX < (int32_t)OutLineLenght &&
736 CurrGY < (int32_t)OunLines)
737 {
738 pGrayPix = (puchar)cDIBOut->GetPtrToPixel(CurrGX, CurrGY);
739
740 if ( !pGrayPix )
741 continue;
742 }
743 else
744 continue;
745
746 if ( pMask )
747 {
748 UnmaskPixels(pMask, pGrayPix, CurrGX, CurrGY, OutLineLenght, GShiftX, GShiftY);
749 }
750
751 //берем черно-белый пиксел
752 if ( CurrLAX < (int32_t)InLineLenght &&
753 CurrLAY < (int32_t)InLines)
754 {
755 pLAPix = (puchar)cDIBIn->GetPtrToPixel(CurrLAX, CurrLAY);
756
757 if ( !pLAPix )
758 continue;
759
760 }
761 else
762 continue;
763
764 // раскидываем по серому
765 LABitInByte = CurrLAX - ((CurrLAX / 8) * 8);
766 if ( ((*pLAPix) & OneBitMask[LABitInByte]) == 0 )
767 {
768 Decrement = ((256 - abs(GShiftX)) * (256 - abs(GShiftY))) / 256;
769 AddBlackToGray(CurrGX, CurrGY, Decrement);
770 Corner = 1;
771
772 if ( GShiftX != 0)
773 {
774 Decrement = ( abs(GShiftX) * (256 - abs(GShiftY))) / 256;
775
776 if ( GShiftX < 0 )
777 {
778 AddBlackToGray(CurrGX - 1, CurrGY, Decrement);
779 Corner *= 2;
780 }
781 else
782 {
783 AddBlackToGray(CurrGX + 1, CurrGY, Decrement);
784 Corner *= 3;
785 }
786 }
787
788 if (GShiftY != 0)
789 {
790 Decrement = ( abs(GShiftY) * (256 - abs(GShiftX))) / 256;
791
792 if ( GShiftY < 0 )
793 {
794 AddBlackToGray(CurrGX , CurrGY - 1, Decrement);
795 Corner *= 4;
796 }
797 else
798 {
799 AddBlackToGray(CurrGX, CurrGY + 1, Decrement);
800 Corner *= 5;
801 }
802
803 }
804
805 Decrement = ( abs(GShiftY) * (256 - abs(GShiftX))) / 256;
806 switch (Corner)
807 {
808 case 8:
809 AddBlackToGray(CurrGX - 1, CurrGY - 1, Decrement);
810 break;
811 case 12:
812 AddBlackToGray(CurrGX + 1, CurrGY - 1, Decrement);
813 break;
814 case 15:
815 AddBlackToGray(CurrGX + 1, CurrGY + 1, Decrement);
816 break;
817 case 10:
818 AddBlackToGray(CurrGX - 1, CurrGY + 1, Decrement);
819 break;
820 default:
821 pGrayPix = NULL;
822 }
823 }
824
825 }
826 }
827
828 RIMAGEUnlock( hMask );
829 RIMAGEFree( hMask );
830
831 return bRet;
832 }
833
834 Bool32 CRRotator::GetExtCoord(int32_t X, int32_t Y, int32_t * peX, int32_t * peY)
835 {
836 if ( peX )
837 {
838 *peX = 128 + X * 256;
839 }
840
841 if ( peY )
842 {
843 *peY = 128 + Y * 256;
844 }
845
846 return TRUE;
847 }
848
849 Bool32 CRRotator::RollPoint(int32_t X, int32_t Y, int32_t * pnX, int32_t * pnY)
850 {
851 if ( pnX )
852 {
853 *pnX = (int32_t)(((long double)X * mfCos) + ((long double)Y * mfSin));
854 }
855
856 if ( pnY )
857 {
858 *pnY = (int32_t)(((long double)Y * mfCos) - ((long double)X * mfSin));
859 }
860
861 return TRUE;
862 }
863
864 Bool32 CRRotator::GetGrayCoord(int32_t eX, int32_t eY, int32_t * pgX, int32_t * pgY, int32_t * psX, int32_t * psY)
865 {
866 if ( pgX )
867 {
868 *pgX = (int32_t)(eX / 256);
869
870 if ( psX )
871 *psX = (int32_t)(eX - (*pgX * 256) - 128);
872 }
873
874 if ( pgY )
875 {
876 *pgY = (int32_t)(eY / 256);
877
878 if ( psY )
879 *psY = (int32_t)(eY - (*pgY * 256) - 128);
880 }
881
882 return TRUE;
883 }
884
885
886
887 Bool32 CRRotator::UnmaskPixels(puchar pMask, puchar pGaryPix, int32_t X, int32_t Y, uint32_t wLineLen, int32_t ShiftX, int32_t ShiftY)
888 {
889 if ( *(pMask + (Y * wLineLen + X)) )
890 {
891 *(pMask + (Y * wLineLen + X)) = 0;
892 *pGaryPix = 255;
893 }
894
895 if ( ShiftX > 0 && X < (int32_t)(wLineLen - 1) )
896 {
897 if ( *(pMask + (Y * wLineLen + X + 1)) )
898 {
899 *(pMask + (Y * wLineLen + X + 1)) = 0;
900 *( pGaryPix + 1 ) = 255;
901 }
902 }
903
904 if ( ShiftX < 0 && X > 1 )
905 {
906 if ( *(pMask + (Y * wLineLen + X - 1)) )
907 {
908 *(pMask + (Y * wLineLen + X - 1)) = 0;
909 *( pGaryPix - 1 ) = 255;
910 }
911 }
912
913 return TRUE;
914 }
915
916 Bool32 CRRotator::AddBlackToGray(int32_t X, int32_t Y, uchar Gray)
917 {
918 static puchar pGrayPixel;
919
920 pGrayPixel = (puchar)mdDIBOut->GetPtrToPixel(X, Y);
921
922 if ( pGrayPixel )
923 {
924 *pGrayPixel = (Gray > *pGrayPixel ? 0 : *pGrayPixel - Gray);
925 return TRUE;
926 }
927
928 return FALSE;
929 }
930
931 void CRRotator::AllocWorkBuffers(uint32_t wStringBufferRange)
932 {
933 if (mwTablesRange)
934 {
935 hHShiftTable = RIMAGEDAlloc((mwTablesRange + 1)*4,"Rotator::AllocWorkBuffer - hor shift table");
936 HShiftTable = static_cast<int32_t*>(RIMAGELock(hHShiftTable));
937 hVShiftTable = RIMAGEDAlloc((mwTablesRange + 1)*4,"Rotator::AllocWorkBuffer - vert shift table");
938 VShiftTable = static_cast<uint32_t*>(RIMAGELock(hVShiftTable));
939 hVShiftLenght = RIMAGEDAlloc((mwTablesRange + 1)*4,"Rotator::AllocWorkBuffer - vl shift table");
940 VShiftLenght = static_cast<uint32_t*>(RIMAGELock(hVShiftLenght));
941 }
942
943 if ( wStringBufferRange )
944 {
945 //hBufferForGray = RIMAGEAlloc( wLineBytesWTo + HorisontalShiftInBytes * 2 + ( VShiftLenght[0] * 2 ) ); //буфер для конечной картинки
946 hBufferForGray = RIMAGEDAlloc( wWorkGrayBufferLenght = ( mwDescewedWidth * 4 ), "Rotator::AllocWorkBuffer - buffer for gray"); //буфер для конечной картинки
947 BufferForGray = (puchar)RIMAGELock(hBufferForGray);
948 }
949
950 }
951
952
953 void CRRotator::FreeWorkBuffers()
954 {
955 mwTablesRange = 0;
956
957 if ( hHShiftTable )
958 {
959 RIMAGEFree(hHShiftTable);
960 hHShiftTable = NULL;
961 HShiftTable = NULL;
962 }
963
964 if ( hVShiftTable )
965 {
966 RIMAGEFree(hVShiftTable);
967 hVShiftTable = NULL;
968 VShiftTable = NULL;
969 }
970
971 if ( hVShiftLenght )
972 {
973 RIMAGEFree(hVShiftLenght);
974 hVShiftLenght = NULL;
975 VShiftLenght = NULL;
976 }
977
978 if (hBufferForGray)
979 {
980 RIMAGEFree(hBufferForGray);
981 hBufferForGray = NULL;
982 BufferForGray = NULL;
983 }
984 }
985
986 Bool32 CRRotator::RotatePoint(int32_t iX, int32_t iY, int32_t * prX, int32_t * prY)
987 {
988 int32_t tY;
989
990 if ( VShiftTable == NULL || HShiftTable == NULL)
991 {
992 return FALSE;
993 }
994
995 if ( iX > -1 && iX < (int32_t)mwOriginalWidth &&
996 iY > -1 && iY < (int32_t)mwOriginalHeight )
997 {
998 if ( mfTang > 0)
999 {
1000 *prY = iY - VShiftTable[iX] + AtY;
1001
1002 if ( *prY < 0 || *prY >= (int32_t)mwTablesRange )
1003 {
1004 *prX = -1;
1005 *prY = -1;
1006 return FALSE;
1007 }
1008
1009 *prX = iX + HShiftTable[*prY] + AtX;
1010 return TRUE;
1011 }
1012 else
1013 {
1014 tY = mwOriginalHeight - (iY + 1);
1015 tY = tY - VShiftTable[iX] + AtY;
1016
1017 if ( tY < 0 || tY >= (int32_t)mwTablesRange )
1018 {
1019 *prX = -1;
1020 *prY = -1;
1021 return FALSE;
1022 }
1023
1024 *prX = iX + HShiftTable[tY] + AtX;
1025 *prY = mwDescewedHeight - (tY + 2);
1026 return TRUE;
1027 }
1028 }
1029 return FALSE;
1030 }
1031
1032 void CRRotator::ComposeLineG(PCTDIB cDIBIn, int32_t iDirect, uint32_t wLine, uint32_t wBuffLen)
1033 {
1034 uint32_t j;
1035 uint32_t StartByte;
1036 uint32_t EndByte;
1037 uint32_t FulBytes;
1038 uint32_t PixelSize = cDIBIn->GetPixelSize() / 8;
1039 int32_t PosInBuff;
1040 uint32_t Copy = 0;
1041 puchar PixFrom;
1042 uint32_t wLines = cDIBIn->GetLinesNumber();
1043
1044 for ( j = 0; j < wBuffLen; )
1045 {
1046 StartByte = j * PixelSize; //откуда начнем
1047 EndByte = (j + VShiftLenght[j]) * PixelSize; //последний копируемый
1048
1049 FulBytes = EndByte - StartByte + 1;
1050
1051 if ( VShiftLenght[j] == 0 )
1052 {
1053 j++;
1054 continue;
1055 }
1056
1057 // если есть строка исходной картинки
1058 PixFrom = NULL;
1059 PosInBuff = ( HShiftTable[wLine] * PixelSize) + StartByte;
1060
1061 if ( wLine + VShiftTable[j] >= AtY && wLine + VShiftTable[j] < ToY )
1062 {
1063 if ( iDirect > 0 )
1064 {
1065 PixFrom = (puchar)cDIBIn->GetPtrToPixel(j,wLine + VShiftTable[j] - AtY);
1066 }
1067 else
1068 {
1069 PixFrom = (puchar)cDIBIn->GetPtrToPixel(j,wLines - (wLine + VShiftTable[j] - AtY));
1070 }
1071 }
1072 // Allex 27.03.00
1073 // слабое место. на некоторых файлах возникают прблемы с отписыванием в BufferForGray - пытается отписать
1074 // туда больше чем длина файла. возможно гсвязано с размером пиксела в цветном файле.
1075 if ( PosInBuff < (int32_t)wWorkGrayBufferLenght )
1076 {
1077 FulBytes = FulBytes > wWorkGrayBufferLenght - PosInBuff ? wWorkGrayBufferLenght - PosInBuff : FulBytes;
1078
1079 if ( PixFrom )
1080 {
1081 // копируем следующий кусок
1082 memcpy(BufferForGray + PosInBuff,PixFrom, FulBytes );
1083 }
1084 else // if ( pixfrom )
1085 {
1086 memset(BufferForGray + PosInBuff,BitFillforGray, FulBytes );
1087 }
1088 }
1089
1090 Copy += FulBytes;
1091 j+= VShiftLenght[j];
1092 }
1093 }
1094 //////////////////////////////////////////////////////////////////////////////////////////////////////////
1095 // end of file