Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
cpdf_rendershading.cpp
Go to the documentation of this file.
1// Copyright 2019 The PDFium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6
7#include "core/fpdfapi/render/cpdf_rendershading.h"
8
9#include <math.h>
10
11#include <algorithm>
12#include <array>
13#include <memory>
14#include <utility>
15#include <vector>
16
17#include "core/fpdfapi/page/cpdf_colorspace.h"
18#include "core/fpdfapi/page/cpdf_dib.h"
19#include "core/fpdfapi/page/cpdf_function.h"
20#include "core/fpdfapi/page/cpdf_meshstream.h"
21#include "core/fpdfapi/parser/cpdf_array.h"
22#include "core/fpdfapi/parser/cpdf_dictionary.h"
23#include "core/fpdfapi/parser/cpdf_stream.h"
24#include "core/fpdfapi/parser/fpdf_parser_utility.h"
25#include "core/fpdfapi/render/cpdf_devicebuffer.h"
26#include "core/fpdfapi/render/cpdf_renderoptions.h"
27#include "core/fxcrt/fx_safe_types.h"
28#include "core/fxcrt/fx_system.h"
29#include "core/fxcrt/span_util.h"
30#include "core/fxcrt/unowned_ptr.h"
31#include "core/fxge/cfx_defaultrenderdevice.h"
32#include "core/fxge/cfx_fillrenderoptions.h"
33#include "core/fxge/cfx_path.h"
34#include "core/fxge/dib/cfx_dibitmap.h"
35#include "core/fxge/dib/fx_dib.h"
36#include "third_party/base/check.h"
37#include "third_party/base/check_op.h"
38#include "third_party/base/containers/span.h"
39
40namespace {
41
42constexpr int kShadingSteps = 256;
43
44uint32_t CountOutputsFromFunctions(
45 const std::vector<std::unique_ptr<CPDF_Function>>& funcs) {
46 FX_SAFE_UINT32 total = 0;
47 for (const auto& func : funcs) {
48 if (func)
49 total += func->CountOutputs();
50 }
51 return total.ValueOrDefault(0);
52}
53
54uint32_t GetValidatedOutputsCount(
55 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
56 const RetainPtr<CPDF_ColorSpace>& pCS) {
57 uint32_t funcs_outputs = CountOutputsFromFunctions(funcs);
58 return funcs_outputs ? std::max(funcs_outputs, pCS->CountComponents()) : 0;
59}
60
61std::array<FX_ARGB, kShadingSteps> GetShadingSteps(
62 float t_min,
63 float t_max,
64 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
65 const RetainPtr<CPDF_ColorSpace>& pCS,
66 int alpha,
67 size_t results_count) {
68 DCHECK(results_count >= CountOutputsFromFunctions(funcs));
69 DCHECK(results_count >= pCS->CountComponents());
70 std::array<FX_ARGB, kShadingSteps> shading_steps;
71 std::vector<float> result_array(results_count);
72 float diff = t_max - t_min;
73 for (int i = 0; i < kShadingSteps; ++i) {
74 float input = diff * i / kShadingSteps + t_min;
75 pdfium::span<float> result_span = pdfium::make_span(result_array);
76 for (const auto& func : funcs) {
77 if (!func)
78 continue;
79 absl::optional<uint32_t> nresults =
80 func->Call(pdfium::span_from_ref(input), result_span);
81 if (nresults.has_value())
82 result_span = result_span.subspan(nresults.value());
83 }
84 float R = 0.0f;
85 float G = 0.0f;
86 float B = 0.0f;
87 pCS->GetRGB(result_array, &R, &G, &B);
88 shading_steps[i] = ArgbEncode(alpha, FXSYS_roundf(R * 255),
89 FXSYS_roundf(G * 255), FXSYS_roundf(B * 255));
90 }
91 return shading_steps;
92}
93
94void DrawAxialShading(const RetainPtr<CFX_DIBitmap>& pBitmap,
95 const CFX_Matrix& mtObject2Bitmap,
96 const CPDF_Dictionary* pDict,
97 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
98 const RetainPtr<CPDF_ColorSpace>& pCS,
99 int alpha) {
100 DCHECK_EQ(pBitmap->GetFormat(), FXDIB_Format::kArgb);
101
102 const uint32_t total_results = GetValidatedOutputsCount(funcs, pCS);
103 if (total_results == 0)
104 return;
105
106 RetainPtr<const CPDF_Array> pCoords = pDict->GetArrayFor("Coords");
107 if (!pCoords)
108 return;
109
110 float start_x = pCoords->GetFloatAt(0);
111 float start_y = pCoords->GetFloatAt(1);
112 float end_x = pCoords->GetFloatAt(2);
113 float end_y = pCoords->GetFloatAt(3);
114 float t_min = 0;
115 float t_max = 1.0f;
116 RetainPtr<const CPDF_Array> pArray = pDict->GetArrayFor("Domain");
117 if (pArray) {
118 t_min = pArray->GetFloatAt(0);
119 t_max = pArray->GetFloatAt(1);
120 }
121 pArray = pDict->GetArrayFor("Extend");
122 const bool bStartExtend = pArray && pArray->GetBooleanAt(0, false);
123 const bool bEndExtend = pArray && pArray->GetBooleanAt(1, false);
124
125 int width = pBitmap->GetWidth();
126 int height = pBitmap->GetHeight();
127 float x_span = end_x - start_x;
128 float y_span = end_y - start_y;
129 float axis_len_square = (x_span * x_span) + (y_span * y_span);
130
131 std::array<FX_ARGB, kShadingSteps> shading_steps =
132 GetShadingSteps(t_min, t_max, funcs, pCS, alpha, total_results);
133
134 CFX_Matrix matrix = mtObject2Bitmap.GetInverse();
135 for (int row = 0; row < height; row++) {
136 uint32_t* dib_buf =
137 fxcrt::reinterpret_span<uint32_t>(pBitmap->GetWritableScanline(row))
138 .data();
139 for (int column = 0; column < width; column++) {
140 CFX_PointF pos = matrix.Transform(
141 CFX_PointF(static_cast<float>(column), static_cast<float>(row)));
142 float scale =
143 (((pos.x - start_x) * x_span) + ((pos.y - start_y) * y_span)) /
144 axis_len_square;
145 int index = static_cast<int32_t>(scale * (kShadingSteps - 1));
146 if (index < 0) {
147 if (!bStartExtend)
148 continue;
149
150 index = 0;
151 } else if (index >= kShadingSteps) {
152 if (!bEndExtend)
153 continue;
154
155 index = kShadingSteps - 1;
156 }
157 dib_buf[column] = shading_steps[index];
158 }
159 }
160}
161
162void DrawRadialShading(const RetainPtr<CFX_DIBitmap>& pBitmap,
163 const CFX_Matrix& mtObject2Bitmap,
164 const CPDF_Dictionary* pDict,
165 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
166 const RetainPtr<CPDF_ColorSpace>& pCS,
167 int alpha) {
168 DCHECK_EQ(pBitmap->GetFormat(), FXDIB_Format::kArgb);
169
170 const uint32_t total_results = GetValidatedOutputsCount(funcs, pCS);
171 if (total_results == 0)
172 return;
173
174 RetainPtr<const CPDF_Array> pCoords = pDict->GetArrayFor("Coords");
175 if (!pCoords)
176 return;
177
178 float start_x = pCoords->GetFloatAt(0);
179 float start_y = pCoords->GetFloatAt(1);
180 float start_r = pCoords->GetFloatAt(2);
181 float end_x = pCoords->GetFloatAt(3);
182 float end_y = pCoords->GetFloatAt(4);
183 float end_r = pCoords->GetFloatAt(5);
184 float t_min = 0;
185 float t_max = 1.0f;
186 RetainPtr<const CPDF_Array> pArray = pDict->GetArrayFor("Domain");
187 if (pArray) {
188 t_min = pArray->GetFloatAt(0);
189 t_max = pArray->GetFloatAt(1);
190 }
191 pArray = pDict->GetArrayFor("Extend");
192 const bool bStartExtend = pArray && pArray->GetBooleanAt(0, false);
193 const bool bEndExtend = pArray && pArray->GetBooleanAt(1, false);
194
195 std::array<FX_ARGB, kShadingSteps> shading_steps =
196 GetShadingSteps(t_min, t_max, funcs, pCS, alpha, total_results);
197
198 const float dx = end_x - start_x;
199 const float dy = end_y - start_y;
200 const float dr = end_r - start_r;
201 const float a = dx * dx + dy * dy - dr * dr;
202 const bool a_is_float_zero = FXSYS_IsFloatZero(a);
203
204 int width = pBitmap->GetWidth();
205 int height = pBitmap->GetHeight();
206 bool bDecreasing = dr < 0 && static_cast<int>(FXSYS_sqrt2(dx, dy)) < -dr;
207
208 CFX_Matrix matrix = mtObject2Bitmap.GetInverse();
209 for (int row = 0; row < height; row++) {
210 uint32_t* dib_buf =
211 fxcrt::reinterpret_span<uint32_t>(pBitmap->GetWritableScanline(row))
212 .data();
213 for (int column = 0; column < width; column++) {
214 CFX_PointF pos = matrix.Transform(
215 CFX_PointF(static_cast<float>(column), static_cast<float>(row)));
216 float pos_dx = pos.x - start_x;
217 float pos_dy = pos.y - start_y;
218 float b = -2 * (pos_dx * dx + pos_dy * dy + start_r * dr);
219 float c = pos_dx * pos_dx + pos_dy * pos_dy - start_r * start_r;
220 float s;
221 if (FXSYS_IsFloatZero(b)) {
222 s = sqrt(-c / a);
223 } else if (a_is_float_zero) {
224 s = -c / b;
225 } else {
226 float b2_4ac = (b * b) - 4 * (a * c);
227 if (b2_4ac < 0)
228 continue;
229
230 float root = sqrt(b2_4ac);
231 float s1 = (-b - root) / (2 * a);
232 float s2 = (-b + root) / (2 * a);
233 if (a <= 0)
234 std::swap(s1, s2);
235 if (bDecreasing)
236 s = (s1 >= 0 || bStartExtend) ? s1 : s2;
237 else
238 s = (s2 <= 1.0f || bEndExtend) ? s2 : s1;
239
240 if (start_r + s * dr < 0)
241 continue;
242 }
243
244 int index = static_cast<int32_t>(s * (kShadingSteps - 1));
245 if (index < 0) {
246 if (!bStartExtend)
247 continue;
248 index = 0;
249 } else if (index >= kShadingSteps) {
250 if (!bEndExtend)
251 continue;
252 index = kShadingSteps - 1;
253 }
254 dib_buf[column] = shading_steps[index];
255 }
256 }
257}
258
259void DrawFuncShading(const RetainPtr<CFX_DIBitmap>& pBitmap,
260 const CFX_Matrix& mtObject2Bitmap,
261 const CPDF_Dictionary* pDict,
262 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
263 const RetainPtr<CPDF_ColorSpace>& pCS,
264 int alpha) {
265 DCHECK_EQ(pBitmap->GetFormat(), FXDIB_Format::kArgb);
266
267 const uint32_t total_results = GetValidatedOutputsCount(funcs, pCS);
268 if (total_results == 0)
269 return;
270
271 RetainPtr<const CPDF_Array> pDomain = pDict->GetArrayFor("Domain");
272 float xmin = 0.0f;
273 float ymin = 0.0f;
274 float xmax = 1.0f;
275 float ymax = 1.0f;
276 if (pDomain) {
277 xmin = pDomain->GetFloatAt(0);
278 xmax = pDomain->GetFloatAt(1);
279 ymin = pDomain->GetFloatAt(2);
280 ymax = pDomain->GetFloatAt(3);
281 }
282 CFX_Matrix mtDomain2Target = pDict->GetMatrixFor("Matrix");
283 CFX_Matrix matrix =
284 mtObject2Bitmap.GetInverse() * mtDomain2Target.GetInverse();
285 int width = pBitmap->GetWidth();
286 int height = pBitmap->GetHeight();
287
288 DCHECK(total_results >= CountOutputsFromFunctions(funcs));
289 DCHECK(total_results >= pCS->CountComponents());
290 std::vector<float> result_array(total_results);
291 for (int row = 0; row < height; ++row) {
292 uint32_t* dib_buf =
293 fxcrt::reinterpret_span<uint32_t>(pBitmap->GetWritableScanline(row))
294 .data();
295 for (int column = 0; column < width; column++) {
296 CFX_PointF pos = matrix.Transform(
297 CFX_PointF(static_cast<float>(column), static_cast<float>(row)));
298 if (pos.x < xmin || pos.x > xmax || pos.y < ymin || pos.y > ymax)
299 continue;
300
301 float input[2] = {pos.x, pos.y};
302 pdfium::span<float> result_span = pdfium::make_span(result_array);
303 for (const auto& func : funcs) {
304 if (!func)
305 continue;
306 absl::optional<uint32_t> nresults = func->Call(input, result_span);
307 if (nresults.has_value())
308 result_span = result_span.subspan(nresults.value());
309 }
310 float R = 0.0f;
311 float G = 0.0f;
312 float B = 0.0f;
313 pCS->GetRGB(result_array, &R, &G, &B);
314 dib_buf[column] = ArgbEncode(alpha, static_cast<int32_t>(R * 255),
315 static_cast<int32_t>(G * 255),
316 static_cast<int32_t>(B * 255));
317 }
318 }
319}
320
321bool GetScanlineIntersect(int y,
322 const CFX_PointF& first,
323 const CFX_PointF& second,
324 float* x) {
325 if (first.y == second.y)
326 return false;
327
328 if (first.y < second.y) {
329 if (y < first.y || y > second.y)
330 return false;
331 } else if (y < second.y || y > first.y) {
332 return false;
333 }
334 *x = first.x + ((second.x - first.x) * (y - first.y) / (second.y - first.y));
335 return true;
336}
337
338void DrawGouraud(const RetainPtr<CFX_DIBitmap>& pBitmap,
339 int alpha,
340 CPDF_MeshVertex triangle[3]) {
341 float min_y = triangle[0].position.y;
342 float max_y = triangle[0].position.y;
343 for (int i = 1; i < 3; i++) {
344 min_y = std::min(min_y, triangle[i].position.y);
345 max_y = std::max(max_y, triangle[i].position.y);
346 }
347 if (min_y == max_y)
348 return;
349
350 int min_yi = std::max(static_cast<int>(floorf(min_y)), 0);
351 int max_yi = static_cast<int>(ceilf(max_y));
352 if (max_yi >= pBitmap->GetHeight())
353 max_yi = pBitmap->GetHeight() - 1;
354
355 for (int y = min_yi; y <= max_yi; y++) {
356 int nIntersects = 0;
357 float inter_x[3];
358 float r[3];
359 float g[3];
360 float b[3];
361 for (int i = 0; i < 3; i++) {
362 CPDF_MeshVertex& vertex1 = triangle[i];
363 CPDF_MeshVertex& vertex2 = triangle[(i + 1) % 3];
364 CFX_PointF& position1 = vertex1.position;
365 CFX_PointF& position2 = vertex2.position;
366 bool bIntersect =
367 GetScanlineIntersect(y, position1, position2, &inter_x[nIntersects]);
368 if (!bIntersect)
369 continue;
370
371 float y_dist = (y - position1.y) / (position2.y - position1.y);
372 r[nIntersects] = vertex1.r + ((vertex2.r - vertex1.r) * y_dist);
373 g[nIntersects] = vertex1.g + ((vertex2.g - vertex1.g) * y_dist);
374 b[nIntersects] = vertex1.b + ((vertex2.b - vertex1.b) * y_dist);
375 nIntersects++;
376 }
377 if (nIntersects != 2)
378 continue;
379
380 int min_x;
381 int max_x;
382 int start_index;
383 int end_index;
384 if (inter_x[0] < inter_x[1]) {
385 min_x = static_cast<int>(floorf(inter_x[0]));
386 max_x = static_cast<int>(ceilf(inter_x[1]));
387 start_index = 0;
388 end_index = 1;
389 } else {
390 min_x = static_cast<int>(floorf(inter_x[1]));
391 max_x = static_cast<int>(ceilf(inter_x[0]));
392 start_index = 1;
393 end_index = 0;
394 }
395
396 int start_x = std::clamp(min_x, 0, pBitmap->GetWidth());
397 int end_x = std::clamp(max_x, 0, pBitmap->GetWidth());
398 float r_unit = (r[end_index] - r[start_index]) / (max_x - min_x);
399 float g_unit = (g[end_index] - g[start_index]) / (max_x - min_x);
400 float b_unit = (b[end_index] - b[start_index]) / (max_x - min_x);
401 float r_result = r[start_index] + (start_x - min_x) * r_unit;
402 float g_result = g[start_index] + (start_x - min_x) * g_unit;
403 float b_result = b[start_index] + (start_x - min_x) * b_unit;
404 pdfium::span<uint8_t> dib_span =
405 pBitmap->GetWritableScanline(y).subspan(start_x * 4);
406
407 for (int x = start_x; x < end_x; x++) {
408 uint8_t* dib_buf = dib_span.data();
409 r_result += r_unit;
410 g_result += g_unit;
411 b_result += b_unit;
412 FXARGB_SETDIB(dib_buf, ArgbEncode(alpha, static_cast<int>(r_result * 255),
413 static_cast<int>(g_result * 255),
414 static_cast<int>(b_result * 255)));
415 dib_span = dib_span.subspan(4);
416 }
417 }
418}
419
420void DrawFreeGouraudShading(
421 const RetainPtr<CFX_DIBitmap>& pBitmap,
422 const CFX_Matrix& mtObject2Bitmap,
423 RetainPtr<const CPDF_Stream> pShadingStream,
424 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
426 int alpha) {
427 DCHECK_EQ(pBitmap->GetFormat(), FXDIB_Format::kArgb);
428
430 std::move(pShadingStream), std::move(pCS));
431 if (!stream.Load())
432 return;
433
434 CPDF_MeshVertex triangle[3];
435 while (!stream.IsEOF()) {
436 CPDF_MeshVertex vertex;
437 uint32_t flag;
438 if (!stream.ReadVertex(mtObject2Bitmap, &vertex, &flag))
439 return;
440
441 if (flag == 0) {
442 triangle[0] = vertex;
443 for (int i = 1; i < 3; ++i) {
444 uint32_t dummy_flag;
445 if (!stream.ReadVertex(mtObject2Bitmap, &triangle[i], &dummy_flag))
446 return;
447 }
448 } else {
449 if (flag == 1)
450 triangle[0] = triangle[1];
451
452 triangle[1] = triangle[2];
453 triangle[2] = vertex;
454 }
455 DrawGouraud(pBitmap, alpha, triangle);
456 }
457}
458
459void DrawLatticeGouraudShading(
460 const RetainPtr<CFX_DIBitmap>& pBitmap,
461 const CFX_Matrix& mtObject2Bitmap,
462 RetainPtr<const CPDF_Stream> pShadingStream,
463 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
465 int alpha) {
466 DCHECK_EQ(pBitmap->GetFormat(), FXDIB_Format::kArgb);
467
468 int row_verts = pShadingStream->GetDict()->GetIntegerFor("VerticesPerRow");
469 if (row_verts < 2)
470 return;
471
473 std::move(pShadingStream), std::move(pCS));
474 if (!stream.Load())
475 return;
476
477 std::vector<CPDF_MeshVertex> vertices[2];
478 vertices[0] = stream.ReadVertexRow(mtObject2Bitmap, row_verts);
479 if (vertices[0].empty())
480 return;
481
482 int last_index = 0;
483 while (true) {
484 vertices[1 - last_index] = stream.ReadVertexRow(mtObject2Bitmap, row_verts);
485 if (vertices[1 - last_index].empty())
486 return;
487
488 CPDF_MeshVertex triangle[3];
489 for (int i = 1; i < row_verts; ++i) {
490 triangle[0] = vertices[last_index][i];
491 triangle[1] = vertices[1 - last_index][i - 1];
492 triangle[2] = vertices[last_index][i - 1];
493 DrawGouraud(pBitmap, alpha, triangle);
494 triangle[2] = vertices[1 - last_index][i];
495 DrawGouraud(pBitmap, alpha, triangle);
496 }
497 last_index = 1 - last_index;
498 }
499}
500
501struct CoonBezierCoeff {
502 void InitFromPoints(float p0, float p1, float p2, float p3) {
503 a = -p0 + 3 * p1 - 3 * p2 + p3;
504 b = 3 * p0 - 6 * p1 + 3 * p2;
505 c = -3 * p0 + 3 * p1;
506 d = p0;
507 }
508
509 void InitFromBezierInterpolation(const CoonBezierCoeff& C1,
510 const CoonBezierCoeff& C2,
511 const CoonBezierCoeff& D1,
512 const CoonBezierCoeff& D2) {
513 a = (D1.a + D2.a) / 2;
514 b = (D1.b + D2.b) / 2;
515 c = (D1.c + D2.c) / 2 - (C1.a / 8 + C1.b / 4 + C1.c / 2) +
516 (C2.a / 8 + C2.b / 4) + (-C1.d + D2.d) / 2 - (C2.a + C2.b) / 2;
517 d = C1.a / 8 + C1.b / 4 + C1.c / 2 + C1.d;
518 }
519
520 CoonBezierCoeff first_half() const {
521 CoonBezierCoeff result;
522 result.a = a / 8;
523 result.b = b / 4;
524 result.c = c / 2;
525 result.d = d;
526 return result;
527 }
528
529 CoonBezierCoeff second_half() const {
530 CoonBezierCoeff result;
531 result.a = a / 8;
532 result.b = 3 * a / 8 + b / 4;
533 result.c = 3 * a / 8 + b / 2 + c / 2;
534 result.d = a / 8 + b / 4 + c / 2 + d;
535 return result;
536 }
537
538 void GetPoints(float p[4]) const {
539 p[0] = d;
540 p[1] = c / 3 + p[0];
541 p[2] = b / 3 - p[0] + 2 * p[1];
542 p[3] = a + p[0] - 3 * p[1] + 3 * p[2];
543 }
544
545 float Distance() const {
546 float dis = a + b + c;
547 return dis < 0 ? -dis : dis;
548 }
549
550 float a;
551 float b;
552 float c;
553 float d;
554};
555
556struct CoonBezier {
557 void InitFromPoints(float x0,
558 float y0,
559 float x1,
560 float y1,
561 float x2,
562 float y2,
563 float x3,
564 float y3) {
565 x.InitFromPoints(x0, x1, x2, x3);
566 y.InitFromPoints(y0, y1, y2, y3);
567 }
568
569 void InitFromBezierInterpolation(const CoonBezier& C1,
570 const CoonBezier& C2,
571 const CoonBezier& D1,
572 const CoonBezier& D2) {
573 x.InitFromBezierInterpolation(C1.x, C2.x, D1.x, D2.x);
574 y.InitFromBezierInterpolation(C1.y, C2.y, D1.y, D2.y);
575 }
576
577 CoonBezier first_half() const {
578 CoonBezier result;
579 result.x = x.first_half();
580 result.y = y.first_half();
581 return result;
582 }
583
584 CoonBezier second_half() const {
585 CoonBezier result;
586 result.x = x.second_half();
587 result.y = y.second_half();
588 return result;
589 }
590
591 void GetPoints(pdfium::span<CFX_Path::Point> path_points) const {
592 constexpr size_t kPointsCount = 4;
593 float points_x[kPointsCount];
594 float points_y[kPointsCount];
595 x.GetPoints(points_x);
596 y.GetPoints(points_y);
597 for (size_t i = 0; i < kPointsCount; ++i)
598 path_points[i].m_Point = {points_x[i], points_y[i]};
599 }
600
601 void GetPointsReverse(pdfium::span<CFX_Path::Point> path_points) const {
602 constexpr size_t kPointsCount = 4;
603 float points_x[kPointsCount];
604 float points_y[kPointsCount];
605 x.GetPoints(points_x);
606 y.GetPoints(points_y);
607 for (size_t i = 0; i < kPointsCount; ++i) {
608 size_t reverse_index = kPointsCount - i - 1;
609 path_points[i].m_Point = {points_x[reverse_index],
610 points_y[reverse_index]};
611 }
612 }
613
614 float Distance() const { return x.Distance() + y.Distance(); }
615
616 CoonBezierCoeff x;
617 CoonBezierCoeff y;
618};
619
620int Interpolate(int p1, int p2, int delta1, int delta2, bool* overflow) {
621 FX_SAFE_INT32 p = p2;
622 p -= p1;
623 p *= delta1;
624 p /= delta2;
625 p += p1;
626 if (!p.IsValid())
627 *overflow = true;
628 return p.ValueOrDefault(0);
629}
630
631int BiInterpolImpl(int c0,
632 int c1,
633 int c2,
634 int c3,
635 int x,
636 int y,
637 int x_scale,
638 int y_scale,
639 bool* overflow) {
640 int x1 = Interpolate(c0, c3, x, x_scale, overflow);
641 int x2 = Interpolate(c1, c2, x, x_scale, overflow);
642 return Interpolate(x1, x2, y, y_scale, overflow);
643}
644
645struct CoonColor {
646 CoonColor() = default;
647
648 // Returns true if successful, false if overflow detected.
649 bool BiInterpol(CoonColor colors[4], int x, int y, int x_scale, int y_scale) {
650 bool overflow = false;
651 for (int i = 0; i < 3; i++) {
652 comp[i] = BiInterpolImpl(colors[0].comp[i], colors[1].comp[i],
653 colors[2].comp[i], colors[3].comp[i], x, y,
654 x_scale, y_scale, &overflow);
655 }
656 return !overflow;
657 }
658
659 int Distance(const CoonColor& o) const {
660 return std::max({abs(comp[0] - o.comp[0]), abs(comp[1] - o.comp[1]),
661 abs(comp[2] - o.comp[2])});
662 }
663
664 int comp[3] = {};
665};
666
667struct PatchDrawer {
668 static constexpr int kCoonColorThreshold = 4;
669
670 void Draw(int x_scale,
671 int y_scale,
672 int left,
673 int bottom,
674 CoonBezier C1,
675 CoonBezier C2,
676 CoonBezier D1,
677 CoonBezier D2) {
678 bool bSmall = C1.Distance() < 2 && C2.Distance() < 2 && D1.Distance() < 2 &&
679 D2.Distance() < 2;
680 CoonColor div_colors[4];
681 int d_bottom = 0;
682 int d_left = 0;
683 int d_top = 0;
684 int d_right = 0;
685 if (!div_colors[0].BiInterpol(patch_colors, left, bottom, x_scale,
686 y_scale)) {
687 return;
688 }
689 if (!bSmall) {
690 if (!div_colors[1].BiInterpol(patch_colors, left, bottom + 1, x_scale,
691 y_scale)) {
692 return;
693 }
694 if (!div_colors[2].BiInterpol(patch_colors, left + 1, bottom + 1, x_scale,
695 y_scale)) {
696 return;
697 }
698 if (!div_colors[3].BiInterpol(patch_colors, left + 1, bottom, x_scale,
699 y_scale)) {
700 return;
701 }
702 d_bottom = div_colors[3].Distance(div_colors[0]);
703 d_left = div_colors[1].Distance(div_colors[0]);
704 d_top = div_colors[1].Distance(div_colors[2]);
705 d_right = div_colors[2].Distance(div_colors[3]);
706 }
707
708 if (bSmall ||
709 (d_bottom < kCoonColorThreshold && d_left < kCoonColorThreshold &&
710 d_top < kCoonColorThreshold && d_right < kCoonColorThreshold)) {
711 pdfium::span<CFX_Path::Point> points = path.GetPoints();
712 C1.GetPoints(points.subspan(0, 4));
713 D2.GetPoints(points.subspan(3, 4));
714 C2.GetPointsReverse(points.subspan(6, 4));
715 D1.GetPointsReverse(points.subspan(9, 4));
716 CFX_FillRenderOptions fill_options(
718 fill_options.full_cover = true;
719 if (bNoPathSmooth) {
720 fill_options.aliased_path = true;
721 }
722 pDevice->DrawPath(
723 path, nullptr, nullptr,
724 ArgbEncode(alpha, div_colors[0].comp[0], div_colors[0].comp[1],
725 div_colors[0].comp[2]),
726 0, fill_options);
727 } else {
728 if (d_bottom < kCoonColorThreshold && d_top < kCoonColorThreshold) {
729 CoonBezier m1;
730 m1.InitFromBezierInterpolation(D1, D2, C1, C2);
731 y_scale *= 2;
732 bottom *= 2;
733 Draw(x_scale, y_scale, left, bottom, C1, m1, D1.first_half(),
734 D2.first_half());
735 Draw(x_scale, y_scale, left, bottom + 1, m1, C2, D1.second_half(),
736 D2.second_half());
737 } else if (d_left < kCoonColorThreshold &&
738 d_right < kCoonColorThreshold) {
739 CoonBezier m2;
740 m2.InitFromBezierInterpolation(C1, C2, D1, D2);
741 x_scale *= 2;
742 left *= 2;
743 Draw(x_scale, y_scale, left, bottom, C1.first_half(), C2.first_half(),
744 D1, m2);
745 Draw(x_scale, y_scale, left + 1, bottom, C1.second_half(),
746 C2.second_half(), m2, D2);
747 } else {
748 CoonBezier m1;
749 CoonBezier m2;
750 m1.InitFromBezierInterpolation(D1, D2, C1, C2);
751 m2.InitFromBezierInterpolation(C1, C2, D1, D2);
752 CoonBezier m1f = m1.first_half();
753 CoonBezier m1s = m1.second_half();
754 CoonBezier m2f = m2.first_half();
755 CoonBezier m2s = m2.second_half();
756 x_scale *= 2;
757 y_scale *= 2;
758 left *= 2;
759 bottom *= 2;
760 Draw(x_scale, y_scale, left, bottom, C1.first_half(), m1f,
761 D1.first_half(), m2f);
762 Draw(x_scale, y_scale, left, bottom + 1, m1f, C2.first_half(),
763 D1.second_half(), m2s);
764 Draw(x_scale, y_scale, left + 1, bottom, C1.second_half(), m1s, m2f,
765 D2.first_half());
766 Draw(x_scale, y_scale, left + 1, bottom + 1, m1s, C2.second_half(), m2s,
767 D2.second_half());
768 }
769 }
770 }
771
772 int max_delta;
773 CFX_Path path;
775 bool bNoPathSmooth;
776 int alpha;
777 CoonColor patch_colors[4];
778};
779
780void DrawCoonPatchMeshes(
781 ShadingType type,
782 const RetainPtr<CFX_DIBitmap>& pBitmap,
783 const CFX_Matrix& mtObject2Bitmap,
784 RetainPtr<const CPDF_Stream> pShadingStream,
785 const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
787 bool bNoPathSmooth,
788 int alpha) {
789 DCHECK_EQ(pBitmap->GetFormat(), FXDIB_Format::kArgb);
790 DCHECK(type == kCoonsPatchMeshShading ||
791 type == kTensorProductPatchMeshShading);
792
793 CFX_DefaultRenderDevice device;
794 device.Attach(pBitmap);
795
796 CPDF_MeshStream stream(type, funcs, std::move(pShadingStream),
797 std::move(pCS));
798 if (!stream.Load())
799 return;
800
801 PatchDrawer patch;
802 patch.alpha = alpha;
803 patch.pDevice = &device;
804 patch.bNoPathSmooth = bNoPathSmooth;
805
806 for (int i = 0; i < 13; i++) {
807 patch.path.AppendPoint(CFX_PointF(), i == 0
810 }
811
812 CFX_PointF coords[16];
813 int point_count = type == kTensorProductPatchMeshShading ? 16 : 12;
814 while (!stream.IsEOF()) {
815 if (!stream.CanReadFlag())
816 break;
817 uint32_t flag = stream.ReadFlag();
818 int iStartPoint = 0;
819 int iStartColor = 0;
820 int i = 0;
821 if (flag) {
822 iStartPoint = 4;
823 iStartColor = 2;
824 CFX_PointF tempCoords[4];
825 for (i = 0; i < 4; i++) {
826 tempCoords[i] = coords[(flag * 3 + i) % 12];
827 }
828 fxcrt::spancpy(pdfium::make_span(coords), pdfium::make_span(tempCoords));
829 CoonColor tempColors[2] = {
830 tempColors[0] = patch.patch_colors[flag],
831 tempColors[1] = patch.patch_colors[(flag + 1) % 4]};
832 fxcrt::spancpy(pdfium::make_span(patch.patch_colors),
833 pdfium::make_span(tempColors));
834 }
835 for (i = iStartPoint; i < point_count; i++) {
836 if (!stream.CanReadCoords())
837 break;
838 coords[i] = mtObject2Bitmap.Transform(stream.ReadCoords());
839 }
840
841 for (i = iStartColor; i < 4; i++) {
842 if (!stream.CanReadColor())
843 break;
844
845 float r;
846 float g;
847 float b;
848 std::tie(r, g, b) = stream.ReadColor();
849
850 patch.patch_colors[i].comp[0] = static_cast<int32_t>(r * 255);
851 patch.patch_colors[i].comp[1] = static_cast<int32_t>(g * 255);
852 patch.patch_colors[i].comp[2] = static_cast<int32_t>(b * 255);
853 }
854 CFX_FloatRect bbox =
855 CFX_FloatRect::GetBBox(pdfium::make_span(coords).first(point_count));
856 if (bbox.right <= 0 || bbox.left >= (float)pBitmap->GetWidth() ||
857 bbox.top <= 0 || bbox.bottom >= (float)pBitmap->GetHeight()) {
858 continue;
859 }
860 CoonBezier C1;
861 CoonBezier C2;
862 CoonBezier D1;
863 CoonBezier D2;
864 C1.InitFromPoints(coords[0].x, coords[0].y, coords[11].x, coords[11].y,
865 coords[10].x, coords[10].y, coords[9].x, coords[9].y);
866 C2.InitFromPoints(coords[3].x, coords[3].y, coords[4].x, coords[4].y,
867 coords[5].x, coords[5].y, coords[6].x, coords[6].y);
868 D1.InitFromPoints(coords[0].x, coords[0].y, coords[1].x, coords[1].y,
869 coords[2].x, coords[2].y, coords[3].x, coords[3].y);
870 D2.InitFromPoints(coords[9].x, coords[9].y, coords[8].x, coords[8].y,
871 coords[7].x, coords[7].y, coords[6].x, coords[6].y);
872 patch.Draw(1, 1, 0, 0, C1, C2, D1, D2);
873 }
874}
875
876} // namespace
877
878// static
880 CPDF_RenderContext* pContext,
881 const CPDF_PageObject* pCurObj,
882 const CPDF_ShadingPattern* pPattern,
883 const CFX_Matrix& mtMatrix,
884 const FX_RECT& clip_rect,
885 int alpha,
886 const CPDF_RenderOptions& options) {
887 RetainPtr<CPDF_ColorSpace> pColorSpace = pPattern->GetCS();
888 if (!pColorSpace)
889 return;
890
891 FX_ARGB background = 0;
892 RetainPtr<const CPDF_Dictionary> pDict =
893 pPattern->GetShadingObject()->GetDict();
894 if (!pPattern->IsShadingObject() && pDict->KeyExist("Background")) {
895 RetainPtr<const CPDF_Array> pBackColor = pDict->GetArrayFor("Background");
896 if (pBackColor && pBackColor->size() >= pColorSpace->CountComponents()) {
897 std::vector<float> comps = ReadArrayElementsToVector(
898 pBackColor.Get(), pColorSpace->CountComponents());
899
900 float R = 0.0f;
901 float G = 0.0f;
902 float B = 0.0f;
903 pColorSpace->GetRGB(comps, &R, &G, &B);
904 background = ArgbEncode(255, static_cast<int32_t>(R * 255),
905 static_cast<int32_t>(G * 255),
906 static_cast<int32_t>(B * 255));
907 }
908 }
909 FX_RECT clip_rect_bbox = clip_rect;
910 if (pDict->KeyExist("BBox")) {
911 clip_rect_bbox.Intersect(
912 mtMatrix.TransformRect(pDict->GetRectFor("BBox")).GetOuterRect());
913 }
914 bool bAlphaMode = options.ColorModeIs(CPDF_RenderOptions::kAlpha);
916 pDevice->DrawShading(pPattern, &mtMatrix, clip_rect_bbox, alpha,
917 bAlphaMode)) {
918 return;
919 }
920 CPDF_DeviceBuffer buffer(pContext, pDevice, clip_rect_bbox, pCurObj, 150);
921 RetainPtr<CFX_DIBitmap> pBitmap = buffer.Initialize();
922 if (!pBitmap) {
923 return;
924 }
925
926 if (background != 0) {
927 pBitmap->Clear(background);
928 }
929 const CFX_Matrix final_matrix = mtMatrix * buffer.GetMatrix();
930 const auto& funcs = pPattern->GetFuncs();
931 switch (pPattern->GetShadingType()) {
932 case kInvalidShading:
933 case kMaxShading:
934 return;
936 DrawFuncShading(pBitmap, final_matrix, pDict.Get(), funcs, pColorSpace,
937 alpha);
938 break;
939 case kAxialShading:
940 DrawAxialShading(pBitmap, final_matrix, pDict.Get(), funcs, pColorSpace,
941 alpha);
942 break;
943 case kRadialShading:
944 DrawRadialShading(pBitmap, final_matrix, pDict.Get(), funcs, pColorSpace,
945 alpha);
946 break;
948 // The shading object can be a stream or a dictionary. We do not handle
949 // the case of dictionary at the moment.
950 RetainPtr<const CPDF_Stream> pStream =
951 ToStream(pPattern->GetShadingObject());
952 if (pStream) {
953 DrawFreeGouraudShading(pBitmap, final_matrix, std::move(pStream), funcs,
954 pColorSpace, alpha);
955 }
956 break;
957 }
959 // The shading object can be a stream or a dictionary. We do not handle
960 // the case of dictionary at the moment.
961 RetainPtr<const CPDF_Stream> pStream =
962 ToStream(pPattern->GetShadingObject());
963 if (pStream) {
964 DrawLatticeGouraudShading(pBitmap, final_matrix, std::move(pStream),
965 funcs, pColorSpace, alpha);
966 }
967 break;
968 }
971 // The shading object can be a stream or a dictionary. We do not handle
972 // the case of dictionary at the moment.
973 RetainPtr<const CPDF_Stream> pStream =
974 ToStream(pPattern->GetShadingObject());
975 if (pStream) {
976 DrawCoonPatchMeshes(pPattern->GetShadingType(), pBitmap, final_matrix,
977 std::move(pStream), funcs, pColorSpace,
978 options.GetOptions().bNoPathSmooth, alpha);
979 }
980 break;
981 }
982 }
983 if (bAlphaMode)
984 pBitmap->SetRedFromBitmap(pBitmap);
985
987 pBitmap->ConvertColorScale(0, 0xffffff);
988
989 buffer.OutputToDevice();
990}
bool Attach(RetainPtr< CFX_DIBitmap > pBitmap)
static CFX_FloatRect GetBBox(pdfium::span< const CFX_PointF > pPoints)
CFX_Matrix operator*(const CFX_Matrix &right) const
CFX_PointF Transform(const CFX_PointF &point) const
CFX_Matrix GetInverse() const
bool DrawShading(const CPDF_ShadingPattern *pPattern, const CFX_Matrix *pMatrix, const FX_RECT &clip_rect, int alpha, bool bAlphaMode)
int GetDeviceCaps(int id) const
CPDF_DeviceBuffer(CPDF_RenderContext *pContext, CFX_RenderDevice *pDevice, const FX_RECT &rect, const CPDF_PageObject *pObj, int max_dpi)
const CFX_Matrix & GetMatrix() const
RetainPtr< const CPDF_Array > GetArrayFor(const ByteString &key) const
CFX_Matrix GetMatrixFor(const ByteString &key) const
CFX_PointF ReadCoords()
bool CanReadCoords() const
bool CanReadFlag() const
bool ReadVertex(const CFX_Matrix &pObject2Bitmap, CPDF_MeshVertex *vertex, uint32_t *flag)
bool CanReadColor() const
std::tuple< float, float, float > ReadColor()
const Options & GetOptions() const
bool ColorModeIs(Type mode) const
static void Draw(CFX_RenderDevice *pDevice, CPDF_RenderContext *pContext, const CPDF_PageObject *pCurObj, const CPDF_ShadingPattern *pPattern, const CFX_Matrix &mtMatrix, const FX_RECT &clip_rect, int alpha, const CPDF_RenderOptions &options)
ShadingType GetShadingType() const
@ kRadialShading
@ kAxialShading
@ kInvalidShading
@ kCoonsPatchMeshShading
@ kMaxShading
@ kTensorProductPatchMeshShading
@ kLatticeFormGouraudTriangleMeshShading
@ kFreeFormGouraudTriangleMeshShading
@ kFunctionBasedShading
constexpr FX_ARGB ArgbEncode(uint32_t a, uint32_t r, uint32_t g, uint32_t b)
Definition fx_dib.h:118
#define FXARGB_SETDIB(p, argb)
Definition fx_dib.h:137
#define FXSYS_IsFloatZero(f)
Definition fx_system.h:35
int FXSYS_roundf(float f)
Definition fx_system.cpp:92
float FXSYS_sqrt2(float a, float b)
#define FXDC_RENDER_CAPS
#define FXRC_SHADING
static constexpr CFX_FillRenderOptions WindingOptions()