1/*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "modules/sksg/include/SkSGGroup.h"
9
10#include "include/core/SkCanvas.h"
11
12#include <algorithm>
13
14namespace sksg {
15
16Group::Group(std::vector<sk_sp<RenderNode>> children)
17 : fChildren(std::move(children)) {
18 for (const auto& child : fChildren) {
19 this->observeInval(child);
20 }
21}
22
23Group::~Group() {
24 for (const auto& child : fChildren) {
25 this->unobserveInval(child);
26 }
27}
28
29void Group::clear() {
30 for (const auto& child : fChildren) {
31 this->unobserveInval(child);
32 }
33 fChildren.clear();
34}
35
36void Group::addChild(sk_sp<RenderNode> node) {
37 // should we allow duplicates?
38 for (const auto& child : fChildren) {
39 if (child == node) {
40 return;
41 }
42 }
43
44 this->observeInval(node);
45 fChildren.push_back(std::move(node));
46
47 this->invalidate();
48}
49
50void Group::removeChild(const sk_sp<RenderNode>& node) {
51 SkDEBUGCODE(const auto origSize = fChildren.size());
52 fChildren.erase(std::remove(fChildren.begin(), fChildren.end(), node), fChildren.end());
53 SkASSERT(fChildren.size() == origSize - 1);
54
55 this->unobserveInval(node);
56 this->invalidate();
57}
58
59void Group::onRender(SkCanvas* canvas, const RenderContext* ctx) const {
60 const auto local_ctx = ScopedRenderContext(canvas, ctx).setIsolation(this->bounds(),
61 canvas->getTotalMatrix(),
62 fRequiresIsolation);
63
64 for (const auto& child : fChildren) {
65 child->render(canvas, local_ctx);
66 }
67}
68
69const RenderNode* Group::onNodeAt(const SkPoint& p) const {
70 for (auto it = fChildren.crbegin(); it != fChildren.crend(); ++it) {
71 if (const auto* node = (*it)->nodeAt(p)) {
72 return node;
73 }
74 }
75
76 return nullptr;
77}
78
79SkRect Group::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
80 SkASSERT(this->hasInval());
81
82 SkRect bounds = SkRect::MakeEmpty();
83 fRequiresIsolation = false;
84
85 for (size_t i = 0; i < fChildren.size(); ++i) {
86 const auto child_bounds = fChildren[i]->revalidate(ic, ctm);
87
88 // If any of the child nodes overlap, group effects require layer isolation.
89 if (!fRequiresIsolation && i > 0 && child_bounds.intersects(bounds)) {
90#if 1
91 // Testing conservatively against the union of prev bounds is cheap and good enough.
92 fRequiresIsolation = true;
93#else
94 // Testing exhaustively doesn't seem to increase the layer elision rate in practice.
95 for (size_t j = 0; j < i; ++ j) {
96 if (child_bounds.intersects(fChildren[i]->bounds())) {
97 fRequiresIsolation = true;
98 break;
99 }
100 }
101#endif
102 }
103
104 bounds.join(child_bounds);
105 }
106
107 return bounds;
108}
109
110} // namespace sksg
111