Debian Codegraph @

components/Image32/source/Img32.Transform.pas

raw
1 unit Img32.Transform;
2
3 (*******************************************************************************
4 * Author : Angus Johnson *
5 * Version : 4.7 *
6 * Date : 6 January 2025 *
7 * Website : http://www.angusj.com *
8 * Copyright : Angus Johnson 2019-2025 *
9 * Purpose : Affine and projective transformation routines for TImage32 *
10 * License : http://www.boost.org/LICENSE_1_0.txt *
11 *******************************************************************************)
12
13 interface
14
15 {$I Img32.inc}
16
17 uses
18 SysUtils, Classes, Math, Types, Img32, Img32.Vector;
19
20 type
21 TMatrixD = array [0..2, 0..2] of double;
22
23 //Matrix functions
24 function IsIdentityMatrix(const matrix: TMatrixD): Boolean;
25 {$IFDEF INLINE} inline; {$ENDIF}
26 function IsValidMatrix(const matrix: TMatrixD): Boolean;
27 {$IFDEF INLINE} inline; {$ENDIF}
28 function Matrix(const m00, m01, m02, m10, m11, m12, m20, m21, m22: double): TMatrixD;
29 function MatrixDeterminant(const matrix: TMatrixD): double;
30 function MatrixAdjugate(const matrix: TMatrixD): TMatrixD;
31 function MatrixInvert(var matrix: TMatrixD): Boolean;
32
33 // Note: Matrix multiplication IS NOT commutative hence ...
34 procedure MatrixMultiply(var matrix1: TMatrixD; const matrix2: TMatrixD);
35 procedure MatrixMultiply2(const matrix1: TMatrixD; var matrix2: TMatrixD);
36
37 procedure MatrixApply(const matrix: TMatrixD;
38 var x, y: double); overload; {$IFDEF INLINE} inline; {$ENDIF}
39 procedure MatrixApply(const matrix: TMatrixD;
40 var pt: TPointD); overload; {$IFDEF INLINE} inline; {$ENDIF}
41 procedure MatrixApply(const matrix: TMatrixD; var rec: TRect); overload;
42 procedure MatrixApply(const matrix: TMatrixD; var rec: TRectD); overload;
43 procedure MatrixApply(const matrix: TMatrixD; var path: TPathD); overload;
44 procedure MatrixApply(const matrix: TMatrixD; var paths: TPathsD); overload;
45 procedure MatrixApply(const matrix: TMatrixD;
46 img: TImage32; scaleAdjust: Boolean = false); overload; {$IFDEF INLINE} inline; {$ENDIF}
47 procedure MatrixApply(const matrix: TMatrixD;
48 img, targetImg: TImage32; scaleAdjust: Boolean = false); overload; {$IFDEF INLINE} inline; {$ENDIF}
49
50 procedure MatrixSkew(var matrix: TMatrixD; angleX, angleY: double);
51
52 procedure MatrixScale(var matrix: TMatrixD; scale: double); overload;
53 procedure MatrixScale(var matrix: TMatrixD; scaleX, scaleY: double); overload;
54
55 procedure MatrixRotate(var matrix: TMatrixD; angRad: double); overload;
56 procedure MatrixRotate(var matrix: TMatrixD; const center: TPointD; angRad: double); overload;
57
58 procedure MatrixTranslate(var matrix: TMatrixD; dx, dy: double);
59
60 // The following MatrixExtract routines assume here is no skew
61 procedure MatrixExtractScale(const mat: TMatrixD; out scale: double); overload;
62 procedure MatrixExtractScale(const mat: TMatrixD; out X, Y: double); overload;
63 procedure MatrixExtractTranslation(const mat: TMatrixD; out dx, dy: double);
64 procedure MatrixExtractRotation(const mat: TMatrixD; out angle: double);
65 // MatrixExtractAll - except skew :)
66 function MatrixExtractAll(const mat: TMatrixD; out angle: double;
67 out scale, trans: TPointD): Boolean;
68
69 // AffineTransformImage: will automagically translate the image
70 // Note: when the "scaleAdjust" parameter is enabled, it prevents antialiasing
71 // from extending way outside of images when they are being enlarged
72 // significantly (> 2 times) and rotated concurrently
73 function AffineTransformImage(img: TImage32; matrix: TMatrixD;
74 scaleAdjust: Boolean = false): TPoint; overload; {$IFDEF INLINE} inline; {$ENDIF}
75 function AffineTransformImage(img, targetImg: TImage32; matrix: TMatrixD;
76 scaleAdjust: Boolean = false): TPoint; overload;
77
78 // ProjectiveTransform:
79 // srcPts, dstPts => each path must contain 4 points
80 // margins => the margins around dstPts (in the dest. projective).
81 // Margins are only meaningful when srcPts are inside the image.
82 function ProjectiveTransform(img: TImage32;
83 const srcPts, dstPts: TPathD; const margins: TRect): Boolean; overload; {$IFDEF INLINE} inline; {$ENDIF}
84 function ProjectiveTransform(img, targetImg: TImage32;
85 const srcPts, dstPts: TPathD; const margins: TRect): Boolean; overload;
86
87 function SplineVertTransform(img: TImage32; const topSpline: TPathD;
88 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean; overload; {$IFDEF INLINE} inline; {$ENDIF}
89 function SplineVertTransform(img, targetImg: TImage32; const topSpline: TPathD;
90 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean; overload;
91 function SplineHorzTransform(img: TImage32; const leftSpline: TPathD;
92 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean; overload; {$IFDEF INLINE} inline; {$ENDIF}
93 function SplineHorzTransform(img, targetImg: TImage32; const leftSpline: TPathD;
94 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean; overload;
95
96 type
97 PWeightedColor = ^TWeightedColor;
98 TWeightedColor = {$IFDEF RECORD_METHODS} record {$ELSE} object {$ENDIF}
99 private
100 fAddCount : Integer;
101 fAlphaTot : Int64;
102 fColorTotR: Int64;
103 fColorTotG: Int64;
104 fColorTotB: Int64;
105 function GetColor: TColor32;
106 public
107 procedure Reset; overload; {$IFDEF INLINE} inline; {$ENDIF}
108 procedure Reset(c: TColor32; w: Integer = 1); overload; {$IFDEF INLINE} inline; {$ENDIF}
109 procedure Add(c: TColor32; w: Integer); overload; {$IFDEF INLINE_COMPATIBLE} inline; {$ENDIF}
110 procedure Add(c: TColor32); overload; {$IFDEF INLINE} inline; {$ENDIF}
111 procedure Add(const other: TWeightedColor); overload;
112 {$IFDEF INLINE} inline; {$ENDIF}
113 procedure Subtract(c: TColor32; w: Integer); overload;
114 procedure Subtract(c: TColor32); overload; {$IFDEF INLINE} inline; {$ENDIF}
115 procedure Subtract(const other: TWeightedColor); overload;
116 {$IFDEF INLINE} inline; {$ENDIF}
117 function AddSubtract(addC, subC: TColor32): Boolean; {$IFDEF INLINE_COMPATIBLE} inline; {$ENDIF}
118 function AddNoneSubtract(c: TColor32): Boolean; {$IFDEF INLINE_COMPATIBLE} inline; {$ENDIF}
119 procedure AddWeight(w: Integer); {$IFDEF INLINE} inline; {$ENDIF}
120 property AddCount: Integer read fAddCount;
121 property Color: TColor32 read GetColor;
122 property Weight: integer read fAddCount;
123 end;
124 TArrayOfWeightedColor = array of TWeightedColor;
125
126 const
127 IdentityMatrix: TMatrixD = ((1, 0, 0),(0, 1, 0),(0, 0, 1));
128
129 implementation
130
131 uses Img32.Resamplers;
132
133 resourcestring
134 rsInvalidScale = 'Invalid matrix scaling factor (0)';
135
136 const
137 DivOneByXTableSize = 1024;
138
139 {$IFDEF CPUX86}
140 // Use faster Trunc for x86 code in this unit.
141 Trunc: function(Value: Double): Integer = __Trunc;
142 {$ENDIF CPUX86}
143
144 var
145 // DivOneByXTable[x] = 1/x
146 DivOneByXTable: array[0 .. DivOneByXTableSize -1] of Double;
147
148 //------------------------------------------------------------------------------
149 // Matrix functions
150 //------------------------------------------------------------------------------
151
152 function IsIdentityMatrix(const matrix: TMatrixD): Boolean;
153 begin
154 result := (matrix[0,0] = 1) and (matrix[0,1] = 0) and (matrix[0,2] = 0) and
155 (matrix[1,0] = 0) and (matrix[1,1] = 1) and (matrix[1,2] = 0) and
156 (matrix[2,0] = 0) and (matrix[2,1] = 0) and (matrix[2,2] = 1);
157 end;
158 //------------------------------------------------------------------------------
159
160 function IsValidMatrix(const matrix: TMatrixD): Boolean;
161 begin
162 result := matrix[2][2] = 1.0;
163 end;
164 //------------------------------------------------------------------------------
165
166 function Matrix(const m00, m01, m02, m10, m11, m12, m20, m21, m22: double): TMatrixD;
167 begin
168 Result[0,0] := m00; Result[0,1] := m01; Result[0,2] := m02;
169 Result[1,0] := m10; Result[1,1] := m11; Result[1,2] := m12;
170 Result[2,0] := m20; Result[2,1] := m21; Result[2,2] := m22;
171 end;
172 //------------------------------------------------------------------------------
173
174 function Det4(a1, a2, b1, b2: double): double; {$IFDEF INLINE} inline; {$ENDIF}
175 begin
176 Result := a1 * b2 - a2 * b1;
177 end;
178 //------------------------------------------------------------------------------
179
180 function Det9(a1, a2, a3, b1, b2, b3, c1, c2, c3: double): double;
181 {$IFDEF INLINE} inline; {$ENDIF}
182 begin
183 Result := a1 * Det4(b2, b3, c2, c3) -
184 b1 * Det4(a2, a3, c2, c3) +
185 c1 * Det4(a2, a3, b2, b3);
186 end;
187 //------------------------------------------------------------------------------
188
189 function MatrixDeterminant(const matrix: TMatrixD): double;
190 {$IFDEF INLINE} inline; {$ENDIF}
191 begin
192 Result := Det9(matrix[0,0], matrix[1,0], matrix[2,0],
193 matrix[0,1], matrix[1,1], matrix[2,1],
194 matrix[0,2], matrix[1,2], matrix[2,2]);
195 end;
196 //------------------------------------------------------------------------------
197
198 function MatrixAdjugate(const matrix: TMatrixD): TMatrixD;
199 begin
200 //https://en.wikipedia.org/wiki/Adjugate_matrix
201 Result[0,0] := Det4(matrix[1,1], matrix[1,2], matrix[2,1], matrix[2,2]);
202 Result[0,1] := -Det4(matrix[0,1], matrix[0,2], matrix[2,1], matrix[2,2]);
203 Result[0,2] := Det4(matrix[0,1], matrix[0,2], matrix[1,1], matrix[1,2]);
204
205 Result[1,0] := -Det4(matrix[1,0], matrix[1,2], matrix[2,0], matrix[2,2]);
206 Result[1,1] := Det4(matrix[0,0], matrix[0,2], matrix[2,0], matrix[2,2]);
207 Result[1,2] := -Det4(matrix[0,0], matrix[0,2], matrix[1,0], matrix[1,2]);
208
209 Result[2,0] := Det4(matrix[1,0], matrix[1,1], matrix[2,0], matrix[2,1]);
210 Result[2,1] := -Det4(matrix[0,0], matrix[0,1], matrix[2,0], matrix[2,1]);
211 Result[2,2] := Det4(matrix[0,0], matrix[0,1], matrix[1,0], matrix[1,1]);
212 end;
213 //------------------------------------------------------------------------------
214
215 procedure MatrixApply(const matrix: TMatrixD; var x, y: double);
216 var
217 tmpX: double;
218 begin
219 tmpX := x;
220 x := tmpX * matrix[0, 0] + y * matrix[1, 0] + matrix[2, 0];
221 y := tmpX * matrix[0, 1] + y * matrix[1, 1] + matrix[2, 1];
222 end;
223 //------------------------------------------------------------------------------
224
225 procedure MatrixApply(const matrix: TMatrixD; var pt: TPointD);
226 var
227 tmpX: double;
228 begin
229 tmpX := pt.x;
230 pt.X := tmpX * matrix[0, 0] + pt.Y * matrix[1, 0] + matrix[2, 0];
231 pt.Y := tmpX * matrix[0, 1] + pt.Y * matrix[1, 1] + matrix[2, 1];
232 end;
233 //------------------------------------------------------------------------------
234
235 procedure MatrixApply(const matrix: TMatrixD; var rec: TRect);
236 var
237 path: TPathD;
238 begin
239 if not IsValidMatrix(matrix) then Exit;
240 path := Rectangle(rec);
241 MatrixApply(matrix, path);
242 rec := GetBounds(path);
243 end;
244 //------------------------------------------------------------------------------
245
246 procedure MatrixApply(const matrix: TMatrixD; var rec: TRectD);
247 var
248 path: TPathD;
249 begin
250 if not IsValidMatrix(matrix) then Exit;
251 path := Rectangle(rec);
252 MatrixApply(matrix, path);
253 rec := GetBoundsD(path);
254 end;
255 //------------------------------------------------------------------------------
256
257 procedure MatrixApply(const matrix: TMatrixD; var path: TPathD);
258 var
259 i, len: integer;
260 tmpX: double;
261 pp: PPointD;
262 begin
263 len := Length(path);
264 if (len = 0) or IsIdentityMatrix(matrix) or
265 not IsValidMatrix(matrix) then Exit;
266 pp := @path[0];
267 for i := 0 to len -1 do
268 begin
269 tmpX := pp.X;
270 pp.X := tmpX * matrix[0, 0] + pp.Y * matrix[1, 0] + matrix[2, 0];
271 pp.Y := tmpX * matrix[0, 1] + pp.Y * matrix[1, 1] + matrix[2, 1];
272 inc(pp);
273 end;
274 end;
275 //------------------------------------------------------------------------------
276
277 procedure MatrixApply(const matrix: TMatrixD; var paths: TPathsD);
278 var
279 i,j,len: integer;
280 tmpX: double;
281 pp: PPointD;
282 begin
283 if not Assigned(paths) or IsIdentityMatrix(matrix) or
284 not IsValidMatrix(matrix) then Exit;
285
286 for i := 0 to High(paths) do
287 begin
288 len := Length(paths[i]);
289 if len = 0 then Continue;
290 pp := @paths[i][0];
291 for j := 0 to High(paths[i]) do
292 begin
293 tmpX := pp.X;
294 pp.X := tmpX * matrix[0, 0] + pp.Y * matrix[1, 0] + matrix[2, 0];
295 pp.Y := tmpX * matrix[0, 1] + pp.Y * matrix[1, 1] + matrix[2, 1];
296 inc(pp);
297 end;
298 end;
299 end;
300 //------------------------------------------------------------------------------
301
302 procedure MatrixApply(const matrix: TMatrixD;
303 img: TImage32; scaleAdjust: Boolean);
304 begin
305 AffineTransformImage(img, matrix, scaleAdjust);
306 end;
307 //------------------------------------------------------------------------------
308
309 procedure MatrixApply(const matrix: TMatrixD;
310 img, targetImg: TImage32; scaleAdjust: Boolean);
311 begin
312 AffineTransformImage(img, targetImg, matrix, scaleAdjust);
313 end;
314 //------------------------------------------------------------------------------
315
316 procedure MatrixMultiply(var matrix1: TMatrixD; const matrix2: TMatrixD);
317 var
318 i, j: Integer;
319 m: TMatrixD;
320 begin
321 for i := 0 to 2 do
322 for j := 0 to 2 do
323 m[i, j] :=
324 (matrix1[i, 0] * matrix2[0, j]) +
325 (matrix1[i, 1] * matrix2[1, j]) +
326 (matrix1[i, 2] * matrix2[2, j]);
327 matrix1 := m;
328 end;
329 //------------------------------------------------------------------------------
330
331 procedure MatrixMultiply2(const matrix1: TMatrixD; var matrix2: TMatrixD);
332 var
333 i, j: Integer;
334 m: TMatrixD;
335 begin
336 for i := 0 to 2 do
337 for j := 0 to 2 do
338 m[i, j] :=
339 (matrix1[i, 0] * matrix2[0, j]) +
340 (matrix1[i, 1] * matrix2[1, j]) +
341 (matrix1[i, 2] * matrix2[2, j]);
342 matrix2 := m;
343 end;
344 //------------------------------------------------------------------------------
345
346 procedure MatrixScale(var matrix: TMatrixD; scaleX, scaleY: double);
347 var
348 m: TMatrixD;
349 begin
350 m := IdentityMatrix;
351 if (scaleX = 0) or (scaleY = 0) then
352 raise Exception(rsInvalidScale);
353
354 if ValueAlmostOne(scaleX) and ValueAlmostOne(scaleY) then Exit;
355 m[0, 0] := scaleX;
356 m[1, 1] := scaleY;
357 MatrixMultiply(matrix, m);
358 end;
359 //------------------------------------------------------------------------------
360
361 procedure MatrixScale(var matrix: TMatrixD; scale: double);
362 begin
363 if (scale = 0) or (scale = 1) then Exit;
364 MatrixScale(matrix, scale, scale);
365 end;
366 //------------------------------------------------------------------------------
367
368 procedure MatrixRotate(var matrix: TMatrixD;
369 const center: TPointD; angRad: double);
370 var
371 m: TMatrixD;
372 sinA, cosA: double;
373 begin
374 if not PointsEqual(center, NullPointD) then
375 begin
376 NormalizeAngle(angRad);
377 if angRad = 0 then Exit;
378 {$IFNDEF CLOCKWISE_ROTATION_WITH_NEGATIVE_ANGLES}
379 angRad := -angRad; //negated angle because of inverted Y-axis.
380 {$ENDIF}
381 m := IdentityMatrix;
382 MatrixTranslate(matrix, -center.X, -center.Y);
383 GetSinCos(angRad, sinA, cosA);
384 m := IdentityMatrix;
385 m[0, 0] := cosA; m[1, 0] := sinA;
386 m[0, 1] := -sinA; m[1, 1] := cosA;
387 MatrixMultiply(matrix, m);
388 MatrixTranslate(matrix, center.X, center.Y);
389 end
390 else
391 MatrixRotate(matrix, angRad)
392 end;
393 //------------------------------------------------------------------------------
394
395 procedure MatrixRotate(var matrix: TMatrixD; angRad: double);
396 var
397 m: TMatrixD;
398 sinA, cosA: double;
399 begin
400 NormalizeAngle(angRad);
401 if angRad = 0 then Exit;
402 {$IFNDEF CLOCKWISE_ROTATION_WITH_NEGATIVE_ANGLES}
403 angRad := -angRad; //negated angle because of inverted Y-axis.
404 {$ENDIF}
405 m := IdentityMatrix;
406 GetSinCos(angRad, sinA, cosA);
407 m := IdentityMatrix;
408 m[0, 0] := cosA; m[1, 0] := sinA;
409 m[0, 1] := -sinA; m[1, 1] := cosA;
410 MatrixMultiply(matrix, m);
411 end;
412 //------------------------------------------------------------------------------
413
414
415 procedure MatrixTranslate(var matrix: TMatrixD; dx, dy: double);
416 var
417 m: TMatrixD;
418 begin
419 if ValueAlmostZero(dx) and ValueAlmostZero(dy) then Exit;
420 m := IdentityMatrix;
421 m[2, 0] := dx;
422 m[2, 1] := dy;
423 MatrixMultiply(matrix, m);
424 end;
425 //------------------------------------------------------------------------------
426
427 procedure ScaleInternal(var matrix: TMatrixD; s: double);
428 var
429 i, j: Integer;
430 begin
431 for i := 0 to 2 do
432 for j := 0 to 2 do
433 matrix[i,j] := matrix[i,j] * s;
434 end;
435 //------------------------------------------------------------------------------
436
437 function MatrixInvert(var matrix: TMatrixD): Boolean;
438 var
439 d: double;
440 const
441 tolerance = 1.0E-5;
442 begin
443 d := MatrixDeterminant(matrix);
444 Result := abs(d) > tolerance;
445 if Result then
446 begin
447 matrix := MatrixAdjugate(matrix);
448 ScaleInternal(matrix, 1/d);
449 end;
450 end;
451 //------------------------------------------------------------------------------
452
453 procedure MatrixSkew(var matrix: TMatrixD; angleX, angleY: double);
454 var
455 m: TMatrixD;
456 begin
457 if ValueAlmostZero(angleX) and ValueAlmostZero(angleY) then Exit;
458 m := IdentityMatrix;
459 m[1, 0] := tan(angleX);
460 m[0, 1] := tan(angleY);
461 MatrixMultiply(matrix, m);
462 end;
463 //------------------------------------------------------------------------------
464
465 procedure MatrixExtractScale(const mat: TMatrixD; out X, Y: double);
466 begin
467 // https://stackoverflow.com/a/32125700/359538
468 X := Sqrt(Sqr(mat[0,0]) + Sqr(mat[0,1]));
469 //Y := Sqrt(Sqr(mat[1,0]) + Sqr(mat[1,1]));
470 Y := Abs((mat[0,0] * mat[1,1] - mat[1,0] * mat[0,1]) / X);
471 end;
472 //------------------------------------------------------------------------------
473
474 procedure MatrixExtractScale(const mat: TMatrixD; out scale: double);
475 var
476 x,y: double;
477 begin
478 MatrixExtractScale(mat, x, y);
479 scale := Average(x,y);
480 end;
481 //------------------------------------------------------------------------------
482
483 procedure MatrixExtractTranslation(const mat: TMatrixD; out dx, dy: double);
484 begin
485 dx := mat[2,0];
486 dy := mat[2,1];
487 end;
488 //------------------------------------------------------------------------------
489
490 procedure MatrixExtractRotation(const mat: TMatrixD; out angle: double);
491 begin
492 angle := ArcTan2(mat[0,1], mat[0,0]);
493 end;
494 //------------------------------------------------------------------------------
495
496 function MatrixExtractAll(const mat: TMatrixD;
497 out angle: double; out scale, trans: TPointD): Boolean;
498 var
499 m00, m01, m10, m11: double;
500 begin
501 m00 := mat[0][0]; m10 := mat[1][0];
502 m01 := mat[0][1]; m11 := mat[1][1];
503 trans.X := mat[2][0];
504 trans.Y := mat[2][1];
505
506 angle := 0;
507 scale := PointD(1,1);
508
509 Result := (m00 <> 0) or (m01 <> 0);
510 if not Result then Exit;
511
512 angle := ArcTan2(m01, m00);
513 // https://stackoverflow.com/a/32125700/359538
514 scale.X := Sqrt(Sqr(mat[0,0]) + Sqr(mat[0,1]));
515 scale.Y := (m00 * m11 - m10 * m01) / scale.X;
516 end;
517 //------------------------------------------------------------------------------
518
519 {$IFDEF USE_DOWNSAMPLER_AUTOMATICALLY}
520 function CanUseBoxDownsampler(const mat: TMatrixD; sx, sy: double): Boolean;
521 begin
522 // If the matrix looks like this after removing the scale,
523 // the box downsampler can be used. (only translation and scaling)
524 // cos(0) -sin(0) tx 1 0 tx
525 // sin(0) cos(0) ty => 0 1 ty
526 // 0 0 1 0 0 1
527
528 {
529 Result := (mat[0,0]/sx = 1) and (mat[0,1]/sx = 0) and
530 (mat[1,0]/sy = 0) and (mat[1,1]/sy = 1) and
531 (mat[2,0] = 0) and (mat[2,1] = 0) and
532 (mat[2,2] = 1);
533 }
534
535 // We can skip the divisions, because m/s is only zero if m is zero
536 // and m/s=1 is the same as m=s
537 Result := (SameValue(mat[0,0], sx)) and (mat[0,1] = 0) and
538 (mat[1,0] = 0) and (SameValue(mat[1,1], sy)) and
539 (mat[2,0] = 0) and (mat[2,1] = 0) and
540 (mat[2,2] = 1);
541 end;
542 {$ENDIF USE_DOWNSAMPLER_AUTOMATICALLY}
543
544 //------------------------------------------------------------------------------
545 // Affine Transformation
546 //------------------------------------------------------------------------------
547
548 function GetTransformBounds(img: TImage32; const matrix: TMatrixD): TRect;
549 var
550 pts: TPathD;
551 begin
552 pts := Rectangle(img.Bounds);
553 MatrixApply(matrix, pts);
554 Result := GetBounds(pts);
555 end;
556 //------------------------------------------------------------------------------
557
558 function AffineTransformImage(img: TImage32; matrix: TMatrixD;
559 scaleAdjust: Boolean): TPoint;
560 begin
561 Result := AffineTransformImage(img, img, matrix, scaleAdjust);
562 end;
563 //------------------------------------------------------------------------------
564
565 function AffineTransformImage(img, targetImg: TImage32; matrix: TMatrixD;
566 scaleAdjust: Boolean): TPoint;
567 var
568 i, j: integer;
569 newWidth, newHeight: integer;
570 sx, sy, x,y: double;
571 xLimLo, yLimLo, xLimHi, yLimHi: double;
572 pc: PColor32;
573 tmp: TArrayOfColor32;
574 dstRec: TRect;
575 resampler: TResamplerFunction;
576 {$IFDEF USE_DOWNSAMPLER_AUTOMATICALLY}
577 useBoxDownsampler: Boolean;
578 {$ENDIF}
579 begin
580 Result := NullPoint;
581 if IsIdentityMatrix(matrix) or
582 img.IsEmpty or (targetImg.Resampler = 0) then
583 begin
584 if targetImg <> img then targetImg.Assign(img);
585 Exit;
586 end;
587
588 resampler := GetResampler(targetImg.Resampler);
589 if not Assigned(resampler) then
590 begin
591 if targetImg <> img then targetImg.Assign(img);
592 Exit;
593 end;
594
595 //auto-resize the image so it'll fit transformed image
596
597 dstRec := img.Bounds;
598 MatrixApply(matrix, dstRec);
599 RectWidthHeight(dstRec, newWidth, newHeight);
600
601 MatrixExtractScale(matrix, sx, sy);
602 {$IFDEF USE_DOWNSAMPLER_AUTOMATICALLY}
603 if (sx < 1.0) and (sy < 1.0) then
604 begin
605 //only use box downsampling when downsizing
606 useBoxDownsampler := CanUseBoxDownsampler(matrix, sx, sy);
607 end else
608 useBoxDownsampler := false;
609
610 if useBoxDownsampler then
611 begin
612 BoxDownSampling(img, targetImg, sx, sy);
613 Exit;
614 end;
615 {$ENDIF}
616
617 if scaleAdjust then
618 begin
619 sx := Max(1, sx * 0.5);
620 sy := Max(1, sy * 0.5);
621 end;
622
623 //auto-translate the image too
624 Result := dstRec.TopLeft;
625
626 //starting with the result pixel coords, reverse lookup
627 //the fractional coordinates in the untransformed image
628 if not MatrixInvert(matrix) then
629 begin
630 if targetImg <> img then targetImg.Assign(img);
631 Exit;
632 end;
633
634 NewColor32Array(tmp, newWidth * newHeight, True);
635 pc := @tmp[0];
636 xLimLo := -0.5/sx;
637 xLimHi := img.Width + 0.5/sx;
638 yLimLo := -0.5/sy;
639 yLimHi := img.Height + 0.5/sy;
640
641 for i := dstRec.Top to dstRec.Bottom -1 do
642 begin
643 for j := dstRec.Left to dstRec.Right -1 do
644 begin
645 x := j; y := i;
646 MatrixApply(matrix, x, y);
647
648 if (x <= xLimLo) or (x >= xLimHi) or (y <= yLimLo) or (y >= yLimHi) then
649 pc^ := clNone32
650 else
651 // nb: -0.5 below is needed to properly center the transformed image
652 // (and this is most obviously needed when there is large scaling)
653 pc^ := resampler(img, x - 0.5, y - 0.5);
654
655 inc(pc);
656 end;
657 end;
658
659 targetImg.AssignPixelArray(tmp, newWidth, newHeight);
660 end;
661
662 //------------------------------------------------------------------------------
663 // Projective Transformation
664 //------------------------------------------------------------------------------
665
666 procedure MatrixMulCoord(const matrix: TMatrixD; var x,y,z: double);
667 {$IFDEF INLINE} inline; {$ENDIF}
668 var
669 xx, yy: double;
670 begin
671 xx := x; yy := y;
672 x := matrix[0,0] *xx + matrix[0,1] *yy + matrix[0,2] *z;
673 y := matrix[1,0] *xx + matrix[1,1] *yy + matrix[1,2] *z;
674 z := matrix[2,0] *xx + matrix[2,1] *yy + matrix[2,2] *z;
675 end;
676 //------------------------------------------------------------------------------
677
678 function BasisToPoints(x1, y1, x2, y2, x3, y3, x4, y4: double): TMatrixD;
679 var
680 m2: TMatrixD;
681 z4: double;
682 begin
683 Result := Matrix(x1, x2, x3, y1, y2, y3, 1, 1, 1);
684 m2 := MatrixAdjugate(Result);
685 z4 := 1;
686 MatrixMulCoord(m2, x4, y4, z4);
687 m2 := Matrix(x4, 0, 0, 0, y4, 0, 0, 0, z4);
688 MatrixMultiply(Result, m2);
689 end;
690 //------------------------------------------------------------------------------
691
692 procedure GetSrcCoords256(const matrix: TMatrixD; var x, y: integer);
693 {$IFDEF INLINE} inline; {$ENDIF}
694 var
695 xx,yy,zz: double;
696 const
697 Q: integer = MaxInt div 256;
698 begin
699 //returns coords multiplied by 256 in anticipation of the following
700 //GetWeightedPixel function call which in turn expects the lower 8bits
701 //of the integer coord value to represent a fraction.
702 xx := x; yy := y; zz := 1;
703 MatrixMulCoord(matrix, xx, yy, zz);
704
705 if zz = 0 then
706 begin
707 if xx >= 0 then x := Q else x := -MaxInt;
708 if yy >= 0 then y := Q else y := -MaxInt;
709 end else
710 begin
711 xx := xx/zz;
712 if xx > Q then x := MaxInt
713 else if xx < -Q then x := -MaxInt
714 else x := Round(xx *256);
715
716 yy := yy/zz;
717 if yy > Q then y := MaxInt
718 else if yy < -Q then y := -MaxInt
719 else y := Round(yy *256);
720 end;
721 end;
722 //------------------------------------------------------------------------------
723
724 procedure GetSrcCoords(const matrix: TMatrixD; var x, y: double);
725 {$IFDEF INLINE} inline; {$ENDIF}
726 var
727 zz: double;
728 const
729 Q: integer = MaxInt div 256;
730 begin
731 //returns coords multiplied by 256 in anticipation of the following
732 //GetWeightedPixel function call which in turn expects the lower 8bits
733 //of the integer coord value to represent a fraction.
734 zz := 1;
735 MatrixMulCoord(matrix, x, y, zz);
736
737 if zz = 0 then
738 begin
739 if x >= 0 then x := Q else x := -MaxDouble;
740 if y >= 0 then y := Q else y := -MaxDouble;
741 end else
742 begin
743 x := x/zz;
744 if x > Q then x := MaxDouble
745 else if x < -Q then x := -MaxDouble;
746
747 y := y/zz;
748 if y > Q then y := MaxDouble
749 else if y < -Q then y := -MaxDouble
750 end;
751 end;
752 //------------------------------------------------------------------------------
753
754 function GetProjectionMatrix(const srcPts, dstPts: TPathD): TMatrixD;
755 var
756 dstMat: TMatrixD;
757 begin
758 if (length(srcPts) <> 4) or (length(dstPts) <> 4) then
759 begin
760 Result := IdentityMatrix;
761 Exit;
762 end;
763 Result := BasisToPoints(srcPts[0].X, srcPts[0].Y,
764 srcPts[1].X, srcPts[1].Y, srcPts[2].X, srcPts[2].Y, srcPts[3].X, srcPts[3].Y);
765 dstMat := BasisToPoints(dstPts[0].X, dstPts[0].Y,
766 dstPts[1].X, dstPts[1].Y, dstPts[2].X, dstPts[2].Y, dstPts[3].X, dstPts[3].Y);
767 MatrixMultiply(Result, MatrixAdjugate(dstMat));
768 end;
769 //------------------------------------------------------------------------------
770
771 function ProjectiveTransform(img: TImage32;
772 const srcPts, dstPts: TPathD; const margins: TRect): Boolean;
773 begin
774 Result := ProjectiveTransform(img, img, srcPts, dstPts, margins);
775 end;
776 //------------------------------------------------------------------------------
777
778 function ProjectiveTransform(img, targetImg: TImage32;
779 const srcPts, dstPts: TPathD; const margins: TRect): Boolean;
780 var
781 w,h,i,j: integer;
782 x,y: double;
783 xLimLo, yLimLo, xLimHi, yLimHi: double;
784 rec: TRect;
785 dstPts2: TPathD;
786 mat: TMatrixD;
787 tmp: TArrayOfColor32;
788 pc: PColor32;
789 resampler: TResamplerFunction;
790 begin
791 //https://math.stackexchange.com/a/339033/384709
792
793 if targetImg.Resampler = 0 then
794 resampler := nil else
795 resampler := GetResampler(targetImg.Resampler);
796
797 Result := Assigned(resampler) and not img.IsEmpty and
798 (Length(dstPts) = 4) and IsPathConvex(dstPts);
799 if not Result then
800 begin
801 if targetImg <> img then targetImg.Assign(img);
802 Exit;
803 end;
804
805 rec := GetBounds(dstPts);
806 dec(rec.Left, margins.Left);
807 dec(rec.Top, margins.Top);
808 inc(rec.Right, margins.Right);
809 inc(rec.Bottom, margins.Bottom);
810 dstPts2 := TranslatePath(dstPts, -rec.Left, -rec.Top);
811
812 xLimLo := -0.5;
813 xLimHi := img.Width + 0.5;
814 yLimLo := -0.5;
815 yLimHi := img.Height + 0.5;
816
817 mat := GetProjectionMatrix(srcPts, dstPts2);
818 RectWidthHeight(rec, w, h);
819 NewColor32Array(tmp, w * h, True);
820 pc := @tmp[0];
821 for i := 0 to h -1 do
822 for j := 0 to w -1 do
823 begin
824 x := j; y := i;
825 GetSrcCoords(mat, x, y);
826
827 if (x <= xLimLo) or (x >= xLimHi) or (y <= yLimLo) or (y >= yLimHi) then
828 pc^ := clNone32
829 else
830 pc^ := resampler(img, x -0.5, y -0.5);
831 inc(pc);
832 end;
833
834 targetImg.BlockNotify;
835 targetImg.AssignPixelArray(tmp, w, h);
836 targetImg.UnblockNotify;
837 end;
838
839 //------------------------------------------------------------------------------
840 // Spline transformations
841 //------------------------------------------------------------------------------
842
843 function ReColor(color, newColor: TColor32): TColor32;
844 {$IFDEF INLINE} inline; {$ENDIF}
845 begin
846 Result := (color and $FF000000) or newColor;
847 end;
848 //------------------------------------------------------------------------------
849
850 function InterpolateSegX(const pt1, pt2: TPointD): TPathD;
851 var
852 i, x1, x2: integer;
853 xo,dydx: double;
854 begin
855 Result := nil;
856 if pt2.X > pt1.X then
857 begin
858 x1 := Ceil(pt1.X);
859 x2 := Ceil(pt2.X);
860 if x1 = x2 then Exit;
861 dydx := (pt2.Y - pt1.Y)/(pt2.X - pt1.X);
862 xo := x1 -pt1.X;
863 NewPointDArray(Result, x2-x1, True);
864 for i:= 0 to x2 - x1 -1 do
865 begin
866 Result[i].X := x1 +i;
867 Result[i].Y := pt1.Y + dydx * (xo +i);
868 end;
869 end else
870 begin
871 x1 := Floor(pt1.X);
872 x2 := Floor(pt2.X);
873 if x1 = x2 then Exit;
874 dydx := (pt2.Y - pt1.Y)/(pt2.X - pt1.X);
875 xo := x1 -pt1.X;
876 NewPointDArray(Result, x1-x2, True);
877 for i:= 0 to x1 - x2 -1 do
878 begin
879 Result[i].X := x1 -i;
880 Result[i].Y := pt1.Y + dydx * (xo -i);
881 end;
882 end;
883 end;
884 //------------------------------------------------------------------------------
885
886 function InterpolateSegY(const pt1, pt2: TPointD): TPathD;
887 var
888 i, y1,y2: integer;
889 yo,dxdy: double;
890 begin
891 Result := nil;
892 if pt2.Y > pt1.Y then
893 begin
894 y1 := Ceil(pt1.Y);
895 y2 := Ceil(pt2.Y);
896 if y1 = y2 then Exit;
897 dxdy := (pt2.X - pt1.X)/(pt2.Y - pt1.Y);
898 yo := y1 -pt1.Y;
899 NewPointDArray(Result, y2-y1, True);
900 for i:= 0 to y2 - y1 -1 do
901 begin
902 Result[i].Y := y1 +i;
903 Result[i].X := pt1.X + dxdy * (yo +i);
904 end;
905 end else
906 begin
907 y1 := Floor(pt1.Y);
908 y2 := Floor(pt2.Y);
909 if y1 = y2 then Exit;
910 dxdy := (pt2.X - pt1.X)/(pt2.Y - pt1.Y);
911 yo := y1 -pt1.Y;
912 NewPointDArray(Result, y1-y2, True);
913 for i:= 0 to y1 - y2 -1 do
914 begin
915 Result[i].Y := y1 -i;
916 Result[i].X := pt1.X + dxdy * (yo -i);
917 end;
918 end;
919 end;
920 //------------------------------------------------------------------------------
921
922 function InterpolatePathForX(const path: TPathD): TPathD;
923 var
924 i,len: integer;
925 tmp: TPathD;
926 begin
927 Result := nil;
928 len := length(path);
929 if len < 2 then Exit;
930 for i := 1 to len -1 do
931 begin
932 tmp := InterpolateSegX(path[i-1], path[i]);
933 ConcatPaths(Result, tmp);
934 end;
935 end;
936 //------------------------------------------------------------------------------
937
938 function InterpolatePathForY(const path: TPathD): TPathD;
939 var
940 i, len: integer;
941 tmp: TPathD;
942 begin
943 Result := nil;
944 len := length(path);
945 if len < 2 then Exit;
946 for i := 1 to len -1 do
947 begin
948 tmp := InterpolateSegY(path[i-1], path[i]);
949 ConcatPaths(Result, tmp);
950 end;
951 end;
952 //------------------------------------------------------------------------------
953
954 function SplineVertTransform(img: TImage32; const topSpline: TPathD;
955 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean;
956 begin
957 Result := SplineVertTransform(img, img, topSpline, splineType, backColor, offset);
958 end;
959 //------------------------------------------------------------------------------
960
961 function SplineVertTransform(img, targetImg: TImage32; const topSpline: TPathD;
962 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean;
963 var
964 i,j, w,h, len: integer;
965 x,y, yy, q: double;
966 yLimLo, yLimHi: double;
967 distances: TArrayOfDouble;
968 pc: PColor32;
969 rec: TRect;
970 tmp: TArrayOfColor32;
971 topPath: TPathD;
972 prevX: double;
973 resampler: TResamplerFunction;
974 backColoring, allowBackColoring: Boolean;
975 begin
976 offset := NullPoint;
977 if targetImg.Resampler = 0 then
978 resampler := nil else
979 resampler := GetResampler(targetImg.Resampler);
980
981 //convert the top spline control points into a flattened path
982 if splineType = stQuadratic then
983 topPath := FlattenQSpline(topSpline) else
984 topPath := FlattenCSpline(topSpline);
985
986 rec := GetBounds(topPath);
987 //return false if the spline is invalid or there's no vertical transformation
988 Result := Assigned(resampler) and not IsEmptyRect(rec);
989 if not Result then
990 begin
991 if targetImg <> img then targetImg.Assign(img);
992 Exit;
993 end;
994
995 offset := rec.TopLeft;
996 topPath := InterpolatePathForX(topPath);
997 len := Length(topPath);
998 inc(rec.Bottom, img.Height);
999 RectWidthHeight(rec, w, h);
1000 NewColor32Array(tmp, (w+1) * h, False);
1001
1002 prevX := topPath[0].X;
1003 allowBackColoring := GetAlpha(backColor) > 2;
1004 backColor := backColor and $00FFFFFF;
1005
1006 distances := GetCumulativeDistances(topPath);
1007 q := img.Width / distances[High(distances)];
1008
1009 yLimLo := -0.5;
1010 yLimHi := img.Height + 0.5;
1011
1012 for i := 0 to len -1 do
1013 begin
1014 pc := @tmp[Round(topPath[i].X)-rec.Left];
1015 backColoring := allowBackColoring and (prevX >= topPath[i].X);
1016 prevX := topPath[i].X;
1017 yy := topPath[i].Y;
1018 for j := rec.top to rec.bottom -1 do
1019 begin
1020 x := Distances[i]*q;
1021 y := j - yy;
1022 if (y < yLimLo) or (y > yLimHi) then
1023 // do nothing !
1024 else if backColoring then
1025 pc^ := BlendToAlpha(pc^, ReColor(resampler(img, x -0.5, y -0.5), backColor))
1026 else
1027 pc^ := BlendToAlpha(pc^, resampler(img, x -0.5, y -0.5));
1028 inc(pc, w);
1029 end;
1030 end;
1031
1032 // tmp was creates with "(w+1)*h". We take advantage of the
1033 // memory manager's inplace shrink.
1034 SetLength(tmp, w * h);
1035 targetImg.AssignPixelArray(tmp, w, h);
1036 end;
1037 //------------------------------------------------------------------------------
1038
1039 function SplineHorzTransform(img: TImage32; const leftSpline: TPathD;
1040 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean;
1041 begin
1042 Result := SplineHorzTransform(img, img, leftSpline, splineType, backColor, offset);
1043 end;
1044 //------------------------------------------------------------------------------
1045
1046 function SplineHorzTransform(img, targetImg: TImage32; const leftSpline: TPathD;
1047 splineType: TSplineType; backColor: TColor32; out offset: TPoint): Boolean;
1048 var
1049 i,j, len, w,h: integer;
1050 x,y, xx, q, prevY: double;
1051 xLimLo, xLimHi: double;
1052 leftPath: TPathD;
1053 distances: TArrayOfDouble;
1054 rec: TRect;
1055 pc: PColor32;
1056 tmp: TArrayOfColor32;
1057 backColoring, allowBackColoring: Boolean;
1058 resampler: TResamplerFunction;
1059 begin
1060 offset := NullPoint;
1061
1062 if targetImg.Resampler = 0 then
1063 resampler := nil else
1064 resampler := GetResampler(targetImg.Resampler);
1065
1066 //convert the left spline control points into a flattened path
1067 if splineType = stQuadratic then
1068 leftPath := FlattenQSpline(leftSpline) else
1069 leftPath := FlattenCSpline(leftSpline);
1070 rec := GetBounds(leftPath);
1071
1072 //return false if the spline is invalid or there's no horizontal transformation
1073 Result := Assigned(resampler) and not IsEmptyRect(rec);
1074 if not Result then
1075 begin
1076 if targetImg <> img then targetImg.Assign(img);
1077 Exit;
1078 end;
1079
1080 offset := rec.TopLeft;
1081 leftPath := InterpolatePathForY(leftPath);
1082 len := Length(leftPath);
1083 inc(rec.Right, img.Width);
1084 RectWidthHeight(rec, w, h);
1085 NewColor32Array(tmp, w * (h+1), False);
1086
1087 prevY := leftPath[0].Y;
1088 allowBackColoring := GetAlpha(backColor) > 2;
1089 backColor := backColor and $00FFFFFF;
1090
1091 distances := GetCumulativeDistances(leftPath);
1092 q := img.Height / distances[High(distances)];;
1093 xLimLo := -0.5;
1094 xLimHi := img.Width + 0.5;
1095
1096 for i := 0 to len -1 do
1097 begin
1098 pc := @tmp[Round(leftPath[i].Y - rec.Top) * w];
1099 backColoring := allowBackColoring and (prevY >= leftPath[i].Y);
1100 prevY := leftPath[i].Y;
1101 xx := leftPath[i].X;
1102 y := Distances[i]*q;
1103 for j := rec.left to rec.right -1 do
1104 begin
1105 x := j - xx;
1106
1107 if (x < xLimLo) or (x > xLimHi) then
1108 // do nothing !
1109 else if backColoring then
1110 pc^ := BlendToAlpha(pc^, ReColor(resampler(img, x -0.5, y -0.5), backColor))
1111 else
1112 pc^ := BlendToAlpha(pc^, resampler(img, x -0.5, y -0.5));
1113
1114 inc(pc);
1115 end;
1116 end;
1117
1118 // tmp was creates with "w*(h+1)". We take advantage of the
1119 // memory manager's inplace shrink.
1120 SetLength(tmp, w * h);
1121 targetImg.AssignPixelArray(tmp, w, h);
1122 end;
1123
1124 //------------------------------------------------------------------------------
1125 // Miscellaneous WeightedColor function
1126 //------------------------------------------------------------------------------
1127
1128 function LimitByte(val: Cardinal): byte; {$IFDEF INLINE} inline; {$ENDIF}
1129 begin
1130 if val > 255 then result := 255
1131 else result := val;
1132 end;
1133
1134 //------------------------------------------------------------------------------
1135 // TWeightedColor
1136 //------------------------------------------------------------------------------
1137
1138 procedure TWeightedColor.Reset;
1139 {$IFDEF CPUX64}
1140 var
1141 Zero: Int64;
1142 {$ENDIF CPUX64}
1143 begin
1144 {$IFDEF CPUX64}
1145 Zero := 0;
1146 fAddCount := Zero;
1147 fAlphaTot := Zero;
1148 fColorTotR := Zero;
1149 fColorTotG := Zero;
1150 fColorTotB := Zero;
1151 {$ELSE}
1152 fAddCount := 0;
1153 fAlphaTot := 0;
1154 fColorTotR := 0;
1155 fColorTotG := 0;
1156 fColorTotB := 0;
1157 {$ENDIF CPUX64}
1158 end;
1159 //------------------------------------------------------------------------------
1160
1161 procedure TWeightedColor.Reset(c: TColor32; w: Integer);
1162 var
1163 a: Cardinal;
1164 begin
1165 fAddCount := w;
1166 a := w * Byte(c shr 24);
1167 if a = 0 then
1168 begin
1169 fAlphaTot := 0;
1170 fColorTotB := 0;
1171 fColorTotG := 0;
1172 fColorTotR := 0;
1173 end else
1174 begin
1175 fAlphaTot := a;
1176 fColorTotB := (a * Byte(c));
1177 fColorTotG := (a * Byte(c shr 8));
1178 fColorTotR := (a * Byte(c shr 16));
1179 end;
1180 end;
1181 //------------------------------------------------------------------------------
1182
1183 procedure TWeightedColor.AddWeight(w: Integer);
1184 begin
1185 inc(fAddCount, w);
1186 end;
1187 //------------------------------------------------------------------------------
1188
1189 procedure TWeightedColor.Add(c: TColor32; w: Integer);
1190 var
1191 a: Int64;
1192 begin
1193 inc(fAddCount, w);
1194 a := Byte(c shr 24);
1195 if a <> 0 then
1196 begin
1197 a := a * Cardinal(w);
1198 inc(fAlphaTot, a);
1199 inc(fColorTotB, (a * Byte(c)));
1200 inc(fColorTotG, (a * Byte(c shr 8)));
1201 inc(fColorTotR, (a * Byte(c shr 16)));
1202 end;
1203 end;
1204 //------------------------------------------------------------------------------
1205
1206 procedure TWeightedColor.Add(c: TColor32);
1207 // Optimized for w=1
1208 var
1209 a: Int64;
1210 begin
1211 inc(fAddCount);
1212 a := Byte(c shr 24);
1213 if a = 0 then Exit;
1214 inc(fAlphaTot, a);
1215 inc(fColorTotB, (a * Byte(c)));
1216 inc(fColorTotG, (a * Byte(c shr 8)));
1217 inc(fColorTotR, (a * Byte(c shr 16)));
1218 end;
1219 //------------------------------------------------------------------------------
1220
1221 procedure TWeightedColor.Add(const other: TWeightedColor);
1222 begin
1223 inc(fAddCount, other.fAddCount);
1224 inc(fAlphaTot, other.fAlphaTot);
1225 inc(fColorTotR, other.fColorTotR);
1226 inc(fColorTotG, other.fColorTotG);
1227 inc(fColorTotB, other.fColorTotB);
1228 end;
1229 //------------------------------------------------------------------------------
1230
1231 procedure TWeightedColor.Subtract(c: TColor32; w: Integer);
1232 var
1233 a: Int64;
1234 begin
1235 dec(fAddCount, w);
1236 a := w * Byte(c shr 24);
1237 if a = 0 then Exit;
1238 dec(fAlphaTot, a);
1239 dec(fColorTotB, (a * Byte(c)));
1240 dec(fColorTotG, (a * Byte(c shr 8)));
1241 dec(fColorTotR, (a * Byte(c shr 16)));
1242 end;
1243 //------------------------------------------------------------------------------
1244
1245 procedure TWeightedColor.Subtract(c: TColor32);
1246 // Optimized for w=1
1247 var
1248 a: Int64;
1249 begin
1250 dec(fAddCount);
1251 a := Byte(c shr 24);
1252 if a = 0 then Exit;
1253 dec(fAlphaTot, a);
1254 dec(fColorTotB, (a * Byte(c)));
1255 dec(fColorTotG, (a * Byte(c shr 8)));
1256 dec(fColorTotR, (a * Byte(c shr 16)));
1257 end;
1258 //------------------------------------------------------------------------------
1259
1260 procedure TWeightedColor.Subtract(const other: TWeightedColor);
1261 begin
1262 dec(fAddCount, other.fAddCount);
1263 dec(fAlphaTot, other.fAlphaTot);
1264 dec(fColorTotR, other.fColorTotR);
1265 dec(fColorTotG, other.fColorTotG);
1266 dec(fColorTotB, other.fColorTotB);
1267 end;
1268 //------------------------------------------------------------------------------
1269
1270 function TWeightedColor.AddSubtract(addC, subC: TColor32): Boolean;
1271 var
1272 a: Int64;
1273 begin
1274 // add+subtract => fAddCount stays the same
1275
1276 // skip identical colors
1277 Result := False;
1278 if addC = subC then Exit;
1279
1280 a := Byte(addC shr 24);
1281 if a > 0 then
1282 begin
1283 inc(fAlphaTot, a);
1284 inc(fColorTotB, (a * Byte(addC)));
1285 inc(fColorTotG, (a * Byte(addC shr 8)));
1286 inc(fColorTotR, (a * Byte(addC shr 16)));
1287 Result := True;
1288 end;
1289
1290 a := Byte(subC shr 24);
1291 if a > 0 then
1292 begin
1293 dec(fAlphaTot, a);
1294 dec(fColorTotB, (a * Byte(subC)));
1295 dec(fColorTotG, (a * Byte(subC shr 8)));
1296 dec(fColorTotR, (a * Byte(subC shr 16)));
1297 Result := True;
1298 end;
1299 end;
1300 //------------------------------------------------------------------------------
1301
1302 function TWeightedColor.AddNoneSubtract(c: TColor32): Boolean;
1303 var
1304 a: Int64;
1305 begin
1306 // add+subtract => fAddCount stays the same
1307
1308 a := Byte(c shr 24);
1309 if a > 0 then
1310 begin
1311 dec(fAlphaTot, a);
1312 dec(fColorTotB, (a * Byte(c)));
1313 dec(fColorTotG, (a * Byte(c shr 8)));
1314 dec(fColorTotR, (a * Byte(c shr 16)));
1315 Result := True;
1316 end
1317 else
1318 Result := False;
1319 end;
1320 //------------------------------------------------------------------------------
1321
1322 function TWeightedColor.GetColor: TColor32;
1323 var
1324 oneDivAlphaTot: double;
1325 alpha: Integer;
1326 begin
1327 result := clNone32;
1328 if (fAlphaTot <= 0) or (fAddCount <= 0) then
1329 Exit;
1330 {$IFDEF CPUX86}
1331 if fAlphaTot and $FFFFFFFF80000000 = 0 then // small, so can avoid _lldiv call
1332 alpha := (Cardinal(fAlphaTot) + (Cardinal(fAddCount) shr 1)) div
1333 Cardinal(fAddCount)
1334 else
1335 {$ENDIF CPUX86}
1336 alpha := (fAlphaTot + (Cardinal(fAddCount) shr 1)) div Cardinal(fAddCount);
1337
1338 result := TColor32(Min(255, alpha)) shl 24;
1339 // alpha weighting has been applied to color channels, so div by fAlphaTot
1340
1341 if fAlphaTot < DivOneByXTableSize then // use precalculated 1/X values
1342 oneDivAlphaTot := DivOneByXTable[fAlphaTot] else
1343 oneDivAlphaTot := 1/(fAlphaTot);
1344
1345 // 1. Skip zero calculations.
1346 // 2. LimitByte(Integer): Values can't be less than 0, so don't use ClampByte.
1347 // 3. x86: Round expects the value in the st(0)/xmm1 FPU register.
1348 // Thus we need to do the calculation and Round call in one expression.
1349 // Otherwise the compiler will use a temporary double variable on
1350 // the stack that will cause unnecessary store and load operations.
1351 if fColorTotB > 0 then
1352 result := result or LimitByte(System.Round(fColorTotB * oneDivAlphaTot));
1353 if fColorTotG > 0 then
1354 result := result or LimitByte(System.Round(fColorTotG * oneDivAlphaTot)) shl 8;
1355 if fColorTotR > 0 then
1356 result := result or LimitByte(System.Round(fColorTotR * oneDivAlphaTot)) shl 16;
1357 end;
1358
1359 //------------------------------------------------------------------------------
1360 // Initialization
1361 //------------------------------------------------------------------------------
1362
1363 procedure MakeDivOneByXTable;
1364 var
1365 i: Integer;
1366 begin
1367 DivOneByXTable[0] := 0; // NaN
1368 for i := 1 to High(DivOneByXTable) do
1369 DivOneByXTable[i] := 1/i;
1370 end;
1371
1372 initialization
1373 MakeDivOneByXTable;
1374
1375 end.