OpenToonz - An open-source full-featured 2D animation creation software
C
update naru lazybrush (#6946)
Naru Nino1c54fb3320cf
diff --git a/stuff/config/current.txt b/stuff/config/current.txtindex 51f0fa192..1e51644ba 100644--- a/stuff/config/current.txt+++ b/stuff/config/current.txt@@ -1728,19 +1728,15 @@<item>"STD_naru_LazyBrushFx" "LazyBrush Naru" </item><item>"STD_naru_LazyBrushFx.mode" "Mode" </item>- <item>"STD_naru_LazyBrushFx.mask_color" "Mask Color" </item>- <item>"STD_naru_LazyBrushFx.undef_is_sink" "Fill Hole" </item>- <item>"STD_naru_LazyBrushFx.auto_scribble" "Auto Mask Scribble" </item>- <item>"STD_naru_LazyBrushFx.line_weight" "Line's Weights" </item>- <item>"STD_naru_LazyBrushFx.sink_pos" "Background Direction" </item>- <item>"STD_naru_LazyBrushFx.lambda" "Scribble Strength" </item>+ <item>"STD_naru_LazyBrushFx.blend_mode" "Blend Mode" </item>+ <item>"STD_naru_LazyBrushFx.enable_auto_scribble" "Enable Auto Scribble" </item>+ <item>"STD_naru_LazyBrushFx.auto_scribble_color" "Color" </item>+ <item>"STD_naru_LazyBrushFx.enable_auto_bg_scribble" "Enable Auto BG Scribble" </item>+ <item>"STD_naru_LazyBrushFx.ref_bgcolor" "BG Reference" </item>+ <item>"STD_naru_LazyBrushFx.auto_scribble_threshold" "Threshold" </item>+ <item>"STD_naru_LazyBrushFx.log_scale" "LoG Scale" </item><item>"STD_naru_LazyBrushFx.scr_type" "Scribble Type" </item>- <item>"STD_naru_LazyBrushFx.min_lightness" "Outline Cutoff" </item>- <item>"STD_naru_LazyBrushFx.log_scale" "LoG Filter Scale" </item>- <item>"STD_naru_LazyBrushFx.sigma" "Filter Smoothness" </item>- <item>"STD_naru_LazyBrushFx.alpha" "Difficulty Passing Through Ink" </item>- <item>"STD_naru_LazyBrushFx.auto_scribble_length" "Auto Scribble Margin" </item>- <item>"STD_naru_LazyBrushFx.auto_scribble_threshold" "Auto Scribble Outline Threshold" </item>+ <item>"STD_naru_LazyBrushFx.lambda" "Scribble Softness" </item></stringtable>diff --git a/stuff/profiles/layouts/fxs/STD_naru_LazyBrushFx.xml b/stuff/profiles/layouts/fxs/STD_naru_LazyBrushFx.xmlindex ee9fb1e41..997bb7c06 100644--- a/stuff/profiles/layouts/fxs/STD_naru_LazyBrushFx.xml+++ b/stuff/profiles/layouts/fxs/STD_naru_LazyBrushFx.xml@@ -1,21 +1,18 @@<fxlayout><page name="LazyBrush Config"><control>mode</control>- <control>mask_color</control>- <control>undef_is_sink</control>- <control>auto_scribble</control>- <control>line_weight</control>- <control>sink_pos</control>+ <control>blend_mode</control>- <vbox shrink="0" label="Advanced">- <control>scr_type</control>- <control>min_lightness</control>- <control>log_scale</control>- <control>sigma</control>- <control>alpha</control>- <control>lambda</control>- <control>auto_scribble_length</control>- <control>auto_scribble_threshold</control>- </vbox>+ <separator label="Auto Scribble Settings"/>+ <control>enable_auto_scribble</control>+ <control>auto_scribble_color</control>+ <control>enable_auto_bg_scribble</control>+ <control>ref_bgcolor</control>+ <control>auto_scribble_threshold</control>++ <separator label="Advanced"/>+ <control>log_scale</control>+ <control>scr_type</control>+ <control>lambda</control></page></fxlayout>diff --git a/toonz/sources/stdfx/CMakeLists.txt b/toonz/sources/stdfx/CMakeLists.txtindex 58e9949ee..36f2ae37f 100644--- a/toonz/sources/stdfx/CMakeLists.txt+++ b/toonz/sources/stdfx/CMakeLists.txt@@ -293,7 +293,6 @@ set(SOURCESiwa_motionflowfx.cppiwa_smootherfx.cppnaru_lazybrush.cpp- naru_maxflow.cpp)if(OpenCV_FOUND)diff --git a/toonz/sources/stdfx/naru_graph.h b/toonz/sources/stdfx/naru_graph.hindex a3e3cd096..aec43280d 100644--- a/toonz/sources/stdfx/naru_graph.h+++ b/toonz/sources/stdfx/naru_graph.h@@ -1,105 +1,635 @@-#include "stdfx.h"-#include <queue>+// https://github.com/patmjen/maxflow_algorithms-#define TERMINAL ((Graph::arc*)1)-#define ORPHAN ((Graph::arc*)2)+#ifndef REIMPLS_GRAPH2_H__+#define REIMPLS_GRAPH2_H__+#ifndef REIMPLS_PACKED+#define REIMPLS_PACKED+#endif+#include <vector>+#include <deque>+#include <cinttypes>+#include <cassert>+#include <algorithm>+#include <type_traits>++namespace reimpls {++using Time = uint32_t;+using Dist = uint16_t;++template <class Cap, class Term, class Flow, class ArcIdx = int32_t,+ class NodeIdx = int32_t>+class Graph2 {+ static_assert(std::is_integral<ArcIdx>::value,+ "ArcIdx must be an integer type");+ static_assert(std::is_integral<NodeIdx>::value,+ "NodeIdx must be an integer type");+ static_assert(std::is_signed<Term>::value, "Term must be a signed type");++ // Forward decls.+ struct Node;+ struct Arc;-class Graph {public:- typedef enum { SOURCE = 0, SINK = 1 } terminalType;+ static const NodeIdx INVALID_NODE =+ ~NodeIdx(0); // -1 for signed type, max. value for unsigned type+ static const ArcIdx INVALID_ARC =+ ~ArcIdx(0); // -1 for signed type, max. value for unsigned type+ static const ArcIdx TERMINAL_ARC = INVALID_ARC - 1;+ static const ArcIdx ORPHAN_ARC = INVALID_ARC - 2;++ enum TermType : int32_t { SOURCE = 0, SINK = 1 };++ Graph2(size_t expected_nodes, size_t expected_arcs);- Graph(int maxNodeNum);- ~Graph();+ NodeIdx add_node(size_t num = 1);++ void add_tweights(NodeIdx i, Term cap_source, Term cap_sink);++ void add_edge(NodeIdx i, NodeIdx j, Cap cap, Cap rev_cap,+ bool merge_duplicates = true);++ void init_maxflow();+ Flow maxflow();++ TermType what_segment(NodeIdx i, TermType default_segment = SOURCE) const;++ inline size_t get_node_num() const noexcept { return nodes.size() - 1; }+ inline size_t get_arc_num() const noexcept { return arcs.size(); }private:- struct node;- struct arc;-- struct node {- arc* firstArc;- arc* parentArc;- bool isSink : 1;- int tCap;+ std::vector<Node> nodes;+ std::vector<Arc> arcs;+ std::vector<Arc> arc_buffer;++ Flow flow;+ int32_t maxflow_iteration;++ NodeIdx first_active, last_active;+ std::deque<NodeIdx> orphan_nodes;++ Time time;++#pragma pack(1)+ struct REIMPLS_PACKED Node {+ ArcIdx first; // First out-going arc.+ ArcIdx parent; // Arc to parent node in search tree+ NodeIdx next_active; // Index of next active node (or itself if this is the+ // last one)++ Time timestamp; // Timestamp showing when dist was computed.+ Dist dist; // Distance to terminal.++ Term tr_cap; // If tr_cap > 0 then tr_cap is residual capacity of the arc+ // SOURCE->node. Otherwise -tr_cap is residual+ // capacity of the arc node->SINK.++ bool is_sink : 1; // flag showing if the node is in the source or sink tree+ // (if parent!=NULL)++ Node()+ : first(INVALID_ARC)+ , parent(INVALID_ARC)+ , next_active(INVALID_NODE)+ , timestamp(0)+ , dist(0)+ , tr_cap(0)+ , is_sink(false) {}};- struct arc {- node* headNode;- arc* nextArc;- arc* revArc;- int rCap;+ struct REIMPLS_PACKED Arc {+ ArcIdx sister; // Sister arc+ NodeIdx head; // Node this arc points to.++ Cap r_cap; // Residual capacity++ bool sister_sat; // Is the sister arc saturated++ Arc() {}++ Arc(NodeIdx head, ArcIdx next, Cap r_cap, bool sister_sat)+ : sister(next), head(head), r_cap(r_cap), sister_sat(sister_sat) {}};+#pragma pack()- node *nodes, *nodeLast;- arc *arcs, *arcLast;- int nodesNum, arcsNum;+ void add_half_edge(NodeIdx from, NodeIdx to, Cap cap, Cap rev_cap,+ bool merge_duplicates = true);- std::queue<node*> activeQueue;- std::queue<node*> orphanQueue;+ void make_active(NodeIdx i);+ void make_front_orphan(NodeIdx i);+ void make_back_orphan(NodeIdx i);- int flow;+ NodeIdx next_active();-public:- void addEdge(int from, int to, int cap, int revCap) {- if ((arcLast - arcs) + 2 >= arcsNum) {- throw std::runtime_error("Maximum number of edges exceeded");+ void augment(ArcIdx middle);+ Term tree_bottleneck(NodeIdx start, bool source_tree) const;+ void augment_tree(NodeIdx start, Term bottleneck, bool source_tree);++ ArcIdx grow_search_tree(NodeIdx start);+ template <bool source>+ ArcIdx grow_search_tree_impl(NodeIdx start);++ void process_orphan(NodeIdx i);+ template <bool source>+ void process_orphan_impl(NodeIdx i);++ /*inline ArcIdx sister_idx(ArcIdx a) const noexcept { return a ^ 1; }+ inline Arc& sister(ArcIdx a) { return arcs[sister_idx(a)]; }+ inline const Arc& sister(ArcIdx a) const { return arcs[sister_idx(a)]; }++ inline ArcIdx sister_or_arc_idx(ArcIdx a, bool sis) const noexcept { return a+ ^ (ArcIdx)sis; } inline Arc& sister_or_arc(ArcIdx a, bool sis) { return+ arcs[sister_or_arc_idx(a, sis)]; } inline const Arc& sister_or_arc(ArcIdx a,+ bool sis) const { return arcs[sister_or_arc_idx(a, sis)]; }*/++ Node& head_node(const Arc& a) { return nodes[static_cast<size_t>(a.head)]; }+ Node& head_node(ArcIdx a) { return head_node(arcs[a]); }+ const Node& head_node(const Arc& a) const { return nodes[a.head]; }+ const Node& head_node(ArcIdx a) const { return head_node(arcs[a]); }+};++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::Graph2(size_t expected_nodes,+ size_t expected_arcs)+ : nodes()+ , arcs()+ , arc_buffer()+ , flow(0)+ , maxflow_iteration(0)+ , first_active(INVALID_NODE)+ , last_active(INVALID_NODE)+ , orphan_nodes()+ , time(0) {+ nodes.reserve(expected_nodes + 1);+ nodes.resize(1); // Make room for sentinel node now+ arcs.reserve(2 * expected_arcs);+ arc_buffer.reserve(2 * expected_arcs);+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline NodeIdx Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::add_node(size_t num) {+ NodeIdx crnt = nodes.size();++#ifndef REIMPLS_NO_OVERFLOW_CHECKS+ if (crnt > std::numeric_limits<NodeIdx>::max() - num) {+ throw std::overflow_error(+ "Node count exceeds capacity of index type. "+ "Please increase capacity of NodeIdx type.");+ }+#endif++ nodes.resize(crnt + num);+ return crnt;+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::add_tweights(+ NodeIdx i, Term cap_source, Term cap_sink) {+ assert(i >= 0 && i < nodes.size());+ Term delta = nodes[i].tr_cap;+ if (delta > 0) {+ cap_source += delta;+ } else {+ cap_sink -= delta;+ }+ flow += std::min(cap_source, cap_sink);+ nodes[i].tr_cap = cap_source - cap_sink;+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::add_edge(+ NodeIdx i, NodeIdx j, Cap cap, Cap rev_cap, bool merge_duplicates) {+ assert(i >= 0 && i < nodes.size());+ assert(j >= 0 && j < nodes.size());+ assert(i != j);+ assert(cap >= 0);+ assert(rev_cap >= 0);++ if (merge_duplicates && cap == 0 && rev_cap == 0) {+ return;+ }++#ifndef REIMPLS_NO_OVERFLOW_CHECKS+ if (arcs.size() > std::numeric_limits<ArcIdx>::max() - 2) {+ throw std::overflow_error(+ "Arc count exceeds capacity of index type. "+ "Please increase capacity of ArcIdx type.");+ }+#endif++ add_half_edge(i, j, cap, rev_cap, merge_duplicates);+ add_half_edge(j, i, rev_cap, cap, merge_duplicates);+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::add_half_edge(+ NodeIdx from, NodeIdx to, Cap cap, Cap rev_cap, bool merge_duplicates) {+ ArcIdx ai;++ if (merge_duplicates) {+ // Search for existing arcs between nodes.+ ai = nodes[from].first;+ while (ai != INVALID_ARC) {+ Arc& arc = arcs[ai];+ if (arc.head == to) {+ // Existing arc found, adding capacity.+ arc.r_cap += cap;+ return;+ }+ ai = arc.sister;}- node* fromNode = nodes + from;- node* toNode = nodes + to;+ }- arc* newArc = arcLast++;- arc* revArc = arcLast++;+ // Create new arc.+ ai = arcs.size();+ arcs.emplace_back(to, nodes[from].first, cap, rev_cap == 0);+ nodes[from].first = ai;+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline typename Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::TermType+Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::what_segment(+ NodeIdx i, TermType default_segment) const {+ if (nodes[i].parent != INVALID_ARC) {+ return (nodes[i].is_sink) ? SINK : SOURCE;+ } else {+ return default_segment;+ }+}- newArc->headNode = toNode;- newArc->rCap = cap;- newArc->nextArc = fromNode->firstArc;- newArc->revArc = revArc;- fromNode->firstArc = newArc;+template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline Flow Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::maxflow() {+ // init_maxflow();- revArc->headNode = fromNode;- revArc->rCap = revCap;- revArc->nextArc = toNode->firstArc;- revArc->revArc = newArc;- toNode->firstArc = revArc;+ NodeIdx crnt_node = INVALID_NODE;++ // main loop+ while (true) {+ NodeIdx i = crnt_node;++ // Check if we are already exploring a valid active node+ if (i != INVALID_NODE) {+ Node& n = nodes[i];+ n.next_active = INVALID_NODE;+ if (n.parent == INVALID_ARC) {+ // Active node was not valid so don't explore after all+ i = INVALID_NODE;+ }+ }++ // If we are not already exploring a node try to get a new one+ if (i == INVALID_NODE) {+ i = next_active();+ if (i == INVALID_NODE) {+ // No more nodes to explore so we are done+ break;+ }+ }++ // At this point i must point to a valid active node+ ArcIdx source_sink_connector = grow_search_tree(i);++#ifndef REIMPLS_NO_OVERFLOW_CHECKS+ // Check for overflow in time variable.+ if (time == std::numeric_limits<Time>::max()) {+ throw std::overflow_error(+ "Overflow in 'time' variable. Please increase capacity of Time "+ "type.");+ }+#endif+ time++;++ if (source_sink_connector != INVALID_ARC) {+ // Growth was aborted because we found a node from the other tree+ nodes[i].next_active = i; // Mark as active+ crnt_node = i;++ augment(source_sink_connector);++ std::deque<NodeIdx> crnt_orphan_nodes =+ std::move(orphan_nodes); // Snapshot of current ophans+ for (NodeIdx orphan : crnt_orphan_nodes) {+ process_orphan(orphan);+ // If any additional orphans were added during processing, we process+ // them immediately This leads to a significant decrease of the overall+ // runtime+ while (!orphan_nodes.empty()) {+ NodeIdx o = orphan_nodes.front();+ orphan_nodes.pop_front();+ process_orphan(o);+ }+ }+ } else {+ crnt_node = INVALID_NODE;+ }}- void addTerminal(int nodeIndex, int tCap) { nodes[nodeIndex].tCap = tCap; }+ maxflow_iteration++;+ return flow;+}- terminalType getSegment(int nodeIndex, terminalType defaultType) {- if (nodes[nodeIndex].parentArc)- return nodes[nodeIndex].isSink ? SINK : SOURCE;- else- return defaultType;+template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::init_maxflow() {+ first_active = INVALID_NODE;+ last_active = INVALID_NODE;+ orphan_nodes.clear();+ time = 0;++ // Reorder arcs so outgoing arcs for a node are consecutive+ ArcIdx crnt = 0;+ arc_buffer.resize(arcs.size());+ for (size_t i = 0; i < nodes.size() - 1; ++i) {+ ArcIdx new_first = crnt;+ ArcIdx next;+ for (ArcIdx a = nodes[i].first; a != INVALID_ARC; a = next) {+ next = arcs[a].sister;+ arcs[a].sister = crnt;+ arc_buffer[crnt].head = arcs[a].head;+ arc_buffer[crnt].sister = a;+ arc_buffer[crnt].r_cap = arcs[a].r_cap;+ arc_buffer[crnt].sister_sat = arcs[a].sister_sat;+ ++crnt;+ }+ nodes[i].first = new_first;}- void mincut();+ // Set sentinel node+ nodes[nodes.size() - 1].first = crnt;-private:- void setActive(node* n) { activeQueue.push(n); }+ // Adjust sister indices+ for (auto& arc : arc_buffer) {+ arc.sister = arcs[arc.sister ^ 1].sister;+ }++ // Swap buffer+ std::swap(arcs, arc_buffer);++ // Init nodes and make relevant ones active+ for (size_t i = 0; i < nodes.size() - 1; ++i) {+ Node& n = nodes[i];+ n.next_active = INVALID_NODE;+ n.timestamp = time;+ if (n.tr_cap != 0) {+ // n is connected to the source or sink+ n.is_sink = n.tr_cap < 0; // negative capacity goes to sink+ n.parent = TERMINAL_ARC;+ n.dist = 1;+ make_active(i);+ } else {+ n.parent = INVALID_ARC;+ }+ }+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::make_active(NodeIdx i) {+ if (nodes[i].next_active == INVALID_NODE) {+ // It's not in the active list yet+ if (last_active != INVALID_NODE) {+ nodes[last_active].next_active = i;+ } else {+ first_active = i;+ }+ last_active = i;+ nodes[i].next_active = i;+ }+}- node* nextActive() {- while (!activeQueue.empty()) {- node* n = activeQueue.front();- activeQueue.pop();- if (n->parentArc == ORPHAN) continue;- return n;+template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::make_front_orphan(+ NodeIdx i) {+ nodes[i].parent = ORPHAN_ARC;+ orphan_nodes.push_front(i);+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::make_back_orphan(+ NodeIdx i) {+ nodes[i].parent = ORPHAN_ARC;+ orphan_nodes.push_back(i);+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline NodeIdx Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::next_active() {+ NodeIdx i;+ // Pop nodes from the active list until we find a valid one or run out of+ // nodes+ for (i = first_active; i != INVALID_NODE; i = first_active) {+ // Pop node from active list+ Node& n = nodes[i];+ if (n.next_active == i) {+ // This is the last node in the active list so "clear" it+ first_active = INVALID_NODE;+ last_active = INVALID_NODE;+ } else {+ first_active = n.next_active;+ }+ n.next_active = INVALID_NODE; // Mark as not active++ if (n.parent != INVALID_ARC) {+ // Valid active node found+ break;}- return nullptr;}+ return i;+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::augment(+ ArcIdx middle_idx) {+ Arc& middle = arcs[middle_idx];+ Arc& middle_sister = arcs[middle.sister];+ // Step 1: Find bottleneck capacity+ Term bottleneck = middle.r_cap;+ bottleneck = std::min(bottleneck, tree_bottleneck(middle_sister.head, true));+ bottleneck = std::min(bottleneck, tree_bottleneck(middle.head, false));++ // Step 2: Augment along source and sink tree+ middle_sister.r_cap += bottleneck;+ middle.r_cap -= bottleneck;+ middle_sister.sister_sat = middle.r_cap == 0;+ middle.sister_sat = middle_sister.r_cap == 0;+ augment_tree(middle_sister.head, bottleneck, true);+ augment_tree(middle.head, bottleneck, false);- void setOrphan(node* n) {- n->parentArc = ORPHAN;- orphanQueue.push(n);+ // Step 3: Add bottleneck to overall flow+ flow += bottleneck;+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline Term Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::tree_bottleneck(+ NodeIdx start, bool source_tree) const {+ NodeIdx i = start;+ Term bottleneck = std::numeric_limits<Term>::max();+ while (true) {+ ArcIdx a = nodes[i].parent;+ if (a == TERMINAL_ARC) {+ break;+ }+ Cap r_cap = source_tree ? arcs[arcs[a].sister].r_cap : arcs[a].r_cap;+ bottleneck = std::min<Term>(bottleneck, r_cap);+ i = arcs[a].head;}+ const Term tr_cap = nodes[i].tr_cap;+ return std::min<Term>(bottleneck, source_tree ? tr_cap : -tr_cap);+}- node* nextOrphan() {- if (!orphanQueue.empty()) {- node* n = orphanQueue.front();- orphanQueue.pop();- return n;- } else- return nullptr;+template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::augment_tree(+ NodeIdx start, Term bottleneck, bool source_tree) {+ NodeIdx i = start;+ while (true) {+ ArcIdx ai = nodes[i].parent;+ if (ai == TERMINAL_ARC) {+ break;+ }+ Arc& a = source_tree ? arcs[ai] : arcs[arcs[ai].sister];+ Arc& b = source_tree ? arcs[arcs[ai].sister] : arcs[ai];+ a.r_cap += bottleneck;+ b.r_cap -= bottleneck;+ a.sister_sat = b.r_cap == 0;+ b.sister_sat = a.r_cap == 0;+ if (b.r_cap == 0) {+ make_front_orphan(i);+ }+ i = arcs[ai].head;+ }+ nodes[i].tr_cap += source_tree ? -bottleneck : bottleneck;+ if (nodes[i].tr_cap == 0) {+ make_front_orphan(i);}+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline ArcIdx Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::grow_search_tree(+ NodeIdx start) {+ return nodes[start].is_sink ? grow_search_tree_impl<false>(start)+ : grow_search_tree_impl<true>(start);+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+template <bool source>+inline ArcIdx Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::grow_search_tree_impl(+ NodeIdx start_idx) {+ const Node& start = nodes[start_idx];+ const Node& next = nodes[start_idx + 1];+ // Add neighbor nodes search tree until we find a node from the other search+ // tree or run out of neighbors+ for (ArcIdx ai = start.first; ai != next.first; ++ai) {+ if (source ? arcs[ai].r_cap : !arcs[ai].sister_sat) {+ Node& n = head_node(ai);+ if (n.parent == INVALID_ARC) {+ // This node is not yet in a tree so claim it for this one+ n.is_sink = !source;+ n.parent = arcs[ai].sister;+ n.timestamp = start.timestamp;+ n.dist = start.dist + 1;+ make_active(arcs[ai].head);+ } else if (n.is_sink == source) {+ // Found a node from the other search tree so abort+ if (!source) {+ // If we are growing the sink tree we instead return the sister arc+ ai = arcs[ai].sister;+ }+ return ai;+ } else if (n.timestamp <= start.timestamp && n.dist > start.dist) {+ // Heuristic: trying to make the distance from j to the source/sink+ // shorter+ n.parent = arcs[ai].sister;+ n.timestamp = n.timestamp;+ n.dist = start.dist + 1;+ }+ }+ }+ return INVALID_ARC;+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::process_orphan(+ NodeIdx i) {+ if (nodes[i].is_sink) {+ process_orphan_impl<false>(i);+ } else {+ process_orphan_impl<true>(i);+ }+}++template <class Cap, class Term, class Flow, class ArcIdx, class NodeIdx>+template <bool source>+inline void Graph2<Cap, Term, Flow, ArcIdx, NodeIdx>::process_orphan_impl(+ NodeIdx i) {+ Node& n = nodes[i];+ Node& next = nodes[i + 1];+ static const int32_t INF_DIST = std::numeric_limits<int32_t>::max();+ int32_t min_d = INF_DIST;+ ArcIdx min_a0 = INVALID_ARC;+ // Try to find a new parent+ for (ArcIdx a0 = n.first; a0 != next.first; ++a0) {+ if (source ? !arcs[a0].sister_sat : arcs[a0].r_cap) {+ NodeIdx j = arcs[a0].head;+ ArcIdx a = nodes[j].parent;+ if (nodes[j].is_sink != source && a != INVALID_ARC) {+ // Check origin of m+ int32_t d = 0;+ while (true) {+ Node& m = nodes[j];+ if (m.timestamp == time) {+ d += m.dist;+ break;+ }+ a = m.parent;+ d++;+ if (a == TERMINAL_ARC) {+ m.timestamp = time;+ m.dist = 1;+ break;+ }+ if (a == ORPHAN_ARC) {+ d = INF_DIST; // infinite distance+ break;+ }+ j = arcs[a].head;+ }+ if (d < INF_DIST) {+ // m originates from the source+ if (d < min_d) {+ min_a0 = a0;+ min_d = d;+ }+ // Set marks along the path+ j = arcs[a0].head;+ while (nodes[j].timestamp != time) {+ Node& m = nodes[j];+ m.timestamp = time;+ m.dist = d--;+ j = arcs[m.parent].head;+ }+ }+ }+ }+ }+ n.parent = min_a0;+ if (min_a0 != INVALID_ARC) {+ n.timestamp = time;+ n.dist = min_d + 1;+ } else {+ // No parent was found so process neighbors+ for (ArcIdx a0 = n.first; a0 != next.first; ++a0) {+ NodeIdx j = arcs[a0].head;+ Node& m = nodes[j];+ if (m.is_sink != source && m.parent != INVALID_ARC) {+ if (source ? !arcs[a0].sister_sat : arcs[a0].r_cap) {+ make_active(j);+ }+ ArcIdx pa = m.parent;+ if (pa != TERMINAL_ARC && pa != ORPHAN_ARC && arcs[pa].head == i) {+ make_back_orphan(j);+ }+ }+ }+ }+}++} // namespace reimpls- void augment(arc* midArc);- void adopt();-};\ No newline at end of file+#endif // REIMPLS_GRAPH_H__\ No newline at end of filediff --git a/toonz/sources/stdfx/naru_lazybrush.cpp b/toonz/sources/stdfx/naru_lazybrush.cppindex b6f3f0cf6..435f71e03 100644--- a/toonz/sources/stdfx/naru_lazybrush.cpp+++ b/toonz/sources/stdfx/naru_lazybrush.cpp@@ -2,12 +2,48 @@#include "tfxparam.h"#include <math.h>#include "stdfx.h"--#include "naru_graph.h"+#include <cstdlib>+#include <memory>#include "tparamset.h"#include "trasterfx.h"#include "tpixelutils.h"+#include "tdoublekeyframe.h"++#include "naru_graph.h"+#include <opencv2/opencv.hpp>++using namespace std;+using GraphType = reimpls::Graph2<int, int, int>;+using namespace cv;++struct RenderContext {+ int mode;+ int scribbleType;+ int width, height, rasSize;+ float s, K, lambda, weightSoft;+ float autoScribbleTh;+ int terminalCap;+ bool enableAutoScribble;+ bool enableAutoBgScribble;++ int minX, minY, maxX, maxY;++ TPixelF refBGColor;+ TPixelF autoScribbleColor;+ vector<TPixelF> colorPalette;++ vector<float> procImgData;+ vector<float> refImgData;+ Mat refMat;+ vector<int> scribbleData;+ vector<int> mincutData;++ unique_ptr<GraphType> graph;+ int bgClusterId = 0;+ int autoScribbleId = 1;+ int blendMode;+};class naru_lazybrush final : public TStandardRasterFx {FX_PLUGIN_DECLARATION(naru_lazybrush)@@ -16,16 +52,23 @@ class naru_lazybrush final : public TStandardRasterFx {TRasterFxPort m_ref;TIntEnumParamP m_mode;- TPixelParamP m_maskcolor;- TIntEnumParamP m_scrtype;+ TPixelParamP m_bg_color;- TDoubleParamP m_minlightness;- TDoubleParamP m_logs;- TDoubleParamP m_sigma;+ TBoolParamP m_enable_auto_scribble;+ TPixelParamP m_auto_scribble_color;+ TDoubleParamP m_auto_scribble_threshold;++ TIntEnumParamP m_scribble_type;+ TDoubleParamP m_log_scale;TDoubleParamP m_lambda;+ TIntEnumParamP m_blend_mode;+ TBoolParamP m_enable_auto_bg_scribble;++ // Obsolete parameters for backward compatibility+ TPixelParamP m_mask_color;+ TDoubleParamP m_sigma;TDoubleParamP m_alpha;TDoubleParamP m_autoscrlen;- TDoubleParamP m_autoscrthresh;TDoubleParamP m_lineweight;TBoolParamP m_fillHole;TIntEnumParamP m_sinkpos;@@ -34,40 +77,61 @@ class naru_lazybrush final : public TStandardRasterFx {public:naru_lazybrush(): m_mode(new TIntEnumParam(0, "Mask+Line"))- , m_maskcolor(TPixel32(200, 200, 200, 255))- , m_scrtype(new TIntEnumParam(0, "Soft"))- , m_minlightness(0.02f)- , m_logs(0.05f)- , m_sigma(1.5f)- , m_lambda(0.6f)- , m_alpha(100.f)- , m_autoscrlen(4.f)- , m_autoscrthresh(0.1f)- , m_lineweight(4.f)- , m_fillHole(true)+ , m_bg_color(TPixel32(0, 0, 255))+ , m_enable_auto_scribble(true)+ , m_auto_scribble_color(TPixel32(200, 200, 200))+ , m_auto_scribble_threshold(0.5f)+ , m_scribble_type(new TIntEnumParam(0, "Soft"))+ , m_log_scale(10.0f)+ , m_lambda(0.05f)+ , m_blend_mode(new TIntEnumParam(0, "Multiply"))+ , m_enable_auto_bg_scribble(true)+ , m_mask_color(TPixel32(0, 0, 0))+ , m_sigma(0.0)+ , m_alpha(0.0)+ , m_autoscrlen(0.0)+ , m_lineweight(0.0)+ , m_fillHole(false), m_sinkpos(new TIntEnumParam(0, "All"))- , m_autoScribble(true) {+ , m_autoScribble(false) {bindParam(this, "mode", m_mode);- bindParam(this, "mask_color", m_maskcolor);- bindParam(this, "scr_type", m_scrtype);-- bindParam(this, "min_lightness", m_minlightness);- bindParam(this, "log_scale", m_logs);- bindParam(this, "sigma", m_sigma);- bindParam(this, "lambda", m_lambda);- bindParam(this, "alpha", m_alpha);- bindParam(this, "auto_scribble_length", m_autoscrlen);- bindParam(this, "auto_scribble_threshold", m_autoscrthresh);- bindParam(this, "line_weight", m_lineweight);- bindParam(this, "undef_is_sink", m_fillHole);- bindParam(this, "sink_pos", m_sinkpos);- bindParam(this, "auto_scribble", m_autoScribble);this->m_mode->addItem(1, "Mask");this->m_mode->addItem(2, "LoG Filter");- this->m_mode->addItem(3, "Capacity Map");- this->m_mode->addItem(4, "Scribble Map");- this->m_scrtype->addItem(1, "Hard");+ this->m_mode->addItem(4, "Scribble");++ bindParam(this, "blend_mode", m_blend_mode);+ this->m_blend_mode->addItem(1, "Normal");+ this->m_blend_mode->addItem(2, "Screen");+ this->m_blend_mode->addItem(3, "Overlay");+ this->m_blend_mode->addItem(4, "Darken");+ this->m_blend_mode->addItem(5, "Lighten");++ bindParam(this, "enable_auto_scribble", m_enable_auto_scribble);+ bindParam(this, "auto_scribble_color", m_auto_scribble_color);+ bindParam(this, "enable_auto_bg_scribble", m_enable_auto_bg_scribble);+ bindParam(this, "ref_bgcolor", m_bg_color);+ bindParam(this, "auto_scribble_threshold", m_auto_scribble_threshold);+ this->m_auto_scribble_threshold->setValueRange(0.f, 1.f);+++ bindParam(this, "scr_type", m_scribble_type);+ this->m_scribble_type->addItem(1, "Hard");++ bindParam(this, "log_scale", m_log_scale);+ this->m_log_scale->setValueRange(0.f, 100.f);++ bindParam(this, "lambda", m_lambda);+ this->m_lambda->setValueRange(0.0f, 1.f);++ bindParam(this, "mask_color", m_mask_color, true, true);+ bindParam(this, "sigma", m_sigma, true, true);+ bindParam(this, "alpha", m_alpha, true, true);+ bindParam(this, "auto_scribble_length", m_autoscrlen, true, true);+ bindParam(this, "line_weight", m_lineweight, true, true);+ bindParam(this, "undef_is_sink", m_fillHole, true, true);+ bindParam(this, "sink_pos", m_sinkpos, true, true);+ bindParam(this, "auto_scribble", m_autoScribble, true, true);this->m_sinkpos->addItem(1, "Bottom-Left");this->m_sinkpos->addItem(2, "Bottom-Center");@@ -78,13 +142,7 @@ public:this->m_sinkpos->addItem(7, "Top-Left");this->m_sinkpos->addItem(8, "Center-Left");- this->m_minlightness->setValueRange(0.f, 1.f);- this->m_logs->setValueRange(0.f, 5.f);- this->m_sigma->setValueRange(0.f, 5.f);- this->m_lambda->setValueRange(0.5f, 5.f);- this->m_alpha->setValueRange(1.f, 10000.f);- this->m_autoscrlen->setValueRange(1.f, 10.f);- this->m_autoscrthresh->setValueRange(0.f, 1.f);+ setFxVersion(2);addInputPort("Source", m_input);addInputPort("Reference", m_ref);@@ -110,539 +168,787 @@ public:return false;}+ void loadData(TIStream &is) override;+ void onObsoleteParamLoaded(const std::string ¶mName) override;+ void onFxVersionSet() override;+private:- const float gauKernel[3][3] = {- {1, 2, 1},- {2, 4, 2},- {1, 2, 1},- };- const float weightSum = 16.f;- const float lapKernel[3][3] = {- {0, 1, 0},- {1, -4, 1},- {0, 1, 0},- };+ //// Params+ array<array<float, 5>, 5> gauKernel = {{+ { 1.f / 256.f, 4.f / 256.f, 6.f / 256.f, 4.f / 256.f, 1.f / 256.f },+ { 4.f / 256.f, 16.f / 256.f, 24.f / 256.f, 16.f / 256.f, 4.f / 256.f },+ { 6.f / 256.f, 24.f / 256.f, 36.f / 256.f, 24.f / 256.f, 6.f / 256.f },+ { 4.f / 256.f, 16.f / 256.f, 24.f / 256.f, 16.f / 256.f, 4.f / 256.f },+ { 1.f / 256.f, 4.f / 256.f, 6.f / 256.f, 4.f / 256.f, 1.f / 256.f }+ }};++ array<array<float, 3>, 3> lapKernel = {{+ { 0.f, 1.f, 0.f },+ { 1.f, -4.f, 1.f },+ { 0.f, 1.f, 0.f }+ }};++ //// functions+ // generate Kernel Functions+ template <size_t N>+ void convolve(vector<float>& data, const array<array<float, N>, N>& kernel, const RenderContext& ctx);+ void logFilter(vector<float>& data, RenderContext& ctx);++ // Intensity Culc+ // I_f = 1 - max(0, s * LoG(I))+ void I_f(vector<float>& arg, const RenderContext& ctx) { // arg = LoG result+ for (int i = 0; i < ctx.rasSize; ++i) {+ arg[i] = fmax(0, 1.f - fmax(0, ctx.s * arg[i]));+ }+ }- int mode = 0; // 0:Mask+Line, 1:Mask, 2:LoG Filter, 3:Scribble Map- TPixelF maskColor; // �}�X�N�̐F+ // I_p = K * (I_f ^ 2) + 1+ void I_p(vector<float>& arg, const RenderContext& ctx) { // arg = I_f result+ for (int i = 0; i < ctx.rasSize; ++i) {+ arg[i] = ctx.K * arg[i] * arg[i] + 1.f;+ }+ }- const float LoG_draw_scale = 20.f; // LoG�t�B���^�̕`��X�P�[��- float LoG_s = 0.05f; // LoG�t�B���^�̃X�P�[��+ //-------------------------------------------------------------------- int idx(int x, int y, int w) { return y * w + x; }+ void initRasters(TRasterP& fullRas, TRasterP& refRas, TTile& fullTile,+ TTile& tile, const TRenderSettings& ri, double frame);- //-------------------------------------------------------------------+ template <typename PIXEL>+ void createScribbleIndexMap(TRasterPT<PIXEL>, RenderContext& ctx);+ template <typename PIXEL>+ void setMat(TRasterPT<PIXEL>, Mat&, const RenderContext& ctx);+ inline int colorToInt(const Vec4f& pix) {+ int r = static_cast<int>(pix[0] * 255 + 0.5f);+ int g = static_cast<int>(pix[1] * 255 + 0.5f);+ int b = static_cast<int>(pix[2] * 255 + 0.5f);+ int a = static_cast<int>(pix[3] * 255 + 0.5f);+ return (r << 24) | (g << 16) | (b << 8) | a;+ }+ void createPalette(const Mat&, RenderContext& ctx);template <typename PIXEL>- void doDraw(TRasterPT<PIXEL> ras, std::vector<float>& r,- std::vector<float>& g, std::vector<float>& b,- std::vector<float>& a);+ void rasterToGrayVector(TRasterPT<PIXEL> ras, vector<float>& vec, const RenderContext& ctx);++ void setBaundaryScribble(RenderContext& ctx);+ void autoScribble(RenderContext& ctx);+ void autoScribbleScan(int x, int y, int dx, int dy, RenderContext& ctx);++ void setCapacity(RenderContext& ctx);+ void setTerminalCapacity(int refInd, RenderContext& ctx);+ void updateMincutData(int refInd, RenderContext& ctx);+template <typename PIXEL>- void doGrayScale(TRasterPT<PIXEL> ras, double frame,- std::vector<float>& temp);+ void setMask(TRasterPT<PIXEL>& mask, const RenderContext& ctx);+template <typename PIXEL>- void doLoG(TRasterPT<PIXEL> ras, double frame, std::vector<float>& gray,- std::vector<float>& lap);+ void drawImgFromInt(TRasterPT<PIXEL> ras, const vector<int>& data, const RenderContext& ctx);+template <typename PIXEL>- void doGraph(TRasterPT<PIXEL> ras, double frame, TRasterPT<PIXEL> refRas,- bool refer_sw, std::vector<float>& lap, Graph& g);+ void drawImgFromFloat(TRasterPT<PIXEL> ras, const vector<float>& data, const RenderContext& ctx);+template <typename PIXEL>- void doColorize(TRasterPT<PIXEL> ras, double frame, Graph& g,- std::vector<float>& gray);+ void drawMaskAndLine(TRasterPT<PIXEL> ras, TRasterPT<PIXEL> mask, const RenderContext& ctx);+template <typename PIXEL>- void process(TRasterPT<PIXEL> ras, double frame, TRasterPT<PIXEL> refRas,- bool refer_sw);+ void process(TRasterPT<PIXEL> ras, double frame, RenderContext& ctx);++ // utils+ int idx(int x, int y, const RenderContext& ctx) { return max(0, min(y * ctx.width + x, ctx.rasSize - 1)); }++ template <typename PIXEL>+ inline float pixelToNormalizedGray(const PIXEL& pix) {+ float invMax = 1.f / (float)PIXEL::maxChannelValue;+ float L_premult = (0.299f * pix.r + 0.587f * pix.g + 0.114f * pix.b) * invMax;+ float m = (float)pix.m * invMax;+ return L_premult + 1.f - m;+ }};-template <typename PIXEL>-void naru_lazybrush::doDraw(TRasterPT<PIXEL> ras, std::vector<float>& r,- std::vector<float>& g, std::vector<float>& b,- std::vector<float>& a) {- int width = ras->getLx();- int height = ras->getLy();- ras->lock();- for (int y = 0; y < height; ++y) {- PIXEL* pix = ras->pixels(y);- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- pix->r = (typename PIXEL::Channel)(maskColor.m * maskColor.r *- fmin(r[p], 1.f) *- (float)PIXEL::maxChannelValue);- pix->g = (typename PIXEL::Channel)(maskColor.m * maskColor.g *- fmin(g[p], 1.f) *- (float)PIXEL::maxChannelValue);- pix->b = (typename PIXEL::Channel)(maskColor.m * maskColor.b *- fmin(b[p], 1.f) *- (float)PIXEL::maxChannelValue);- pix->m = (typename PIXEL::Channel)(maskColor.m * fmin(a[p], 1.f) *- (float)PIXEL::maxChannelValue);- pix++;- }+//------------------------------------------------------------------------------++void naru_lazybrush::doCompute(TTile& tile, double frame,+ const TRenderSettings& ri) {+ if (!m_input.isConnected()) return;++ TRasterP fullRas;+ TRasterP refRas;+ TTile fullTile;+ initRasters(fullRas, refRas, fullTile, tile, ri, frame);++ RenderContext ctx;+ ctx.width = fullRas->getLx();+ ctx.height = fullRas->getLy();+ ctx.rasSize = ctx.width * ctx.height;+ ctx.mode = m_mode->getValue();++ ctx.refBGColor = toPixelF(m_bg_color->getValueD(frame));+ ctx.enableAutoScribble = m_enable_auto_scribble->getValue();+ ctx.autoScribbleColor = toPixelF(m_auto_scribble_color->getValueD(frame));+ ctx.blendMode = m_blend_mode->getValue();+ ctx.enableAutoBgScribble = m_enable_auto_bg_scribble->getValue();++ ctx.scribbleData.resize(ctx.rasSize, -1);++ // default ColorPalette+ ctx.bgClusterId = 0;+ ctx.autoScribbleId = 1;+ ctx.colorPalette.clear();+ ctx.colorPalette.resize(2);+ ctx.colorPalette[0] = TPixelF(0, 0, 0, 0);+ ctx.colorPalette[1] = ctx.autoScribbleColor;++ // pre process reference scribble data+ if (m_ref.isConnected()) {+ if (TRaster32P ras32 = refRas)+ createScribbleIndexMap<TPixel32>(ras32, ctx);+ else if (TRaster64P ras64 = refRas)+ createScribbleIndexMap<TPixel64>(ras64, ctx);+ else if (TRasterFP rasF = refRas)+ createScribbleIndexMap<TPixelF>(rasF, ctx);+ else+ throw TException("unsupported Pixel Type");}- ras->unlock();++ // main process+ if (TRaster32P ras32 = fullRas)+ process<TPixel32>(ras32, frame, ctx);+ else if (TRaster64P ras64 = fullRas)+ process<TPixel64>(ras64, frame, ctx);+ else if (TRasterFP rasF = fullRas)+ process<TPixelF>(rasF, frame, ctx);+ else+ throw TException("unsupported Pixel Type");++ // copy result to tile+ TRasterP tileRas = tile.getRaster();+ TPoint startTilingPos = convert(fullTile.m_pos - tile.m_pos);+ tileRas->copy(fullRas, startTilingPos);}template <typename PIXEL>-void naru_lazybrush::doGrayScale(TRasterPT<PIXEL> ras, double frame,- std::vector<float>& gray) {- int width = ras->getLx();- int height = ras->getLy();-- float minLightness = m_minlightness->getValue(frame);+void naru_lazybrush::process(TRasterPT<PIXEL> ras, double frame, RenderContext& ctx) {+ ctx.K = 2 * (ctx.width + ctx.height);+ ctx.s = m_log_scale->getValue(frame);+ ctx.lambda = m_lambda->getValue(frame);+ ctx.autoScribbleTh = 1.0f - m_auto_scribble_threshold->getValue(frame);+ ctx.scribbleType = m_scribble_type->getValue();+ ctx.weightSoft = floorf((1.0f - ctx.lambda) * ctx.K);+ ctx.terminalCap = ctx.scribbleType == 0 ? 4 * ctx.weightSoft : 5 * ctx.K;+ ctx.procImgData.resize(ctx.rasSize, 0.f);+ ctx.refImgData.resize(ctx.rasSize, 0.f);++ //// process image data+ // Gray scale [I]+ rasterToGrayVector(ras, ctx.procImgData, ctx);++ // LoG Filter [LoG(I)]+ logFilter(ctx.procImgData, ctx);++ // [max(0, 1 - max(0, s * LoG))]+ I_f(ctx.procImgData, ctx);++ // Draw LoG Filter+ if (ctx.mode == 2) {+ drawImgFromFloat(ras, ctx.procImgData, ctx);+ return;+ }- ras->lock();- for (int y = 0; y < height; ++y) {- PIXEL* pix = ras->pixels(y);- for (int x = 0; x < width; ++x) {- float m = (float)pix->m / (float)PIXEL::maxChannelValue;- if (m != 0) {- float r = (float)pix->r / (m * (float)PIXEL::maxChannelValue);- float g = (float)pix->g / (m * (float)PIXEL::maxChannelValue);- float b = (float)pix->b / (m * (float)PIXEL::maxChannelValue);- gray[idx(x, y, width)] =- fmax(0.299f * r + 0.587f * g + 0.114f * b, minLightness);- } else {- gray[idx(x, y, width)] = 1.0f;+ // --- BBox calculation: fast search from the boundaries & union with reference scribbles ---+ ctx.minX = ctx.width;+ ctx.minY = ctx.height;+ ctx.maxX = -1;+ ctx.maxY = -1;++ // 1. Search from the top edge (minY)+ bool found = false;+ for (int y = 0; y < ctx.height; ++y) {+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ if ((ctx.procImgData[p] < ctx.autoScribbleTh) || (ctx.scribbleData[p] >= 1)) {+ ctx.minY = y;+ found = true;+ break;}- pix++;}+ if (found) break;}- ras->unlock();-}-template <typename PIXEL>-void naru_lazybrush::doLoG(TRasterPT<PIXEL> ras, double frame,- std::vector<float>& gray, std::vector<float>& lap) {- int width = ras->getLx();- int height = ras->getLy();-- // �K�E�V�A���t�B���^- std::vector<float> blurred(width * height, 0.0f);- for (int y = 1; y < height - 1; ++y) {- for (int x = 1; x < width - 1; ++x) {- float sum = 0.f;- for (int dy = -1; dy <= 1; ++dy) {- for (int dx = -1; dx <= 1; ++dx) {- sum += gray[idx(x + dx, y + dy, width)] * gauKernel[dy + 1][dx + 1];+ if (found) {+ // 2. Search from the bottom edge (maxY)+ found = false;+ for (int y = ctx.height - 1; y >= 0; --y) {+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ if ((ctx.procImgData[p] < ctx.autoScribbleTh) || (ctx.scribbleData[p] >= 1)) {+ ctx.maxY = y;+ found = true;+ break;}}- blurred[idx(x, y, width)] = sum / weightSum;+ if (found) break;}++ // 3. Search from the left edge (minX)+ found = false;+ for (int x = 0; x < ctx.width; ++x) {+ for (int y = 0; y < ctx.height; ++y) {+ int p = idx(x, y, ctx);+ if ((ctx.procImgData[p] < ctx.autoScribbleTh) || (ctx.scribbleData[p] >= 1)) {+ ctx.minX = x;+ found = true;+ break;+ }+ }+ if (found) break;+ }++ // 4. Search from the right edge (maxX)+ found = false;+ for (int x = ctx.width - 1; x >= 0; --x) {+ for (int y = 0; y < ctx.height; ++y) {+ int p = idx(x, y, ctx);+ if ((ctx.procImgData[p] < ctx.autoScribbleTh) || (ctx.scribbleData[p] >= 1)) {+ ctx.maxX = x;+ found = true;+ break;+ }+ }+ if (found) break;+ }+ } else {+ // If no target is detected, the BBox is considered invalid.+ ctx.minX = ctx.width;+ ctx.minY = ctx.height;+ ctx.maxX = -1;+ ctx.maxY = -1;}- // ���E�l��ݒ�- for (int x = 0; x < width; ++x) {- blurred[idx(x, 0, width)] = blurred[idx(x, 1, width)];- blurred[idx(x, height - 1, width)] = blurred[idx(x, height - 2, width)];+ // Execute the auto-scribble process prior to applying I_p, and evaluate it against the unmodified I_f.+ if (ctx.enableAutoScribble) {+ autoScribble(ctx);}- for (int y = 0; y < height; ++y) {- blurred[idx(0, y, width)] = blurred[idx(1, y, width)];- blurred[idx(width - 1, y, width)] = blurred[idx(width - 2, y, width)];+ // Set Baundary Scribble+ if (ctx.enableAutoBgScribble) {+ setBaundaryScribble(ctx);}- // ���v���V�A���t�B���^- for (int y = 1; y < height - 1; ++y) {- for (int x = 1; x < width - 1; ++x) {- float sum = 0.f;- for (int dy = -1; dy <= 1; ++dy) {- for (int dx = -1; dx <= 1; ++dx) {- sum +=- blurred[idx(x + dx, y + dy, width)] * lapKernel[dy + 1][dx + 1];- }- }- lap[idx(x, y, width)] = fmax(LoG_s * sum, 0.0f);+ // [K * (1 - max(0, s * LoG(I))) ^ 2 + 1]+ I_p(ctx.procImgData, ctx);++ // Draw Capacity Mode+ if (ctx.mode == 3) {+ vector<float> capDisp(ctx.rasSize, 0.f);+ for (int i = 0; i < ctx.rasSize; ++i) {+ capDisp[i] = (ctx.procImgData[i] - 1.f) / ctx.K;}+ drawImgFromFloat(ras, capDisp, ctx);+ return;}- for (int x = 0; x < width; ++x) {- lap[idx(x, 0, width)] = lap[idx(x, 1, width)];- lap[idx(x, height - 1, width)] = lap[idx(x, height - 2, width)];+ // Draw Scribble Map+ if (ctx.mode == 4) {+ drawImgFromInt(ras, ctx.scribbleData, ctx);+ return;}- for (int y = 0; y < height; ++y) {- lap[idx(0, y, width)] = lap[idx(1, y, width)];- lap[idx(width - 1, y, width)] = lap[idx(width - 2, y, width)];++ //// alpha expansion+ ctx.mincutData.assign(ctx.rasSize, ctx.bgClusterId);+ for (int t = 0; t < ctx.colorPalette.size(); ++t) {+ if (t == ctx.bgClusterId) continue;+ // Init Graph+ ctx.graph = make_unique<GraphType>(ctx.rasSize, ctx.rasSize * 4);+ ctx.graph->add_node(ctx.rasSize);++ // Capacity+ setCapacity(ctx);++ // Set Terminal Capacity+ setTerminalCapacity(t, ctx);++ // Process Graph Algorithm+ ctx.graph->init_maxflow();+ int flow = ctx.graph->maxflow();++ // update mincut data+ updateMincutData(t, ctx);+ }++ // Set Mask+ TRasterPT<PIXEL> mask = TRasterPT<PIXEL>(ctx.width, ctx.height);+ setMask<PIXEL>(mask, ctx);++ // draw+ if (ctx.mode == 0) {+ drawMaskAndLine(ras, mask, ctx);+ } else {+ ras->copy(mask);+ }+}+++//-------------------------------------------------------------------+void naru_lazybrush::initRasters(TRasterP &fullRas, TRasterP& refRas,+ TTile &fullTile, TTile& tile,+ const TRenderSettings& ri,+ double frame) {+ // get BBox of the input image+ TRectD fullBBox;+ m_input->getBBox(frame, fullBBox, ri);++ // get input raster+ TDimension size(0, 0);+ size.lx = tceil(fullBBox.getLx());+ size.ly = tceil(fullBBox.getLy());+ m_input->allocateAndCompute(fullTile, fullBBox.getP00(), size,+ tile.getRaster(), frame, ri);+ fullRas = fullTile.getRaster();++ // get reference raster+ if (m_ref.isConnected()) {+ TTile refTile;+ m_ref->allocateAndCompute(refTile, fullBBox.getP00(), size,+ fullRas, frame, ri);+ refRas = refTile.getRaster();}}template <typename PIXEL>-void naru_lazybrush::doGraph(TRasterPT<PIXEL> ras, double frame,- TRasterPT<PIXEL> refRas, bool refer_sw,- std::vector<float>& lap, Graph& g) {- int width = ras->getLx();- int height = ras->getLy();- int rasSize = width * height;-- // LoG to intensity- std::vector<float> intensity(rasSize, 0.0f);- float K = 2.f * (width + height);- for (int y = 0; y < height; ++y) {- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- intensity[p] = K * lap[p] + 1.f;- lap[p] = lap[p] * LoG_draw_scale;+void naru_lazybrush::createScribbleIndexMap(TRasterPT<PIXEL> refRas, RenderContext& ctx) {+ // Cast refColors to refMat+ setMat(refRas, ctx.refMat, ctx);++ // Create Palette+ createPalette(ctx.refMat, ctx);+}++template <typename PIXEL>+void naru_lazybrush::setMat(TRasterPT<PIXEL> ras, Mat& mat, const RenderContext& ctx) {+ mat.create(ctx.rasSize, 1, CV_32FC4);+ ras->lock();+ for (int y = 0; y < ctx.height; ++y) {+ PIXEL* pix = ras->pixels(y);+ for (int x = 0; x < ctx.width; ++x) {+ int i = idx(x, y, ctx);+ float alpha = (float)pix[x].m / (float)PIXEL::maxChannelValue;+ if (alpha < 1.f) {+ mat.at<Vec4f>(i) = Vec4f(0.f, 0.f, 0.f, 0.f);+ } else {+ mat.at<Vec4f>(i) = Vec4f(+ (float)pix[x].r / (float)PIXEL::maxChannelValue,+ (float)pix[x].g / (float)PIXEL::maxChannelValue,+ (float)pix[x].b / (float)PIXEL::maxChannelValue,+ 1.f+ );+ }}}+ ras->unlock();+}- // set capasity- std::vector<float> weights(rasSize, 0.0f);- std::vector<float> capacity(rasSize, 0.0f);- float alpha = m_alpha->getValue(frame);- float sigma = m_sigma->getValue(frame);- float inv_sigmaSq2 = 1.0 / (2 * sigma * sigma);- for (int y = 0; y < height; ++y) {- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- if (x < width - 1) {- int q = idx(x + 1, y, width);- float weight =- alpha * exp(-(intensity[p] + intensity[q]) * inv_sigmaSq2);- g.addEdge(p, q, weight, weight);- }- if (y < height - 1) {- int q = idx(x, y + 1, width);- float weight =- alpha * exp(-(intensity[p] + intensity[q]) * inv_sigmaSq2);- g.addEdge(p, q, weight, weight);+void naru_lazybrush::createPalette(const Mat& mat, RenderContext& ctx) {+ ctx.colorPalette.clear();+ vector<int> colorInts;++ // Define BG Color+ ctx.bgClusterId = 0;+ Vec4f bgColor(ctx.refBGColor.r, ctx.refBGColor.g, ctx.refBGColor.b, 1.f);+ colorInts.push_back(colorToInt(bgColor));+ ctx.colorPalette.push_back(TPixelF(0,0,0,0));++ // Define Auto Scribble Color+ if (ctx.enableAutoScribble) {+ ctx.autoScribbleId = 1;+ Vec4f asColor(ctx.autoScribbleColor.r, ctx.autoScribbleColor.g, ctx.autoScribbleColor.b,+ 1.f);+ int cInt = colorToInt(asColor);+ if (colorInts.size() == 0 || colorInts[0] != cInt) {+ colorInts.push_back(cInt);+ ctx.colorPalette.push_back(TPixelF(ctx.autoScribbleColor));+ }+ }++ // Define Scribble Colors from Reference+ int pos = 0;+ for (int pi = 0; pi < ctx.rasSize; ++pi) {+ Vec4f p = mat.at<Vec4f>(pi, 0);+ if (p[3] == 0) continue;+ p[3] = 1.f;++ int cInt = colorToInt(p);++ // Exist in Palette+ int found = -1;+ for (size_t i = 0; i < colorInts.size(); ++i) {+ if (colorInts[i] == cInt) {+ found = static_cast<int>(i);+ break;}- weights[p] = intensity[p] / (K * LoG_s);- capacity[p] = exp(-intensity[p] * inv_sigmaSq2);}++ if (found == -1) {+ // New Color+ ctx.colorPalette.push_back(+ TPixelF(p[0], p[1], p[2], 1.f));+ colorInts.push_back(cInt);+ found = static_cast<int>(colorInts.size() - 1);+ }+ ctx.scribbleData[pi] = found;}+}- // Scribble- std::vector<float> refR(rasSize, 0.0f);- std::vector<float> refG(rasSize, 0.0f);- std::vector<float> refB(rasSize, 0.0f);- std::vector<float> scribbleR(rasSize, 0.0f);- std::vector<float> scribbleB(rasSize, 0.0f);- float lambda = m_lambda->getValue(frame);- float softCapacity = floorf(lambda * alpha);- int scribbleType = m_scrtype->getValue(); // �X�N���u���^�C�v 0:Soft, 1:Hard- int tLinkCap = scribbleType == 0 ? softCapacity : K;- int sLinkCap = scribbleType == 0 ? alpha - softCapacity : 0;- // Exist Reference- if (refer_sw) {- refRas->lock();- for (int y = 0; y < height; ++y) {- PIXEL* pix = refRas->pixels(y);- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- refR[p] = (float)pix->r / (float)PIXEL::maxChannelValue;- refG[p] = (float)pix->g / (float)PIXEL::maxChannelValue;- refB[p] = (float)pix->b / (float)PIXEL::maxChannelValue;- pix++;- }+template <typename PIXEL>+void naru_lazybrush::rasterToGrayVector(TRasterPT<PIXEL> ras,+ vector<float>& vec,+ const RenderContext& ctx) {+ ras->lock();+ for (int y = 0; y < ctx.height; ++y) {+ PIXEL* pix = ras->pixels(y);+ for (int x = 0; x < ctx.width; ++x) {+ vec[idx(x, y, ctx)] = pixelToNormalizedGray<PIXEL>(pix[x]);}- refRas->unlock();- for (int y = 0; y < height; ++y) {- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- if (refR[p] > 0.5f && refG[p] < 0.5f && refB[p] < 0.5f) {- g.addTerminal(p, tLinkCap - sLinkCap);- scribbleR[p] = 1.f;- } else if (refR[p] < 0.5f && refG[p] < 0.5f && refB[p] > 0.5f) {- g.addTerminal(p, sLinkCap - tLinkCap);- scribbleB[p] = 1.f;+ }+ ras->unlock();+}++template<size_t N>+void naru_lazybrush::convolve(vector<float>& data,+ const array<array<float, N>, N>& kernel,+ const RenderContext& ctx) {+ int kSize = kernel.size();+ int half = kSize / 2;+ vector<float> inputData = data;+ for (int y = 0; y < ctx.height; ++y) {+ for (int x = 0; x < ctx.width; ++x) {+ float sum = 0.f;+ for (int ky = -half; ky <= half; ++ky) {+ for (int kx = -half; kx <= half; ++kx) {+ int ix = std::min(std::max(x + kx, 0), ctx.width - 1);+ int iy = std::min(std::max(y + ky, 0), ctx.height - 1);+ sum += inputData[idx(ix, iy, ctx)] * kernel[ky + half][kx + half];}}+ data[idx(x, y, ctx)] = sum;}}+}- float autoScribbleLength = m_autoscrlen->getValue(frame);- float autoScribbleThreshold = m_autoscrthresh->getValue(frame);- float lineWeight = m_lineweight->getValue(frame);- int sinkPos = m_sinkpos->getValue();- bool autoScribble = m_autoScribble->getValue();- if (autoScribble) {- // Auto Scribble- for (int i = 0; i < width + height; ++i) {- float fcx0, fcx1, fcy0, fcy1, dx, dy;- if (i < width) {- fcx0 = i;- fcy0 = 0;- fcx1 = i;- fcy1 = height - 1;- dx = 0;- dy = 1;- } else {- fcx0 = 0;- fcy0 = i - width + 1;- fcx1 = width - 1;- fcy1 = i - width + 1;- dx = 1;- dy = 0;- }- bool onLine, pOnLine;- onLine = false;- pOnLine = false;- fcx0 += dx * autoScribbleLength;- fcy0 += dy * autoScribbleLength;- for (int i = 0; i < 10000; ++i) {- fcx0 += dx;- fcy0 += dy;- int cx = fcx0;- int cy = fcy0;- if (cx < 0 || cx >= width - 1 || cy < 0 || cy >= height - 1) break;- int cp = idx(cx, cy, width);- if (weights[cp] > autoScribbleThreshold) {- fcx0 += dx * lineWeight;- fcy0 += dy * lineWeight;- onLine = true;- } else- onLine = false;- if (!onLine && pOnLine) {- g.addTerminal(cp, tLinkCap - sLinkCap);- scribbleR[cp] = 1.f;- break;- }- pOnLine = onLine;- }+void naru_lazybrush::logFilter(vector<float>& data, RenderContext& ctx) {+ // Gaussian filter+ convolve(data, gauKernel, ctx);- onLine = false;- pOnLine = false;- fcx1 -= dx * autoScribbleLength;- fcy1 -= dy * autoScribbleLength;- for (int i = 0; i < 10000; ++i) {- fcx1 -= dx;- fcy1 -= dy;- int cx = fcx1;- int cy = fcy1;- if (cx < 0 || cx >= width - 1 || cy < 0 || cy >= height - 1) break;- int cp = idx(cx, cy, width);- if (weights[cp] > autoScribbleThreshold) {- fcx1 -= dx * lineWeight;- fcy1 -= dy * lineWeight;- onLine = true;- } else- onLine = false;- if (!onLine && pOnLine) {- g.addTerminal(cp, tLinkCap - sLinkCap);- scribbleR[cp] = 1.f;- break;- }- pOnLine = onLine;+ // Laplacian filter+ convolve(data, lapKernel, ctx);+}++void naru_lazybrush::setCapacity(RenderContext& ctx) {+ for (int y = 0; y < ctx.height; ++y) {+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ if (x < ctx.width - 1) {+ int q = idx(x + 1, y, ctx);+ float weight = (ctx.procImgData[p] + ctx.procImgData[q]) * 0.5f;+ ctx.graph->add_edge(p, q, weight, weight);+ }+ if (y < ctx.height - 1) {+ int q = idx(x, y + 1, ctx);+ float weight = (ctx.procImgData[p] + ctx.procImgData[q]) * 0.5f;+ ctx.graph->add_edge(p, q, weight, weight);}}}+}- // ���E�l��ݒ�- int bdSize = 2 * (width + height - 2);- int initInds[] = {0,- width / 2,- width,- width + height / 2,- width + height,- width * 3 / 2 + height,- width * 2 + height,- width * 2 + height * 3 / 2};- std::vector<int> bdIdx(bdSize, false);- // 1 "Bottom-Left"- // 2 "Bottom-Center"- // 3 "Bottom-Right"- // 4 "Center-Right"- // 5 "Top-Right"- // 6 "Top-Center"- // 7 "Top-Left"- // 8 "Center-Left"- for (int i = 0; i < bdSize; ++i) {- int p;- if (i < width - 1)- p = idx(i, 0, width);- else if (i < width + height - 2)- p = idx(width - 1, i - width + 1, width);- else if (i < 2 * width + height - 3)- p = idx(width - 1 - (i - width - height + 2), height - 1, width);- else- p = idx(0, height - 1 - (i - 2 * width - height + 3), width);- bdIdx[i] = p;+void naru_lazybrush::autoScribble(RenderContext& ctx) {+ // Perform scanning only when a valid bounding box exists.+ if (ctx.maxX >= 0 && ctx.maxY >= 0) {+ // Scan inward from the four boundaries of the bounding box.+ // From the top edge downward+ for (int x = ctx.minX; x <= ctx.maxX; ++x) {+ autoScribbleScan(x, ctx.minY, 0, 1, ctx);+ }+ // From the bottom edge upward+ for (int x = ctx.minX; x <= ctx.maxX; ++x) {+ autoScribbleScan(x, ctx.maxY, 0, -1, ctx);+ }+ // From the left edge rightward+ for (int y = ctx.minY; y <= ctx.maxY; ++y) {+ autoScribbleScan(ctx.minX, y, 1, 0, ctx);+ }+ // From the right edge leftward+ for (int y = ctx.minY; y <= ctx.maxY; ++y) {+ autoScribbleScan(ctx.maxX, y, -1, 0, ctx);+ }}+}- if (sinkPos == 0) {- for (int i = 0; i < bdSize; ++i) {- int p = bdIdx[i];- g.addTerminal(p, -K);- scribbleB[p] = 1.f;+void naru_lazybrush::autoScribbleScan(int x, int y, int dx, int dy, RenderContext& ctx) {+ bool foundLine = false;+ while (x >= 0 && x < ctx.width && y >= 0 && y < ctx.height) {+ int cp = idx(x, y, ctx);+ bool isLine = ctx.procImgData[cp] < ctx.autoScribbleTh;+ if (isLine) {+ foundLine = true;+ } else if (foundLine) {+ // Mark the inner region once the scan has crossed the stroke boundary and the intensity returns above the threshold (i.e., isLine becomes false).+ ctx.scribbleData[cp] = ctx.autoScribbleId;+ break;}- } else {- int initIdx = initInds[(sinkPos - 1)];- bool inside = false;- for (int i = 0; i < bdSize; ++i) {- int p = bdIdx[(initIdx + i + bdSize) % bdSize];- if (scribbleR[p] == 1.f) {- inside = true;- break;- }- g.addTerminal(p, -K);- scribbleB[p] = 1.f;- }- if (inside) {- for (int i = 0; i < bdSize; ++i) {- int p = bdIdx[(initIdx - i + bdSize) % bdSize];- if (scribbleR[p] == 1.f) break;- g.addTerminal(p, -K);- scribbleB[p] = 1.f;+ x += dx;+ y += dy;+ }+}++void naru_lazybrush::setBaundaryScribble(RenderContext& ctx) {+ int padding = 3;+ if (ctx.maxX >= 0 && ctx.maxY >= 0) {+ // extend Bounding Box by padding+ int minX = ctx.minX - padding;+ int minY = ctx.minY - padding;+ int maxX = ctx.maxX + padding;+ int maxY = ctx.maxY + padding;++ // set scribble+ for (int y = minY; y <= maxY; ++y) {+ for (int x = minX; x <= maxX; ++x) {+ if (x < 0 || x >= ctx.width || y < 0 || y >= ctx.height) continue;+ bool isBBEdge = (x == minX || x == maxX || y == minY || y == maxY);+ if (isBBEdge) {+ int p = idx(x, y, ctx);+ ctx.scribbleData[p] = -2;+ }}}}+}- std::vector<float> drawZero(rasSize, 0.0f);- std::vector<float> drawOne(rasSize, 1.0f);- if (mode == 2) { // Draw LoG Filter- doDraw(ras, lap, lap, lap, drawOne);- } else if (mode == 3) { // Draw Capacity Map- doDraw(ras, capacity, capacity, capacity, drawOne);- } else if (mode == 4) { // Draw Scribble Map- doDraw(ras, scribbleR, drawZero, scribbleB, drawOne);+void naru_lazybrush::setTerminalCapacity(int refInd, RenderContext& ctx) {+ int hardCap = 5 * ctx.K;+ for (int y = 0; y < ctx.height; ++y) {+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ if (ctx.scribbleData[p] == -2) {+ // scribbleData[p] == -2 represents the outer boundary of the image.+ // Connect to the sink (T) to establish a strict boundary constraint.+ ctx.graph->add_tweights(p, 0, hardCap);+ } else if (ctx.scribbleData[p] == -1) {+ // No scribble present: addition of a t-link is not required.+ continue;+ } else if (ctx.scribbleData[p] == refInd) {+ // Connect the target scribble color to the source (S).+ ctx.graph->add_tweights(p, ctx.terminalCap, 0);+ } else {+ // Connect all other scribble colors to the sink (T) collectively.+ ctx.graph->add_tweights(p, 0, ctx.terminalCap);+ }+ }}}-template <typename PIXEL>-void naru_lazybrush::doColorize(TRasterPT<PIXEL> ras, double frame, Graph& g,- std::vector<float>& gray) {- int width = ras->getLx();- int height = ras->getLy();-- bool fillHole = m_fillHole->getValue();- g.mincut();- std::vector<float> maskR(width * height, 0.0f);- std::vector<float> maskG(width * height, 0.0f);- std::vector<float> maskB(width * height, 0.0f);- std::vector<float> maskM(width * height, 0.0f);- // Mask- for (int y = 0; y < height; ++y) {- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- if (!g.getSegment(p, fillHole ? g.SOURCE : g.SINK)) { // SOURCE- maskR[p] = maskColor.m * maskColor.r;- maskG[p] = maskColor.m * maskColor.g;- maskB[p] = maskColor.m * maskColor.b;- maskM[p] = maskColor.m;+void naru_lazybrush::updateMincutData(int refInd, RenderContext& ctx) {+ for (int y = 0; y < ctx.height; ++y) {+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ if (ctx.graph->what_segment(p, ctx.graph->SOURCE) ==+ ctx.graph->SOURCE) {+ ctx.mincutData[p] = refInd;}}}+}- std::vector<float> lineR(width * height, 0.0f);- std::vector<float> lineG(width * height, 0.0f);- std::vector<float> lineB(width * height, 0.0f);- std::vector<float> lineM(width * height, 0.0f);- // Line- if (mode == 0) {- // line => (r, g, b, 1.), noLine => (r, g, b, 0.)- ras->lock();- for (int y = 0; y < height; ++y) {- PIXEL* pix = ras->pixels(y);- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- float m = (float)pix->m / (float)PIXEL::maxChannelValue;- if (m != 0) {- float r = (float)pix->r / (float)PIXEL::maxChannelValue;- float g = (float)pix->g / (float)PIXEL::maxChannelValue;- float b = (float)pix->b / (float)PIXEL::maxChannelValue;- lineM[p] = (1.f - fmin(fmin(r, g), b)) * m;- lineR[p] = r;- lineG[p] = g;- lineB[p] = b;- }- pix++;+template <typename PIXEL>+void naru_lazybrush::setMask(TRasterPT<PIXEL>& mask, const RenderContext& ctx) {+ mask->lock();+ for (int y = 0; y < ctx.height; ++y) {+ PIXEL* maskPix = mask->pixels(y);+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ TPixelF c = ctx.colorPalette[ctx.mincutData[p]];++ maskPix[x].r =+ (typename PIXEL::Channel)(c.r * (float)PIXEL::maxChannelValue);+ maskPix[x].g =+ (typename PIXEL::Channel)(c.g * (float)PIXEL::maxChannelValue);+ maskPix[x].b =+ (typename PIXEL::Channel)(c.b * (float)PIXEL::maxChannelValue);+ maskPix[x].m =+ (typename PIXEL::Channel)(c.m * (float)PIXEL::maxChannelValue);++ if (maskPix[x].m == 0) {+ maskPix[x].r = 0;+ maskPix[x].g = 0;+ maskPix[x].b = 0;}}- ras->unlock();}- ras->lock();+ mask->unlock();+}- // result => line + mask- for (int y = 0; y < height; ++y) {+template <typename PIXEL>+void naru_lazybrush::drawImgFromFloat(TRasterPT<PIXEL> ras, const vector<float>& data, const RenderContext& ctx) {+ ras->lock();+ for (int y = 0; y < ctx.height; ++y) {PIXEL* pix = ras->pixels(y);- for (int x = 0; x < width; ++x) {- int p = idx(x, y, width);- pix->r = (typename PIXEL::Channel)(- (maskR[p] * (1.f - lineM[p]) + lineM[p] * lineR[p]) *- (float)PIXEL::maxChannelValue);- pix->g = (typename PIXEL::Channel)(- (maskG[p] * (1.f - lineM[p]) + lineM[p] * lineG[p]) *- (float)PIXEL::maxChannelValue);- pix->b = (typename PIXEL::Channel)(- (maskB[p] * (1.f - lineM[p]) + lineM[p] * lineB[p]) *- (float)PIXEL::maxChannelValue);- pix->m = (typename PIXEL::Channel)(fmax(maskM[p], lineM[p]) *- (float)PIXEL::maxChannelValue);- pix++;+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ pix[x].r = (typename PIXEL::Channel)(fmin(data[p], 1.f) *+ (float)PIXEL::maxChannelValue);+ pix[x].g = (typename PIXEL::Channel)(fmin(data[p], 1.f) *+ (float)PIXEL::maxChannelValue);+ pix[x].b = (typename PIXEL::Channel)(fmin(data[p], 1.f) *+ (float)PIXEL::maxChannelValue);+ pix[x].m = (typename PIXEL::Channel)(1.f * (float)PIXEL::maxChannelValue);}- ras->unlock();}+ ras->unlock();}-//-------------------------------------------------------------------------------template <typename PIXEL>-void naru_lazybrush::process(TRasterPT<PIXEL> ras, double frame,- TRasterPT<PIXEL> refRas, bool refer_sw) {- int width = ras->getLx();- int height = ras->getLy();- int rasSize = width * height;- std::vector<float> gray(rasSize);- std::vector<float> lap(rasSize);-- // params- mode = m_mode->getValue();- maskColor = toPixelF(m_maskcolor->getValueD(frame));- LoG_s = m_logs->getValue(frame);-- // create graph- Graph g = Graph(rasSize);-- doGrayScale<PIXEL>(ras, frame, gray);- doLoG<PIXEL>(ras, frame, gray, lap);- doGraph<PIXEL>(ras, frame, refRas, refer_sw, lap, g);- if (mode == 0 || mode == 1) {- doColorize<PIXEL>(ras, frame, g, gray);+void naru_lazybrush::drawImgFromInt(TRasterPT<PIXEL> ras, const vector<int>& data, const RenderContext& ctx) {+ ras->lock();+ for (int y = 0; y < ctx.height; ++y) {+ PIXEL* pix = ras->pixels(y);+ for (int x = 0; x < ctx.width; ++x) {+ int p = idx(x, y, ctx);+ TPixelF c;+ if (data[p] == -2 || data[p] == ctx.bgClusterId)+ c = ctx.refBGColor;+ else if (data[p] == -1)+ c = TPixelF(1.f, 1.f, 1.f, 1.f);+ else if (data[p] < ctx.colorPalette.size())+ c = ctx.colorPalette[data[p]];+ else+ c = TPixelF(1.f, 0, 1.f, 1.f);+ pix[x].r = (typename PIXEL::Channel)(c.r * (float)PIXEL::maxChannelValue);+ pix[x].g = (typename PIXEL::Channel)(c.g * (float)PIXEL::maxChannelValue);+ pix[x].b = (typename PIXEL::Channel)(c.b * (float)PIXEL::maxChannelValue);+ pix[x].m = (typename PIXEL::Channel)(c.m * (float)PIXEL::maxChannelValue);+ }}+ ras->unlock();}-void naru_lazybrush::doCompute(TTile& tile, double frame,- const TRenderSettings& ri) {- if (!m_input.isConnected()) return;-- // 1. ���摜�S���BBox���擾- TRectD fullBBox;- m_input->getBBox(frame, fullBBox, ri);+template <typename PIXEL>+void naru_lazybrush::drawMaskAndLine(TRasterPT<PIXEL> ras,+ TRasterPT<PIXEL> mask,+ const RenderContext& ctx) {+ ras->lock();+ mask->lock();+ for (int y = 0; y < ctx.height; ++y) {+ PIXEL* basePix = ras->pixels(y);+ PIXEL* maskPix = mask->pixels(y);++ for (int x = 0; x < ctx.width; ++x) {+ // 1. Get original color and normalize to [0, 1]+ float br = (float)basePix[x].r / (float)PIXEL::maxChannelValue;+ float bg = (float)basePix[x].g / (float)PIXEL::maxChannelValue;+ float bb = (float)basePix[x].b / (float)PIXEL::maxChannelValue;+ float ba = (float)basePix[x].m / (float)PIXEL::maxChannelValue;++ // 2. Get mask color and normalize to [0, 1]+ float mr = (float)maskPix[x].r / (float)PIXEL::maxChannelValue;+ float mg = (float)maskPix[x].g / (float)PIXEL::maxChannelValue;+ float mb = (float)maskPix[x].b / (float)PIXEL::maxChannelValue;+ float ma = (float)maskPix[x].m / (float)PIXEL::maxChannelValue;++ // 3. Compute original image line alpha+ float a_line = ba;++ // 4. Calculate output alpha+ float a_out = a_line + ma * (1.f - a_line);++ // 5. Apply blend mode f(C_b, C_s) where C_b = mask (bottom), C_s = original (top)+ float r_blend = 0.f, g_blend = 0.f, b_blend = 0.f;++ switch (ctx.blendMode) {+ case 0: // Multiply+ r_blend = mr * br;+ g_blend = mg * bg;+ b_blend = mb * bb;+ break;+ case 1: // Normal+ r_blend = br;+ g_blend = bg;+ b_blend = bb;+ break;+ case 2: // Screen+ r_blend = mr + br - mr * br;+ g_blend = mg + bg - mg * bg;+ b_blend = mb + bb - mb * bb;+ break;+ case 3: // Overlay+ r_blend = (mr < 0.5f) ? (2.f * mr * br) : (1.f - 2.f * (1.f - mr) * (1.f - br));+ g_blend = (mg < 0.5f) ? (2.f * mg * bg) : (1.f - 2.f * (1.f - mg) * (1.f - bg));+ b_blend = (mb < 0.5f) ? (2.f * mb * bb) : (1.f - 2.f * (1.f - mb) * (1.f - bb));+ break;+ case 4: // Darken+ r_blend = fmin(mr, br);+ g_blend = fmin(mg, bg);+ b_blend = fmin(mb, bb);+ break;+ case 5: // Lighten+ r_blend = fmax(mr, br);+ g_blend = fmax(mg, bg);+ b_blend = fmax(mb, bb);+ break;+ default:+ r_blend = br;+ g_blend = bg;+ b_blend = bb;+ break;+ }- // 2. ���摜�S�̃��X�^���m��- TDimension size(0, 0);- size.lx = tceil(fullBBox.getLx());- size.ly = tceil(fullBBox.getLy());- TTile fullTile;- m_input->allocateAndCompute(fullTile, fullBBox.getP00(), size,- tile.getRaster(), frame, ri);- TRasterP fullRas = fullTile.getRaster();+ // 6. Composite with alpha+ float r_out = 0.f, g_out = 0.f, b_out = 0.f;+ if (a_out > 0.f) {+ r_out = (a_line * (1.f - ma) * br + ma * (1.f - a_line) * mr + a_line * ma * r_blend) / a_out;+ g_out = (a_line * (1.f - ma) * bg + ma * (1.f - a_line) * mg + a_line * ma * g_blend) / a_out;+ b_out = (a_line * (1.f - ma) * bb + ma * (1.f - a_line) * mb + a_line * ma * b_blend) / a_out;+ }- // 3. �O���t�������t�����X�^�Ŏ��s- TRasterP refRas;- bool refer_sw = false;- if (m_ref.isConnected()) {- refer_sw = true;- TTile refTile;- m_ref->allocateAndCompute(refTile, fullBBox.getP00(), size, fullRas, frame,- ri);- refRas = refTile.getRaster();+ // Clamp and write back+ basePix[x].r = static_cast<typename PIXEL::Channel>(fmax(0.f, fmin(r_out, 1.f)) * (float)PIXEL::maxChannelValue);+ basePix[x].g = static_cast<typename PIXEL::Channel>(fmax(0.f, fmin(g_out, 1.f)) * (float)PIXEL::maxChannelValue);+ basePix[x].b = static_cast<typename PIXEL::Channel>(fmax(0.f, fmin(b_out, 1.f)) * (float)PIXEL::maxChannelValue);+ basePix[x].m = static_cast<typename PIXEL::Channel>(fmax(0.f, fmin(a_out, 1.f)) * (float)PIXEL::maxChannelValue);+ }}+ ras->unlock();+ mask->unlock();+}- if (TRaster32P ras32 = fullRas)- process<TPixel32>(ras32, frame, refRas, refer_sw);- else if (TRaster64P ras64 = fullRas)- process<TPixel64>(ras64, frame, refRas, refer_sw);- else if (TRasterFP rasF = fullRas)- process<TPixelF>(rasF, frame, refRas, refer_sw);- else- throw TException("unsupported Pixel Type");+//------------------------------------------------------------------- // 4. tile �Ɍ��ʂ��R�s�[- TRasterP tileRas = tile.getRaster();- TPoint startTilingPos = convert(fullTile.m_pos - tile.m_pos);- tileRas->copy(fullRas, startTilingPos);+void naru_lazybrush::onObsoleteParamLoaded(const std::string ¶mName) {+ if (paramName == "mask_color") {+ m_auto_scribble_color->copy(m_mask_color.getPointer());+ } else if (paramName == "auto_scribble") {+ m_enable_auto_scribble->setValue(m_autoScribble->getValue());+ }}+void naru_lazybrush::loadData(TIStream &is) {+ TStandardRasterFx::loadData(is);+ if (getFxVersion() < 2) {+ if (m_log_scale->getKeyframeCount() > 0) {+ for (int i = 0; i < m_log_scale->getKeyframeCount(); ++i) {+ TDoubleKeyframe k = m_log_scale->getKeyframe(i);+ k.m_value *= 200.0;+ k.m_speedIn.y *= 200.0;+ k.m_speedOut.y *= 200.0;+ m_log_scale->setKeyframe(i, k);+ }+ } else {+ m_log_scale->setDefaultValue(m_log_scale->getDefaultValue() * 200.0);+ }+ setFxVersion(2);+ }+}++void naru_lazybrush::onFxVersionSet() {}+//------------------------------------------------------------------FX_PLUGIN_IDENTIFIER(naru_lazybrush, "naru_LazyBrushFx")