Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

fix: add braces to resolve dangling-else warnings

Anderson Pradodeab71a6bcd1
diff --git a/toonz/sources/toonz/colormodelviewer.cpp b/toonz/sources/toonz/colormodelviewer.cpp
index cb529c743..8f7e5c8de 100644
--- a/toonz/sources/toonz/colormodelviewer.cpp
+++ b/toonz/sources/toonz/colormodelviewer.cpp
@@ -1,4 +1,5 @@
+
// Tnz6 includes
#include "colormodelviewer.h"
#include "menubarcommandids.h"
@@ -6,7 +7,6 @@
#include "tapp.h"
#include "pane.h"
#include "colormodelbehaviorpopup.h"
-
// TnzTools includes
#include "tools/cursormanager.h"
#include "tools/cursors.h"
@@ -15,7 +15,6 @@
#include "tools/tool.h"
#include "tools/toolhandle.h"
#include "../tnztools/stylepickertool.h"
-
// TnzQt includes
#include "toonzqt/menubarcommand.h"
#include "toonzqt/viewcommandids.h"
@@ -24,7 +23,6 @@
#include "toonzqt/gutil.h"
#include "toonzqt/tselectionhandle.h"
#include "toonzqt/styleselection.h"
-
// TnzLib includes
#include "toonz/palettecmd.h"
#include "toonz/txshlevelhandle.h"
@@ -39,11 +37,9 @@
#include "toonz/txshlevel.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/txshcell.h"
-
// TnzCore includes
#include "tsystem.h"
#include "ttoonzimage.h"
-
// Qt includes
#include <QMimeData>
#include <QMouseEvent>
@@ -62,22 +58,17 @@ namespace {
TPaletteHandle *getPaletteHandle() {
return TApp::instance()->getPaletteController()->getCurrentLevelPalette();
}
-
} // namespace
//=============================================================================
/*! \class ColorModelViewer
- \brief The ColorModelViewer class is a flip book used to manage
- color model.
-
- Inherits \b FlipBook.
-
- This object show the reference image linked to current level
- palette.
-*/
-/*! \fn void ColorModelViewer::resetImageViewer()
- Set current level to TLevelP() and image to "0".
-*/
+ * \brief The ColorModelViewer class is a flip book used to
+ * manage color model. Inherits \b FlipBook. This object show the reference
+ * image linked to current level palette.
+ */
+/*! \fn void ColorModelViewer::resetImageViewer()
+ * Set current level to TLevelP() and image to "0".
+ */
ColorModelViewer::ColorModelViewer(QWidget *parent)
: FlipBook(parent, QString(tr("Color Model")),
std::vector<int>(
@@ -97,46 +88,36 @@ ColorModelViewer::ColorModelViewer(QWidget *parent)
, m_mode(0)
, m_currentRefImgPath(TFilePath()) {
setObjectName("colormodel");
-
m_pickLineStylesBtn = new QToolButton(this);
QString tip("Pick Line Styles");
QIcon icon = createQIcon("stylepicker_lines");
m_pickLineStylesBtn->setIcon(icon);
m_pickLineStylesBtn->setToolTip(tip);
m_pickLineStylesBtn->setCheckable(true);
-
QToolBar *toolBar = this->findChild<QToolBar *>("FlipConsolePlayToolBar");
if (toolBar) {
toolBar->addWidget(m_pickLineStylesBtn);
}
-
setToolCursor(m_imageViewer, ToolCursor::PickerCursor);
-
// Do not call the special procedure for flipbook closures...
disconnect(parentWidget(), SIGNAL(closeButtonPressed()), this,
SLOT(onCloseButtonPressed()));
-
bool ret = connect(this, SIGNAL(refImageNotFound()), this,
SLOT(onRefImageNotFound()), Qt::QueuedConnection);
-
assert(ret);
-
m_imageViewer->setMouseTracking(true);
}
//-----------------------------------------------------------------------------
-
ColorModelViewer::~ColorModelViewer() {}
-
//-----------------------------------------------------------------------------
/*! Accept event if current palette is not empty, event data has urls and each
- urls type are different from "src" and "tpl" .
-*/
+ * urls type are different from "src" and "tpl" .
+ */
void ColorModelViewer::dragEnterEvent(QDragEnterEvent *event) {
TPalette *palette = getPaletteHandle()->getPalette();
if (!palette) return;
const QMimeData *mimeData = event->mimeData();
if (!acceptResourceDrop(mimeData->urls())) return;
-
for (const QUrl &url : mimeData->urls()) {
TFilePath fp(url.toLocalFile().toStdWString());
std::string type = fp.getType();
@@ -147,11 +128,10 @@ void ColorModelViewer::dragEnterEvent(QDragEnterEvent *event) {
// For files, don't accept original proposed action in case it's a move
event->accept();
}
-
//-----------------------------------------------------------------------------
/*! If event data has urls, convert each urls in path and set view and current
- palette reference image (recall loadImage() and setLevel()).
-*/
+ * palette reference image (recall loadImage() and setLevel()).
+ */
void ColorModelViewer::dropEvent(QDropEvent *event) {
const QMimeData *mimeData = event->mimeData();
if (mimeData->hasUrls()) {
@@ -166,27 +146,21 @@ void ColorModelViewer::dropEvent(QDropEvent *event) {
event->accept();
}
}
-
//-----------------------------------------------------------------------------
/*! Set current palette reference image to \b fp recall:
- \b PaletteCmd::loadReferenceImage().
-*/
+ * \b PaletteCmd::loadReferenceImage().
+ */
// This function will be called when drag & drop the file into the color model
// viewer
-
void ColorModelViewer::loadImage(const TFilePath &fp) {
if (fp.isEmpty()) return;
-
TPaletteHandle *paletteHandle = getPaletteHandle();
TPalette *palette = paletteHandle->getPalette();
-
if (!palette || palette->isCleanupPalette()) {
DVGui::error(QObject::tr("Cannot load Color Model in current palette."));
return;
}
-
PaletteCmd::ColorModelLoadingConfiguration config;
-
// if the palette is locked, replace the color model's palette with the
// destination
if (palette->isLocked()) {
@@ -200,17 +174,13 @@ void ColorModelViewer::loadImage(const TFilePath &fp) {
if (ret == QDialog::Rejected) return;
popup.getLoadingConfiguration(config);
}
-
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
-
int isLoaded =
PaletteCmd::loadReferenceImage(paletteHandle, config, fp, scene);
-
if (0 != isLoaded) {
std::cout << "loadReferenceImage Failed for some reason." << std::endl;
return;
}
-
// no changes in the icon with replace (Keep the destination palette) option
if (config.behavior != PaletteCmd::ReplaceColorModelPlt) {
TXshLevel *level = TApp::instance()->getCurrentLevel()->getLevel();
@@ -220,12 +190,11 @@ void ColorModelViewer::loadImage(const TFilePath &fp) {
invalidateIcons(level, fids);
}
}
-
//-----------------------------------------------------------------------------
/*! Create and open the Right-click menu color model viewer.
*/
void ColorModelViewer::contextMenuEvent(QContextMenuEvent *event) {
- /*-- Levelが取得できない場合はMenuを出さない --*/
+ /*-- Do not show menu if level cannot be retrieved --*/
TApp *app = TApp::instance();
TXshLevel *xl = app->getCurrentLevel()->getLevel();
if (!xl) return;
@@ -234,26 +203,20 @@ void ColorModelViewer::contextMenuEvent(QContextMenuEvent *event) {
TPalette *currentPalette =
app->getPaletteController()->getCurrentLevelPalette()->getPalette();
if (!currentPalette) return;
-
QMenu menu(this);
-
menu.addAction(CommandManager::instance()->getAction(MI_LoadColorModel));
-
QAction *loadCurrentFrame =
new QAction(QString(tr("Use Current Frame")), this);
connect(loadCurrentFrame, SIGNAL(triggered()), SLOT(loadCurrentFrame()));
menu.addAction(loadCurrentFrame);
-
if (!m_imageViewer->getImage()) {
menu.exec(event->globalPos());
return;
}
-
QAction *removeColorModel =
new QAction(QString(tr("Remove Color Model")), this);
connect(removeColorModel, SIGNAL(triggered()), SLOT(removeColorModel()));
menu.addAction(removeColorModel);
-
/* If there is at least one style with "picked pos" parameter, then enable
* repick command */
TRasterImageP ri = m_imageViewer->getImage();
@@ -265,22 +228,17 @@ void ColorModelViewer::contextMenuEvent(QContextMenuEvent *event) {
SLOT(repickFromColorModel()));
menu.addAction(repickFromColorModelAct);
}
-
menu.addSeparator();
-
QString shortcut = QString::fromStdString(
CommandManager::instance()->getShortcutFromId(V_ViewReset));
QAction *reset = menu.addAction(tr("Reset View") + "\t " + shortcut);
connect(reset, SIGNAL(triggered()), m_imageViewer, SLOT(resetView()));
-
shortcut = QString::fromStdString(
CommandManager::instance()->getShortcutFromId(V_ZoomFit));
QAction *fit = menu.addAction(tr("Fit to Window") + "\t" + shortcut);
connect(fit, SIGNAL(triggered()), m_imageViewer, SLOT(fitView()));
-
menu.exec(event->globalPos());
}
-
//-----------------------------------------------------------------------------
/*! If left button is pressed recall \b pick() in event pos.
*/
@@ -288,7 +246,6 @@ void ColorModelViewer::mousePressEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton)
pick(event->pos() * getDevicePixelRatio(this));
}
-
//-----------------------------------------------------------------------------
/*! If left button is moved recall \b pick() in event pos.
*/
@@ -296,53 +253,44 @@ void ColorModelViewer::mouseMoveEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton)
pick(event->pos() * getDevicePixelRatio(this));
}
-
//-----------------------------------------------------------------------------
/*! Pick color from image and set it as current style.
*/
void ColorModelViewer::pick(const QPoint &p) {
TImageP img = m_imageViewer->getImage();
if (!img) return;
-
TPaletteHandle *ph =
TApp::instance()->getPaletteController()->getCurrentLevelPalette();
TPalette *currentPalette = ph->getPalette();
TXshLevelHandle *lh = TApp::instance()->getCurrentLevel();
TXshSimpleLevel *level = lh->getSimpleLevel();
if (!currentPalette) return;
-
- /*- 画面外ではPickできない -*/
+ /*- Cannot pick outside the screen -*/
if (!m_imageViewer->rect().contains(p)) return;
-
StylePicker picker(this, img, currentPalette);
-
QPoint viewP = m_imageViewer->mapFrom(this, p);
TPointD pos = m_imageViewer->getViewAff().inv() *
TPointD(viewP.x() - m_imageViewer->width() / 2,
-viewP.y() + m_imageViewer->height() / 2);
-
double scale2 = m_imageViewer->getViewAff().det();
/*---
- カレントToolに合わせてPickモードを変更
- 0=Area, 1=Line, 2=Line&Areas(default)
- ---*/
+ * Change pick mode according to current tool
+ * 0=Area, 1=Line, 2=Line&Areas(default)
+ * ---*/
int styleIndex =
picker.pickStyleId(pos + TPointD(-0.5, -0.5), 1, scale2, m_mode);
-
if (styleIndex < 0) return;
-
- /*-- pickLineモードのとき、取得Styleが0の場合 /
- * PurePaintの部分をクリックした場合 はカレントStyleを変えない --*/
+ /*-- In pickLine mode, if the acquired style is 0 /
+ * or if clicking on a pure paint area, do not change current style --*/
if (m_mode == 1) {
if (styleIndex == 0) return;
TToonzImageP ti = img;
if (ti && picker.pickTone(pos) == 255) return;
}
- /*- Paletteに存在しない色が取れた場合はreturn -*/
+ /*- If a color not in the palette is picked, return -*/
TPalette::Page *page = currentPalette->getStylePage(styleIndex);
if (!page) return;
-
- /*-- Styleを選択している場合は選択を解除する --*/
+ /*-- If a style is selected, deselect it --*/
TSelection *selection =
TApp::instance()->getCurrentSelection()->getSelection();
if (selection) {
@@ -350,15 +298,14 @@ void ColorModelViewer::pick(const QPoint &p) {
dynamic_cast<TStyleSelection *>(selection);
if (styleSelection) styleSelection->selectNone();
}
-
/*
- if the Style Picker tool is current and "organize palette" is activated,
- then move the picked style to the first page of the palette.
- */
+ * if the Style Picker tool is current and "organize palette" is activated,
+ * then move the picked style to the first page of the palette.
+ */
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
- if (tool->getName() == "T_StylePicker") {
+ if (tool->getName() == T_StylePicker) {
StylePickerTool *spTool = dynamic_cast<StylePickerTool *>(tool);
- if (spTool)
+ if (spTool) {
if (spTool->isOrganizePaletteActive()) {
TPoint point = picker.getRasterPoint(pos);
int frame = m_flipConsole->getCurrentFrame() - 1;
@@ -373,13 +320,11 @@ void ColorModelViewer::pick(const QPoint &p) {
replaceLevelStyle(lh, ph, styleIndex, ph->getStyleIndex());
return;
}
+ }
}
-
ph->setStyleIndex(styleIndex);
}
-
//-----------------------------------------------------------------------------
-
void ColorModelViewer::hideEvent(QHideEvent *e) {
TPaletteHandle *paletteHandle = getPaletteHandle();
TXshLevelHandle *levelHandle = TApp::instance()->getCurrentLevel();
@@ -390,16 +335,12 @@ void ColorModelViewer::hideEvent(QHideEvent *e) {
SLOT(showCurrentImage()));
disconnect(paletteHandle, SIGNAL(colorStyleChanged(bool)), this,
SLOT(showCurrentImage()));
-
disconnect(toolHandle, SIGNAL(toolSwitched()), this, SLOT(changePickType()));
disconnect(toolHandle, SIGNAL(toolChanged()), this, SLOT(changePickType()));
-
disconnect(levelHandle, SIGNAL(xshLevelViewChanged()), this,
SLOT(updateViewer()));
}
-
//-----------------------------------------------------------------------------
-
void ColorModelViewer::showEvent(QShowEvent *e) {
TPaletteHandle *paletteHandle = getPaletteHandle();
TXshLevelHandle *levelHandle = TApp::instance()->getCurrentLevel();
@@ -410,7 +351,7 @@ void ColorModelViewer::showEvent(QShowEvent *e) {
SLOT(showCurrentImage()));
ret = ret && connect(paletteHandle, SIGNAL(colorStyleChanged(bool)), this,
SLOT(showCurrentImage()));
- /*- ツールのTypeに合わせてPickのタイプも変え、カーソルも切り替える -*/
+ /*- Change pick type and cursor according to tool type -*/
ret = ret && connect(toolHandle, SIGNAL(toolSwitched()), this,
SLOT(changePickType()));
ret = ret && connect(toolHandle, SIGNAL(toolChanged()), this,
@@ -421,9 +362,8 @@ void ColorModelViewer::showEvent(QShowEvent *e) {
changePickType();
showCurrentImage();
}
-
//-----------------------------------------------------------------------------
-/*- ツールのTypeに合わせてPickのタイプも変え、カーソルも切り替える -*/
+/*- Change pick type and cursor according to tool type -*/
void ColorModelViewer::changePickType() {
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool->getName() == T_StylePicker) {
@@ -433,9 +373,8 @@ void ColorModelViewer::changePickType() {
return;
}
}
-
TPropertyGroup *propGroup = tool->getProperties(0);
- /*- Propertyの無いツールの場合 -*/
+ /*- For tools without properties -*/
if (!propGroup) {
m_mode = 2;
setToolCursor(m_imageViewer, ToolCursor::PickerCursor);
@@ -443,8 +382,7 @@ void ColorModelViewer::changePickType() {
m_pickLineStylesBtn->setChecked(true);
return;
}
-
- /*- Mode: の無いツールの場合は0が返る -*/
+ /*- Tools without "Mode:" return 0 -*/
TProperty *modeProp = propGroup->getProperty("Mode:");
if (!modeProp) {
m_mode = 2;
@@ -452,18 +390,17 @@ void ColorModelViewer::changePickType() {
m_pickLineStylesBtn->setDisabled(true);
m_pickLineStylesBtn->setChecked(true);
return;
- }
-
- else {
+ } else {
std::string var = modeProp->getValueAsString();
if (var == LINES) {
m_mode = 1;
setToolCursor(m_imageViewer, ToolCursor::PickerCursorLine);
} else if (var == AREAS) {
- if (m_pickLineStylesBtn->isChecked())
+ if (m_pickLineStylesBtn->isChecked()) {
m_mode = 2; // Areas & Line
- else
+ } else {
m_mode = 0;
+ }
setToolCursor(m_imageViewer, ToolCursor::PickerCursorArea);
} else // Line & Areas
{
@@ -474,16 +411,12 @@ void ColorModelViewer::changePickType() {
m_pickLineStylesBtn->setChecked(m_mode != 0);
}
}
-
//-----------------------------------------------------------------------------
-/*! If current palette level exists reset image viewer and set current viewer
- to reference image path level.
-*/
-
+/*! If current palette level exists reset image viewer and set current
+ * viewer to reference image path level.
+ */
void ColorModelViewer::updateViewer() { getImageViewer()->repaint(); }
-
//------------------------------------------------------------------------------
-
void ColorModelViewer::showCurrentImage() {
TPalette *palette = getPaletteHandle()->getPalette();
if (!palette) {
@@ -496,36 +429,33 @@ void ColorModelViewer::showCurrentImage() {
resetImageViewer();
return;
}
- /*-- UseCurrentFrameの場合、paletteを差し替える --*/
+ /*-- In case of UseCurrentFrame, replace the palette --*/
if (palette->getRefImgPath() == xl->getPath()) {
TXshSimpleLevel *sl = xl->getSimpleLevel();
if (!sl) {
resetImageViewer();
return;
}
- /*- 同じTFrameIdだった場合、パレットを差し替える -*/
+ /*- If same TFrameId, replace the palette -*/
if (m_currentRefImgPath == xl->getPath()) {
TImageP refImg = m_imageViewer->getImage();
if (!refImg) {
resetImageViewer();
return;
}
-
TImageP refImg_clone = refImg->cloneImage();
refImg_clone->setPalette(palette);
m_imageViewer->setImage(refImg_clone);
return;
}
- /*- UseCurrentFrameのLevelに移動してきた場合、Levelを入れ直す -*/
+ /*- When moving to a UseCurrentFrame level, reload the level -*/
else {
reloadCurrentFrame();
return;
}
}
-
- /*- 以下、通常のColorModelが読み込まれている場合 -*/
+ /*- Below: normal case where ColorModel is loaded -*/
resetImageViewer();
-
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
TFilePath fp = scene->decodeFilePath(palette->getRefImgPath());
if (TSystem::doesExistFileOrLevel(fp)) {
@@ -533,7 +463,6 @@ void ColorModelViewer::showCurrentImage() {
} else if (!fp.isEmpty())
emit refImageNotFound();
}
-
//-----------------------------------------------------------------------------
/*! Clone current image and set it in viewer.
*/
@@ -543,7 +472,7 @@ void ColorModelViewer::loadCurrentFrame() {
if (!xl) return;
TXshSimpleLevel *sl = xl->getSimpleLevel();
if (!sl) return;
- /*- カレントフレームのFIdの取得 -*/
+ /*- Get current frame's FId -*/
TFrameId fid;
if (app->getCurrentFrame()->isEditingLevel())
fid = app->getCurrentFrame()->getFid();
@@ -557,23 +486,19 @@ void ColorModelViewer::loadCurrentFrame() {
fid = column->getCellColumn()->getCell(frame).getFrameId();
}
TImageP img = sl->getFrame(fid, true);
-
TPalette *currentPalette =
app->getPaletteController()->getCurrentLevelPalette()->getPalette();
if (!img || !currentPalette) return;
TImageP refImg = img->cloneImage();
currentPalette->setRefImg(TImageP());
- /*--onPaletteSwitchedでRefImagePathを見て、自分自身のパスを参照していたらUpdateのルーチンを切り替える--*/
+ /*-- In onPaletteSwitched, check RefImagePath and switch update routine if
+ * referencing own path --*/
currentPalette->setRefImgPath(xl->getPath());
-
std::vector<TFrameId> fids;
fids.push_back(fid);
currentPalette->setRefLevelFids(fids, false);
-
m_currentRefImgPath = xl->getPath();
-
m_levels.clear();
-
m_levelNames.clear();
m_framesCount = 1;
m_palette = 0;
@@ -586,14 +511,12 @@ void ColorModelViewer::loadCurrentFrame() {
m_flipConsole->setFrameRange(1, 1, 1);
m_title1 = m_viewerTitle +
" :: " + m_currentRefImgPath.withoutParentDir().withFrame(fid);
- m_title = " :: <Use Current Frame>";
-
+ m_title = " :: <Use Current Frame>";
m_imageViewer->setImage(refImg);
}
-
//-----------------------------------------------------------------------------
/*--
- * UseCurrentFrameのLevelに移動してきたときに、改めてCurrentFrameを格納しなおす
+ * When moving to a level using UseCurrentFrame, reload the current frame again
* --*/
void ColorModelViewer::reloadCurrentFrame() {
TApp *app = TApp::instance();
@@ -601,29 +524,20 @@ void ColorModelViewer::reloadCurrentFrame() {
if (!xl) return;
TXshSimpleLevel *sl = xl->getSimpleLevel();
if (!sl) return;
-
TPalette *currentPalette =
app->getPaletteController()->getCurrentLevelPalette()->getPalette();
if (!currentPalette) return;
-
std::vector<TFrameId> fids = currentPalette->getRefLevelFids();
- /*- CurrentFrameなので、1Frameのみのはず -*/
+ /*- Since it's CurrentFrame, should only have 1 frame -*/
if (fids.size() != 1) return;
-
TImageP img = sl->getFrame(fids[0], true);
if (!img) return;
-
TImageP refImg = img->cloneImage();
-
currentPalette->setRefImg(TImageP());
-
currentPalette->setRefImgPath(xl->getPath());
-
- /*- currentRefImgPathの更新 -*/
+ /*- Update currentRefImgPath -*/
m_currentRefImgPath = xl->getPath();
-
m_levels.clear();
-
m_levelNames.clear();
m_framesCount = 1;
m_palette = 0;
@@ -636,42 +550,34 @@ void ColorModelViewer::reloadCurrentFrame() {
m_flipConsole->setFrameRange(1, 1, 1);
m_title1 = m_viewerTitle +
" :: " + m_currentRefImgPath.withoutParentDir().withFrame(fids[0]);
- m_title = " :: <Use Current Frame>";
-
+ m_title = " :: <Use Current Frame>";
m_imageViewer->setImage(refImg);
}
-
//-----------------------------------------------------------------------------
/*! Remove reference image from current palette using
- \b PaletteCmd::removeReferenceImage() and reset image viewer.
-*/
+ * \b PaletteCmd::removeReferenceImage() and reset image
+ * viewer.
+ */
void ColorModelViewer::removeColorModel() {
PaletteCmd::removeReferenceImage(getPaletteHandle());
resetImageViewer();
m_currentRefImgPath = TFilePath();
}
-
//-----------------------------------------------------------------------------
-
void ColorModelViewer::onRefImageNotFound() {
DVGui::info(
tr("It is not possible to retrieve the color model set for the current "
"level."));
}
-
//-----------------------------------------------------------------------------
-
void ColorModelViewer::repickFromColorModel() {
TImageP img = m_imageViewer->getImage();
if (!img) return;
TPaletteHandle *ph =
TApp::instance()->getPaletteController()->getCurrentLevelPalette();
-
PaletteCmd::pickColorByUsingPickedPosition(
ph, img, m_flipConsole->getCurrentFrame() - 1);
}
-
//=============================================================================
-
OpenFloatingPanel openColorModelCommand(MI_OpenColorModel, "ColorModel",
QObject::tr("Color Model"));
diff --git a/toonz/sources/toonz/colormodelviewer.h b/toonz/sources/toonz/colormodelviewer.h
index ca57ecddc..d4755f39b 100644
--- a/toonz/sources/toonz/colormodelviewer.h
+++ b/toonz/sources/toonz/colormodelviewer.h
@@ -1,24 +1,38 @@
#pragma once
-
#ifndef COLORMODELVIEWER_H
#define COLORMODELVIEWER_H
-
#include "flipbook.h"
-
//=============================================================================
// ColorModelViewer
//-----------------------------------------------------------------------------
-
+/*! \class ColorModelViewer
+ \brief Flipbook viewer specialized for displaying and interacting with
+ Color Model reference images.
+
+ Displays the reference image associated with the current level's palette.
+ Supports drag & drop loading, picking colors/styles, and "Use Current Frame"
+ mode. Overrides FlipBook behavior to integrate with palette and tool system.
+*/
class ColorModelViewer final : public FlipBook {
Q_OBJECT
- /*-- ツールのタイプを手元に持っておき、取得の手間を省く --*/
+ /*! Current pick mode:
+ 0 = Areas only
+ 1 = Lines only
+ 2 = Lines & Areas (default)
+ Cached locally to avoid repeated tool property lookups.
+ */
int m_mode;
- /*-- ColorModelのファイルパスを覚えておいて、UseCurrentFrame間の移動に対応
- * --*/
+
+ /*! Stores the current reference image path.
+ Used to detect transitions between normal Color Model and
+ "Use Current Frame" mode, ensuring correct reload behavior.
+ */
TFilePath m_currentRefImgPath;
- /*-- Set m_mode to 2 in changePickType after got m_mode if true && mode is AREA--*/
+ /*! Button to toggle line style picking when in "Areas" mode.
+ When checked and mode is AREAS, forces m_mode = 2 (Lines & Areas).
+ */
QToolButton *m_pickLineStylesBtn;
public:
@@ -28,7 +42,16 @@ public:
protected:
void dragEnterEvent(QDragEnterEvent *event) override;
void dropEvent(QDropEvent *event) override;
+
+ /*! Loads a new reference image into the current palette.
+ Triggers PaletteCmd::loadReferenceImage() with appropriate behavior.
+ */
void loadImage(const TFilePath &fp);
+
+ /*! Resets viewer to empty state.
+ Clears cache, levels, title, and current image.
+ Resets reference path and palette pointer.
+ */
void resetImageViewer() {
clearCache();
m_levels.clear();
@@ -39,37 +62,63 @@ protected:
}
void contextMenuEvent(QContextMenuEvent *event) override;
-
void mousePressEvent(QMouseEvent *) override;
void mouseMoveEvent(QMouseEvent *) override;
+
+ /*! Picks color/style at given point and applies it as current style.
+ Respects current tool mode and line/area settings.
+ */
void pick(const QPoint &p);
- void hideEvent(QHideEvent *e)
- override; // to avoid calling the hideEvent of class Flipbook!
+
+ void hideEvent(
+ QHideEvent *e) override; // Override to skip FlipBook::hideEvent
void showEvent(QShowEvent *e) override;
- /*-
- * UseCurrentFrameのLevelに移動してきたときに、改めてCurrentFrameを格納しなおす
- * -*/
+ /*! Reloads the current frame when entering a level using "Use Current Frame".
+ Ensures the displayed image matches the actual frame content.
+ */
void reloadCurrentFrame();
protected slots:
+ /*! Updates viewer with current palette's reference image.
+ Handles both external files and "Use Current Frame" mode.
+ */
void showCurrentImage();
+ /*! Sets the current frame as the Color Model reference.
+ Clones the frame image and updates palette metadata.
+ */
void loadCurrentFrame();
+
+ /*! Removes the reference image from the current palette.
+ Clears viewer and resets state.
+ */
void removeColorModel();
+ /*! Emitted when the expected reference image cannot be found.
+ Shows user-friendly error message.
+ */
void onRefImageNotFound();
+
+ /*! Triggers repaint of the image viewer.
+ Called when level view changes (e.g., frame switch).
+ */
void updateViewer();
- /*-
- * ツールのTypeとm_alwaysPickLineStyleに合わせてPickのタイプも変える。
- * それにあわせカーソルも切り替える
- * -*/
+ /*! Updates pick mode and cursor based on current tool.
+ Syncs with tool properties ("Mode:") and m_pickLineStylesBtn state.
+ */
void changePickType();
+ /*! Re-applies picked positions from the Color Model to update styles.
+ Useful after manual position adjustments.
+ */
void repickFromColorModel();
signals:
+ /*! Emitted when the reference image path exists but file is missing.
+ Allows UI to display warning.
+ */
void refImageNotFound();
};
diff --git a/toonz/sources/toonzlib/fill.cpp b/toonz/sources/toonzlib/fill.cpp
index e73f30a65..b7a7f023b 100644
--- a/toonz/sources/toonzlib/fill.cpp
+++ b/toonz/sources/toonzlib/fill.cpp
@@ -1,7 +1,6 @@
#include <stack>
-
#include "toonz/fill.h"
#include "toonz/ttilesaver.h"
#include "toonz/ttileset.h"
@@ -9,12 +8,14 @@
#include "tpixelutils.h"
#include "trastercm.h"
#include "tropcm.h"
-
//-----------------------------------------------------------------------------
-namespace { // Utility Function
-
+namespace { // Utility Functions
//-----------------------------------------------------------------------------
-
+/*! Thresholds tone value based on fill depth.
+ If fillDepth is max tone, returns original tone.
+ Otherwise, binarizes: returns max tone if above fillDepth, else original
+ tone.
+*/
inline int threshTone(const TPixelCM32 &pix, int fillDepth) {
if (fillDepth == TPixelCM32::getMaxTone())
return pix.getTone();
@@ -23,9 +24,12 @@ inline int threshTone(const TPixelCM32 &pix, int fillDepth) {
: pix.getTone();
}
+/*! Adjusts fill depth to match tone range (15 or 255).
+ For 15-tone: 15 - fillDepth
+ For 255-tone: (15 - fillDepth) repeated in both nibbles
+*/
inline int adjustFillDepth(const int &fillDepth) {
assert(fillDepth >= 0 && fillDepth < 16);
-
switch (TPixelCM32::getMaxTone()) {
case 15:
return 15 - fillDepth;
@@ -37,6 +41,10 @@ inline int adjustFillDepth(const int &fillDepth) {
}
}
+/*! Thresholds matte (alpha) value.
+ If fillDepth is 255, returns original matte.
+ Otherwise, returns 255 if matte < fillDepth, else original.
+*/
inline int threshMatte(int matte, int fillDepth) {
if (fillDepth == 255)
return matte;
@@ -44,23 +52,26 @@ inline int threshMatte(int matte, int fillDepth) {
return (matte < fillDepth) ? 255 : matte;
}
+/*! Finds nearest non-pure-paint (ink) pixel in cardinal directions (no
+ diagonal). Returns first valid ink pixel found (right → left → down → up).
+ Returns (-1,-1) if none found.
+*/
inline TPoint nearestInkNotDiagonal(const TRasterCM32P &r, const TPoint &p) {
TPixelCM32 *buf = (TPixelCM32 *)r->pixels(p.y) + p.x;
-
- if (p.x < r->getLx() - 1 && (!(buf + 1)->isPurePaint()))
+ if (p.x < r->getLx() - 1 && !(buf + 1)->isPurePaint())
return TPoint(p.x + 1, p.y);
-
- if (p.x > 0 && (!(buf - 1)->isPurePaint())) return TPoint(p.x - 1, p.y);
-
- if (p.y < r->getLy() - 1 && (!(buf + r->getWrap())->isPurePaint()))
+ if (p.x > 0 && !(buf - 1)->isPurePaint()) return TPoint(p.x - 1, p.y);
+ if (p.y < r->getLy() - 1 && !(buf + r->getWrap())->isPurePaint())
return TPoint(p.x, p.y + 1);
-
- if (p.y > 0 && (!(buf - r->getWrap())->isPurePaint()))
+ if (p.y > 0 && !(buf - r->getWrap())->isPurePaint())
return TPoint(p.x, p.y - 1);
-
return TPoint(-1, -1);
}
+/*! Collects unique neighboring ink pixels (cardinal directions only).
+ Avoids duplicates by tracking ink IDs in a set.
+ Returns vector of unique ink positions.
+*/
inline std::vector<TPoint> getNeighborInks(const TRasterCM32P &r,
const TPoint &p) {
TPixelCM32 *buf = (TPixelCM32 *)r->pixels(p.y) + p.x;
@@ -68,7 +79,6 @@ inline std::vector<TPoint> getNeighborInks(const TRasterCM32P &r,
std::set<int> inks;
TPixelCM32 *pix;
int ink;
-
if (p.x < r->getLx() - 1) {
pix = buf + 1;
if (!pix->isPurePaint()) {
@@ -77,7 +87,6 @@ inline std::vector<TPoint> getNeighborInks(const TRasterCM32P &r,
inks.insert(ink);
}
}
-
if (p.x > 0) {
pix = buf - 1;
if (!pix->isPurePaint()) {
@@ -88,7 +97,6 @@ inline std::vector<TPoint> getNeighborInks(const TRasterCM32P &r,
}
}
}
-
if (p.y < r->getLy() - 1) {
pix = buf + r->getWrap();
if (!pix->isPurePaint()) {
@@ -99,7 +107,6 @@ inline std::vector<TPoint> getNeighborInks(const TRasterCM32P &r,
}
}
}
-
if (p.y > 0) {
pix = buf - r->getWrap();
if (!pix->isPurePaint()) {
@@ -110,19 +117,16 @@ inline std::vector<TPoint> getNeighborInks(const TRasterCM32P &r,
}
}
}
-
return points;
}
-// dal punto x,y si espande a destra e a sinistra.
-// la riga ridisegnata va da *xa a *xb compresi
-// x1 <= *xa <= *xb <= x2
-// N.B. se non viene disegnato neanche un pixel *xa>*xb
+// Expands fill from point (x,y) both left and right.
+// The redrawn row spans from *xa to *xb (inclusive).
+// Constraint: x1 <= *xa <= *xb <= x2
+// Note: if no pixel is painted, *xa > *xb
//
-// "prevailing" is set to false on revert-filling the border of
-// region in the Rectangular, Freehand and Polyline fill procedures
-// in order to make the paint to protlude behind the line.
-
+// "prevailing" is disabled during border revert-fill in Rectangular,
+// Freehand, and Polyline fill to allow paint to extend behind lines.
void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
int paint, TPalette *palette, TTileSaverCM32 *saver,
bool prevailing = true, int paintAtClickPos = 0,
@@ -130,34 +134,30 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
bool usePrevailingReferFill = false) {
int tone, oldtone;
TPixelCM32 *pix, *pix0, *limit, *tmp_limit;
-
- /* vai a destra */
+ /* Expand to the right */
TPixelCM32 *line = r->pixels(p.y);
-
- pix0 = line + p.x;
- pix = pix0;
- limit = line + r->getBounds().x1;
- oldtone = pix->getTone();
- tone = oldtone;
+ pix0 = line + p.x;
+ pix = pix0;
+ limit = line + r->getBounds().x1;
+ oldtone = pix->getTone();
+ tone = oldtone;
for (; pix <= limit; pix++) {
if (pix->getPaint() == paint) break;
tone = pix->getTone();
if (tone == 0 || (pix->getPaint() != paintAtClickPos && defRegionWithPaint))
break;
- // prevent fill area from protruding behind the colored line
+ // Prevent fill from protruding behind colored lines
if (tone > oldtone) {
- // not-yet-colored line case
+ // Handle uncolored line case
if (prevailing && !pix->isPurePaint() && pix->getInk() != pix->getPaint())
break;
while (pix != pix0) {
- // iterate back in order to leave the pixel with the lowest tone
- // unpainted
+ // Step back to leave lowest-tone pixel unpainted
pix--;
- // make the one-pixel-width semi-transparent line to be painted
+ // Allow painting of 1-pixel semi-transparent lines
if (prevailing && pix->getInk() != pix->getPaint()) break;
if (pix->getTone() > oldtone) {
- // check if the current pixel is NOT with the lowest tone among the
- // vertical neighbors as well
+ // Ensure current pixel is not lowest tone among vertical neighbors
if (p.y > 0 && p.y < r->getLy() - 1) {
TPixelCM32 *upPix = pix - r->getWrap();
TPixelCM32 *downPix = pix + r->getWrap();
@@ -174,10 +174,10 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
oldtone = tone;
}
if (prevailing && tone == 0) {
- tmp_limit = pix + 10; // edge stop fill == 10 per default
+ tmp_limit = pix + 10; // Default edge-stop distance = 10 pixels
if (limit > tmp_limit) limit = tmp_limit;
int preVailingInk,
- oldPrevailingInk = 0; // avoid prevailing different Ink styles
+ oldPrevailingInk = 0; // Prevent mixing different ink styles
for (; pix <= limit; pix++) {
if (pix->getPaint() == paint) break;
if (pix->getTone() != 0) break;
@@ -188,11 +188,8 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
}
}
}
-
xb = p.x + pix - pix0 - 1;
-
- /* vai a sinistra */
-
+ /* Expand to the left */
pix = pix0;
limit = line + r->getBounds().x0;
oldtone = pix->getTone();
@@ -200,22 +197,20 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
for (pix--; pix >= limit; pix--) {
if (pix->getPaint() == paint) break;
tone = pix->getTone();
- if (tone == 0 || pix->getPaint() != paintAtClickPos && defRegionWithPaint)
+ if (tone == 0 || (pix->getPaint() != paintAtClickPos && defRegionWithPaint))
break;
- // prevent fill area from protruding behind the colored line
+ // Prevent fill from protruding behind colored lines
if (tone > oldtone) {
- // not-yet-colored line case
+ // Handle uncolored line case
if (prevailing && !pix->isPurePaint() && pix->getInk() != pix->getPaint())
break;
while (pix != pix0) {
- // iterate forward in order to leave the pixel with the lowest tone
- // unpainted
+ // Step forward to leave lowest-tone pixel unpainted
pix++;
- // make the one-pixel-width semi-transparent line to be painted
+ // Allow painting of 1-pixel semi-transparent lines
if (prevailing && pix->getInk() != pix->getPaint()) break;
if (pix->getTone() > oldtone) {
- // check if the current pixel is NOT with the lowest tone among the
- // vertical neighbors as well
+ // Ensure current pixel is not lowest tone among vertical neighbors
if (p.y > 0 && p.y < r->getLy() - 1) {
TPixelCM32 *upPix = pix - r->getWrap();
TPixelCM32 *downPix = pix + r->getWrap();
@@ -245,19 +240,16 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
}
}
}
-
xa = p.x + pix - pix0 + 1;
-
if (saver) saver->save(TRect(xa, p.y, xb, p.y));
if (xb >= xa) {
pix = line + xa;
int n;
TPixelCM32 *lastPix = pix;
for (n = 0; n < xb - xa + 1; n++, lastPix = pix, pix++) {
- /*--- Check if out of range ---*/
+ /*--- Skip if outside fill region ---*/
if (pix->getPaint() != paintAtClickPos && defRegionWithPaint) continue;
-
- /*--- Paint refer lines ---*/
+ /*--- Paint reference lines ---*/
if (lastPix->getInk() != paint && !defRegionWithPaint) {
if (pix->getInk() == TPixelCM32::getMaxInk() &&
lastPix->getInk() != TPixelCM32::getMaxInk() && pix->isPureInk()) {
@@ -273,8 +265,7 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
pix->getInk() == TPixelCM32::getMaxInk() && pix->isPureInk())
continue;
}
-
- /*--- Paint auto-paint lines ---*/
+ /*--- Auto-paint neighboring ink lines ---*/
if (palette && pix->isPurePaint()) {
auto inks = getNeighborInks(r, TPoint(xa + n, p.y));
for (TPoint pInk : inks) {
@@ -288,15 +279,13 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
inkFill(r, pInk, paint, 0, saver);
}
}
-
- /*--- Do the normal paint ---*/
+ /*--- Apply normal paint ---*/
if (pix->getInk() == TPixelCM32::getMaxInk() && !usePrevailingReferFill &&
pix->isPureInk())
continue;
pix->setPaint(paint);
}
-
- // Make sure the Surround ref Ink Pixels can be painted
+ // Ensure surrounding reference ink pixels are painted
if (p.y > 0 && p.y < r->getLy() - 1 && !defRegionWithPaint) {
pix = line + xa;
for (n = 0; n < xb - xa + 1; n++, pix++) {
@@ -316,22 +305,18 @@ void fillRow(const TRasterCM32P &r, const TPoint &p, int &xa, int &xb,
}
}
}
-
//-----------------------------------------------------------------------------
-
void findSegment(const TRaster32P &r, const TPoint &p, int &xa, int &xb,
const TPixel32 &color, const int fillDepth = 254) {
int matte, oldmatte;
TPixel32 *pix, *pix0, *limit, *tmp_limit;
-
- /* vai a destra */
+ /* Expand to the right */
TPixel32 *line = r->pixels(p.y);
-
- pix0 = line + p.x;
- pix = pix0;
- limit = line + r->getBounds().x1;
- oldmatte = pix->m;
- matte = oldmatte;
+ pix0 = line + p.x;
+ pix = pix0;
+ limit = line + r->getBounds().x1;
+ oldmatte = pix->m;
+ matte = oldmatte;
for (; pix <= limit; pix++) {
if (*pix == color) break;
matte = pix->m;
@@ -339,7 +324,7 @@ void findSegment(const TRaster32P &r, const TPoint &p, int &xa, int &xb,
oldmatte = matte;
}
if (matte == 0) {
- tmp_limit = pix + 10; // edge stop fill == 10 per default
+ tmp_limit = pix + 10; // Default edge-stop = 10 pixels
if (limit > tmp_limit) limit = tmp_limit;
for (; pix <= limit; pix++) {
if (*pix == color) break;
@@ -347,8 +332,7 @@ void findSegment(const TRaster32P &r, const TPoint &p, int &xa, int &xb,
}
}
xb = p.x + pix - pix0 - 1;
-
- /* vai a sinistra */
+ /* Expand to the left */
pix = pix0;
limit = line + r->getBounds().x0;
oldmatte = pix->m;
@@ -369,26 +353,21 @@ void findSegment(const TRaster32P &r, const TPoint &p, int &xa, int &xb,
}
xa = p.x + pix - pix0 + 1;
}
-
//-----------------------------------------------------------------------------
-// Used when the clicked pixel is solid or semi-transparent.
-// Check if the fill is stemmed at the target pixel.
-// Note that RGB values are used for checking the difference, not Alpha value.
-
+// Used when clicked pixel is solid or semi-transparent.
+// Checks if fill should stop at target pixel.
+// Compares RGB difference (not alpha).
bool doesStemFill(const TPixel32 &clickColor, const TPixel32 *targetPix,
const int fillDepth2) {
- // stop if the target pixel is transparent
+ // Stop if target is fully transparent
if (targetPix->m == 0) return true;
- // check difference of RGB values is larger than fillDepth
+ // Stop if RGB difference exceeds threshold
int dr = (int)clickColor.r - (int)targetPix->r;
int dg = (int)clickColor.g - (int)targetPix->g;
int db = (int)clickColor.b - (int)targetPix->b;
- return (dr * dr + dg * dg + db * db) >
- fillDepth2; // condition for "stem" the fill
+ return (dr * dr + dg * dg + db * db) > fillDepth2; // Condition to halt fill
}
-
//-----------------------------------------------------------------------------
-
void fullColorFindSegment(const TRaster32P &r, const TPoint &p, int &xa,
int &xb, const TPixel32 &color,
const TPixel32 &clickedPosColor,
@@ -397,52 +376,36 @@ void fullColorFindSegment(const TRaster32P &r, const TPoint &p, int &xa,
findSegment(r, p, xa, xb, color, fillDepth);
return;
}
-
TPixel32 *pix, *pix0, *limit;
- // check to the right
- TPixel32 *line = r->pixels(p.y);
-
- pix0 = line + p.x; // seed pixel
- pix = pix0;
- limit = line + r->getBounds().x1; // right end
-
+ // Check right
+ TPixel32 *line = r->pixels(p.y);
+ pix0 = line + p.x; // Seed pixel
+ pix = pix0;
+ limit = line + r->getBounds().x1; // Right boundary
TPixel32 oldPix = *pix;
-
- int fillDepth2 = fillDepth * fillDepth;
-
+ int fillDepth2 = fillDepth * fillDepth;
for (; pix <= limit; pix++) {
- // break if the target pixel is with the same as filling color
+ // Stop if target matches fill color
if (*pix == color) break;
- // continue if the target pixel is the same as the previous one
+ // Continue if same as previous pixel
if (*pix == oldPix) continue;
-
if (doesStemFill(clickedPosColor, pix, fillDepth2)) break;
-
- // store pixel color in case if the next pixel is with the same color
oldPix = *pix;
}
xb = p.x + pix - pix0 - 1;
-
- // check to the left
- pix = pix0; // seed pixel
- limit = line + r->getBounds().x0; // left end
+ // Check left
+ pix = pix0;
+ limit = line + r->getBounds().x0; // Left boundary
oldPix = *pix;
for (; pix >= limit; pix--) {
- // break if the target pixel is with the same as filling color
if (*pix == color) break;
- // continue if the target pixel is the same as the previous one
if (*pix == oldPix) continue;
-
if (doesStemFill(clickedPosColor, pix, fillDepth2)) break;
-
- // store pixel color in case if the next pixel is with the same color
oldPix = *pix;
}
xa = p.x + pix - pix0 + 1;
}
-
//-----------------------------------------------------------------------------
-
class FillSeed {
public:
int m_xa, m_xb;
@@ -450,9 +413,7 @@ public:
FillSeed(int xa, int xb, int y, int dy)
: m_xa(xa), m_xb(xb), m_y(y), m_dy(dy) {}
};
-
//-----------------------------------------------------------------------------
-
bool isPixelInSegment(const std::vector<std::pair<int, int>> &segments, int x) {
for (int i = 0; i < (int)segments.size(); i++) {
std::pair<int, int> segment = segments[i];
@@ -460,9 +421,7 @@ bool isPixelInSegment(const std::vector<std::pair<int, int>> &segments, int x) {
}
return false;
}
-
//-----------------------------------------------------------------------------
-
void insertSegment(std::vector<std::pair<int, int>> &segments,
const std::pair<int, int> segment) {
for (int i = segments.size() - 1; i >= 0; i--) {
@@ -472,15 +431,12 @@ void insertSegment(std::vector<std::pair<int, int>> &segments,
}
segments.push_back(segment);
}
-
//-----------------------------------------------------------------------------
-
bool floodCheck(const TPixel32 &clickColor, const TPixel32 *targetPix,
const TPixel32 *oldPix, const int fillDepth) {
auto fullColorThreshMatte = [](int matte, int fillDepth) -> int {
return (matte <= fillDepth) ? matte : 255;
};
-
if (clickColor.m == 0) {
int oldMatte = fullColorThreshMatte(oldPix->m, fillDepth);
int matte = fullColorThreshMatte(targetPix->m, fillDepth);
@@ -489,7 +445,6 @@ bool floodCheck(const TPixel32 &clickColor, const TPixel32 *targetPix,
int fillDepth2 = fillDepth * fillDepth;
return !doesStemFill(clickColor, targetPix, fillDepth2);
}
-
bool scanTransparentRegion(TRasterCM32P ras, int x, int y,
std::vector<TPoint> &points, bool *visited,
const int maxSize) {
@@ -497,96 +452,81 @@ bool scanTransparentRegion(TRasterCM32P ras, int x, int y,
int lx = ras->getLx(), ly = ras->getLy();
if (x < 0 || y < 0 || x >= lx || y >= ly) return true;
if (visited[y * lx + x]) return true;
-
TPixelCM32 *pix = ras->pixels(y) + x;
if (pix->getPaint() != 0 || pix->getTone() < 64) return true;
- if (points.size() + 1 > maxSize) return false;
-
+ if (points.size() + 1 > static_cast<size_t>(maxSize)) return false;
visited[y * lx + x] = true;
points.push_back(TPoint(x, y));
-
bool ret = scanTransparentRegion(ras, x + 1, y, points, visited, maxSize) &&
scanTransparentRegion(ras, x - 1, y, points, visited, maxSize) &&
scanTransparentRegion(ras, x, y + 1, points, visited, maxSize) &&
scanTransparentRegion(ras, x, y - 1, points, visited, maxSize);
- ret = ret && points.size() <= maxSize;
+ ret = ret && points.size() <= static_cast<size_t>(maxSize);
return ret;
}
-
int getMostFrequentNeighborStyleId(TRasterCM32P ras,
const std::vector<TPoint> &points,
const bool *visited, bool &fillInk) {
if (!ras) return 0;
-
int lx = ras->getLx();
int ly = ras->getLy();
-
std::map<int, int> styleCount;
- int maxStyleId = 0;
- int maxCount = 0;
-
+ int maxStyleId = 0;
+ int maxCount = 0;
const std::vector<TPoint> diagonal = {TPoint(1, -1), TPoint(1, 1),
TPoint(-1, 1), TPoint(-1, -1)};
-
const std::vector<TPoint> cardinal = {TPoint(0, -1), TPoint(0, 1),
TPoint(-1, 0), TPoint(1, 0)};
-
for (const TPoint &p : points) {
for (const TPoint &d : cardinal) {
int nx = p.x + d.x;
int ny = p.y + d.y;
if (nx < 0 || ny < 0 || nx >= lx || ny >= ly) continue;
if (visited[ny * lx + nx]) continue;
-
TPixelCM32 *pix = ras->pixels(ny) + nx;
-
- int styleId = pix->getInk();
+ int styleId = pix->getInk();
if (styleId)
styleCount[styleId] +=
- pix->getTone() + 1; // cardinal Ink weights tone+1
+ pix->getTone() + 1; // Cardinal ink: weight = tone + 1
styleId = pix->getPaint();
if (styleId) {
styleCount[styleId] +=
- pix->getTone() + 2; // cardinal Paint weights tone+2
+ pix->getTone() + 2; // Cardinal paint: weight = tone + 2
fillInk = false;
}
}
}
-
for (const TPoint &p : points) {
for (const TPoint &d : diagonal) {
int nx = p.x + d.x;
int ny = p.y + d.y;
if (nx < 0 || ny < 0 || nx >= lx || ny >= ly) continue;
if (visited[ny * lx + nx]) continue;
-
TPixelCM32 *pix = ras->pixels(ny) + nx;
if (pix->isPureInk()) continue;
int styleId = pix->getPaint();
if (styleId) {
styleCount[styleId] +=
- pix->getTone() + 3; // Diagonal not pureInk Paint weights tone+3
+ pix->getTone() +
+ 3; // Diagonal non-pureInk paint: weight = tone + 3
fillInk = false;
}
}
}
-
- // Pick most heavy one
+ // Select style with highest weighted count
for (const auto &entry : styleCount) {
if (entry.second > maxCount) {
maxCount = entry.second;
maxStyleId = entry.first;
}
}
-
assert(maxStyleId);
return maxStyleId;
}
-
//-----------------------------------------------------------------------------
} // namespace
//-----------------------------------------------------------------------------
-/*-- Return true if fill processed --*/
+/*-- Returns true if fill was applied --*/
bool fill(const TRasterCM32P &r, const FillParameters &params,
TTileSaverCM32 *saver, const TRaster32P &Ref) {
TPixelCM32 *pix, *limit, *pix0, *oldpix;
@@ -600,17 +540,14 @@ bool fill(const TRasterCM32P &r, const FillParameters &params,
params.m_shiftFill ? params.m_maxFillDepth : params.m_minFillDepth;
bool defRegionWithPaint = params.m_defRegionWithPaint;
bool usePrevailingReferFill = params.m_usePrevailingReferFill;
-
- /*-- getBounds returns the entire image --*/
+ /*-- getBounds returns full image rect --*/
TRect bbbox = r->getBounds();
-
- /*- Return if clicked outside the screen -*/
+ /*- Abort if click is outside image -*/
if (!bbbox.contains(p)) return false;
-
- /*- If the same color has already been painted, return -*/
+ /*- Abort if clicked pixel already has target paint -*/
pix0 = r->pixels(p.y) + p.x;
int paintAtClickedPos = pix0->getPaint();
- if (paintAtClickedPos == paint)
+ if (paintAtClickedPos == paint) {
if (params.m_shiftFill) {
FillParameters tmp = FillParameters(params);
tmp.m_styleId = 0;
@@ -618,33 +555,26 @@ bool fill(const TRasterCM32P &r, const FillParameters &params,
tmp.m_minFillDepth = params.m_maxFillDepth;
fill(r, tmp, saver, Ref);
paintAtClickedPos = pix0->getPaint();
- } else
+ } else {
return false;
-
- /*- If clicked at pure ink pixel, return -*/
+ }
+ }
+ /*- Abort if clicked on pure ink -*/
if (pix0->isPureInk()) return false;
if (Ref.getPointer() != nullptr && Ref->pixels(y)[x].m == 255) return false;
-
- /*- If the "paint only transparent areas" option is enabled and the area is
- * already colored, return
- * -*/
+ /*- Abort if "empty only" is on and area is already painted -*/
if (params.m_emptyOnly && pix0->getPaint() != 0 && !params.m_shiftFill)
return false;
-
- // Put reference image, will be automatically removed by RAII
- /* To Save Undo Memory, saved refer pixel would be cleared */
+ // RAII guard to manage reference image
+ /* To save undo memory, saved reference pixels are cleared */
RefImageGuard refGuard(r, Ref);
-
fillDepth = adjustFillDepth(fillDepth);
-
std::stack<FillSeed> seeds;
-
- // Also do fillInk for autoPaint style Ink
+ // Fill initial row and seed stack
fillRow(r, p, xa, xb, paint, params.m_palette, saver, params.m_prevailing,
paintAtClickedPos, defRegionWithPaint, usePrevailingReferFill);
seeds.push(FillSeed(xa, xb, y, 1));
seeds.push(FillSeed(xa, xb, y, -1));
-
int lasty = y;
int wrap = r->getWrap();
TPixelCM32 *line = r->pixels(y);
@@ -668,8 +598,7 @@ bool fill(const TRasterCM32P &r, const FillParameters &params,
while (pix <= limit) {
oldtone = threshTone(*oldpix, fillDepth);
tone = threshTone(*pix, fillDepth);
- // the last condition is added in order to prevent fill area from
- // protruding behind the colored line
+ // Additional condition prevents fill from bleeding behind colored lines
int pixPaint = pix->getPaint();
if (pixPaint != paint && tone <= oldtone && tone != 0 &&
(pixPaint == paintAtClickedPos || !defRegionWithPaint) &&
@@ -679,10 +608,12 @@ bool fill(const TRasterCM32P &r, const FillParameters &params,
usePrevailingReferFill);
if (xc < xa) seeds.push(FillSeed(xc, xa - 1, y, -dy));
if (xd > xb) seeds.push(FillSeed(xb + 1, xd, y, -dy));
- if (oldxd >= xc - 1)
+ if (oldxd >= xc - 1) {
oldxd = xd;
- else {
- if (oldxd >= 0) seeds.push(FillSeed(oldxc, oldxd, y, dy));
+ } else {
+ if (oldxd >= 0) {
+ seeds.push(FillSeed(oldxc, oldxd, y, dy));
+ }
oldxc = xc;
oldxd = xd;
}
@@ -696,12 +627,9 @@ bool fill(const TRasterCM32P &r, const FillParameters &params,
}
if (oldxd > 0) seeds.push(FillSeed(oldxc, oldxd, y, dy));
}
-
return true;
}
-
//-----------------------------------------------------------------------------
-
void fill(const TRaster32P &ras, const TRaster32P &ref,
const FillParameters &params, TTileSaverFullColor *saver) {
TPixel32 *pix, *limit, *pix0, *oldpix;
@@ -710,57 +638,44 @@ void fill(const TRaster32P &ras, const TRaster32P &ref,
int matte, oldMatte;
int x = params.m_p.x, y = params.m_p.y;
TRaster32P workRas = ref ? ref : ras;
-
- TRect bbbox = workRas->getBounds();
-
+ TRect bbbox = workRas->getBounds();
if (!bbbox.contains(params.m_p)) return;
-
TPaletteP plt = params.m_palette;
TPixel32 color = plt->getStyle(params.m_styleId)->getMainColor();
int fillDepth =
params.m_shiftFill ? params.m_maxFillDepth : params.m_minFillDepth;
-
assert(fillDepth >= 0 && fillDepth < 16);
fillDepth = ((15 - fillDepth) << 4) | (15 - fillDepth);
-
- // looking for any pure transparent pixel along the border; if after filling
- // that pixel will be changed,
- // it means that I filled the bg and the savebox needs to be recomputed!
+ // Detect border transparency to determine if savebox needs recompute
TPixel32 borderIndex;
TPixel32 *borderPix = 0;
pix = workRas->pixels(0);
int i;
- for (i = 0; i < workRas->getLx(); i++, pix++) // border down
+ for (i = 0; i < workRas->getLx(); i++, pix++) // Bottom border
if (pix->m == 0) {
borderIndex = *pix;
borderPix = pix;
break;
}
- if (borderPix == 0) // not found in border down...try border up (avoid left
- // and right borders...so unlikely)
+ if (borderPix == 0) // Try top border if not found
{
pix = workRas->pixels(workRas->getLy() - 1);
- for (i = 0; i < workRas->getLx(); i++, pix++) // border up
+ for (i = 0; i < workRas->getLx(); i++, pix++) // Top border
if (pix->m == 0) {
borderIndex = *pix;
borderPix = pix;
break;
}
}
-
std::stack<FillSeed> seeds;
std::map<int, std::vector<std::pair<int, int>>> segments;
-
- // fillRow(r, params.m_p, xa, xb, color ,saver);
findSegment(workRas, params.m_p, xa, xb, color);
segments[y].push_back(std::pair<int, int>(xa, xb));
seeds.push(FillSeed(xa, xb, y, 1));
seeds.push(FillSeed(xa, xb, y, -1));
-
while (!seeds.empty()) {
FillSeed fs = seeds.top();
seeds.pop();
-
xa = fs.m_xa;
xb = fs.m_xb;
oldy = fs.m_y;
@@ -781,7 +696,6 @@ void fill(const TRaster32P &ras, const TRaster32P &ref,
test = isPixelInSegment(segments[y], x);
if (*pix != color && !test && matte >= oldMatte && matte != 255) {
findSegment(workRas, TPoint(x, y), xc, xd, color);
- // segments[y].push_back(std::pair<int,int>(xc, xd));
insertSegment(segments[y], std::pair<int, int>(xc, xd));
if (xc < xa) seeds.push(FillSeed(xc, xa - 1, y, -dy));
if (xd > xb) seeds.push(FillSeed(xb + 1, xd, y, -dy));
@@ -802,7 +716,6 @@ void fill(const TRaster32P &ras, const TRaster32P &ref,
}
if (oldxd > 0) seeds.push(FillSeed(oldxc, oldxd, y, dy));
}
-
std::map<int, std::vector<std::pair<int, int>>>::iterator it;
for (it = segments.begin(); it != segments.end(); it++) {
TPixel32 *line = ras->pixels(it->first);
@@ -827,66 +740,49 @@ void fill(const TRaster32P &ras, const TRaster32P &ref,
}
}
}
-
//-----------------------------------------------------------------------------
-
static void rectFill(const TRaster32P &ras, const TRect &r,
const TPixel32 &color) {}
-
//-----------------------------------------------------------------------------
-
static TPoint nearestInk(const TRasterCM32P &r, const TPoint &p, int ray) {
int i, j;
TPixelCM32 *buf = (TPixelCM32 *)r->getRawData();
-
for (j = std::max(p.y - ray, 0); j <= std::min(p.y + ray, r->getLy() - 1);
j++)
for (i = std::max(p.x - ray, 0); i <= std::min(p.x + ray, r->getLx() - 1);
i++)
if (!(buf + j * r->getWrap() + i)->isPurePaint()) return TPoint(i, j);
-
return TPoint(-1, -1);
}
-
//-----------------------------------------------------------------------------
-
void inkFill(const TRasterCM32P &r, const TPoint &pin, int ink, int searchRay,
TTileSaverCM32 *saver, TRect *insideRect) {
r->lock();
TPixelCM32 *pixels = (TPixelCM32 *)r->getRawData();
int oldInk;
TPoint p = pin;
-
if ((pixels + p.y * r->getWrap() + p.x)->isPurePaint() &&
(searchRay == 0 || (p = nearestInk(r, p, searchRay)) == TPoint(-1, -1))) {
r->unlock();
return;
}
TPixelCM32 *pix = pixels + (p.y * r->getWrap() + p.x);
-
if (pix->getInk() == ink) {
r->unlock();
return;
}
-
oldInk = pix->getInk();
-
std::stack<TPoint> seeds;
seeds.push(p);
-
while (!seeds.empty()) {
p = seeds.top();
seeds.pop();
if (!r->getBounds().contains(p)) continue;
if (insideRect && !insideRect->contains(p)) continue;
-
TPixelCM32 *pix = pixels + (p.y * r->getWrap() + p.x);
if (pix->isPurePaint() || pix->getInk() != oldInk) continue;
-
if (saver) saver->save(p);
-
pix->setInk(ink);
-
seeds.push(TPoint(p.x - 1, p.y - 1));
seeds.push(TPoint(p.x - 1, p.y));
seeds.push(TPoint(p.x - 1, p.y + 1));
@@ -898,81 +794,64 @@ void inkFill(const TRasterCM32P &r, const TPoint &pin, int ink, int searchRay,
}
r->unlock();
}
-
//-----------------------------------------------------------------------------
-
void fullColorFill(const TRaster32P &ras, const FillParameters &params,
TTileSaverFullColor *saver) {
int oldy, xa, xb, xc, xd, dy, oldxd, oldxc;
TPixel32 *pix, *limit, *pix0, *oldpix;
int x = params.m_p.x, y = params.m_p.y;
-
TRect bbbox = ras->getBounds();
if (!bbbox.contains(params.m_p)) return;
-
TPixel32 clickedPosColor = *(ras->pixels(y) + x);
-
- TPaletteP plt = params.m_palette;
- TPixel32 color = plt->getStyle(params.m_styleId)->getMainColor();
-
+ TPaletteP plt = params.m_palette;
+ TPixel32 color = plt->getStyle(params.m_styleId)->getMainColor();
if (clickedPosColor == color) return;
-
int fillDepth =
params.m_shiftFill ? params.m_maxFillDepth : params.m_minFillDepth;
-
assert(fillDepth >= 0 && fillDepth < 16);
TPointD m_firstPoint, m_clickPoint;
-
- // convert fillDepth range from [0 - 15] to [0 - 255]
+ // Convert fillDepth from [0-15] to [0-255]
fillDepth = (fillDepth << 4) | fillDepth;
-
std::stack<FillSeed> seeds;
std::map<int, std::vector<std::pair<int, int>>> segments;
-
fullColorFindSegment(ras, params.m_p, xa, xb, color, clickedPosColor,
fillDepth);
-
segments[y].push_back(std::pair<int, int>(xa, xb));
seeds.push(FillSeed(xa, xb, y, 1));
seeds.push(FillSeed(xa, xb, y, -1));
-
while (!seeds.empty()) {
FillSeed fs = seeds.top();
seeds.pop();
-
xa = fs.m_xa;
xb = fs.m_xb;
oldy = fs.m_y;
dy = fs.m_dy;
y = oldy + dy;
- // continue if the fill runs over image bounding
+ // Skip if fill exceeds image bounds
if (y > bbbox.y1 || y < bbbox.y0) continue;
- // left end of the pixels to be filled
+ // Left boundary of fill area
pix = pix0 = ras->pixels(y) + xa;
- // right end of the pixels to be filled
+ // Right boundary of fill area
limit = ras->pixels(y) + xb;
- // left end of the fill seed pixels
+ // Left boundary of seed row
oldpix = ras->pixels(oldy) + xa;
-
- x = xa;
- oldxd = (std::numeric_limits<int>::min)();
- oldxc = (std::numeric_limits<int>::max)();
-
- // check pixels to right
+ x = xa;
+ oldxd = (std::numeric_limits<int>::min)();
+ oldxc = (std::numeric_limits<int>::max)();
+ // Process pixels to the right
while (pix <= limit) {
bool test = false;
- // check if the target is already in the range to be filled
+ // Check if already scheduled for fill
if (segments.find(y) != segments.end())
test = isPixelInSegment(segments[y], x);
-
if (*pix != color && !test &&
floodCheck(clickedPosColor, pix, oldpix, fillDepth)) {
- // compute horizontal range to be filled
+ // Compute horizontal fill range
fullColorFindSegment(ras, TPoint(x, y), xc, xd, color, clickedPosColor,
fillDepth);
- // insert segment to be filled
+ // Record fill segment
insertSegment(segments[y], std::pair<int, int>(xc, xd));
- // create new fillSeed to invert direction, if needed
+ // Seed opposite direction if needed
if (xc < xa) seeds.push(FillSeed(xc, xa - 1, y, -dy));
if (xd > xb) seeds.push(FillSeed(xb + 1, xd, y, -dy));
if (oldxd >= xc - 1)
@@ -982,7 +861,7 @@ void fullColorFill(const TRaster32P &ras, const FillParameters &params,
oldxc = xc;
oldxd = xd;
}
- // jump to the next pixel to the right end of the range
+ // Jump to right edge of new segment
pix += xd - x + 1;
oldpix += xd - x + 1;
x += xd - x + 1;
@@ -991,13 +870,11 @@ void fullColorFill(const TRaster32P &ras, const FillParameters &params,
oldpix++, x++;
}
}
- // insert filled range as new fill seed
+ // Add pending segment as new seed
if (oldxd > 0) seeds.push(FillSeed(oldxc, oldxd, y, dy));
}
-
- // pixels are actually filled here
+ // Apply actual pixel painting
TPixel32 premultiColor = premultiply(color);
-
std::map<int, std::vector<std::pair<int, int>>>::iterator it;
for (it = segments.begin(); it != segments.end(); it++) {
TPixel32 *line = ras->pixels(it->first);
@@ -1015,7 +892,7 @@ void fullColorFill(const TRaster32P &ras, const FillParameters &params,
for (n = 0; n < segment.second - segment.first + 1; n++, pix++) {
if (clickedPosColor.m == 0)
*pix = pix->m == 0 ? color : overPix(color, *pix);
- else if (color.m == 0 || color.m == 255) // used for erasing area
+ else if (color.m == 0 || color.m == 255) // Erase mode
*pix = color;
else
*pix = overPix(*pix, premultiColor);
@@ -1024,18 +901,15 @@ void fullColorFill(const TRaster32P &ras, const FillParameters &params,
}
}
}
-
void fillHoles(const TRasterCM32P &ras, const int maxSize,
TTileSaverCM32 *saver) {
int lx = ras->getLx();
int ly = ras->getLy();
bool *visited = new bool[lx * ly]{false};
-
- auto isEmpty = [&](int x, int y) -> bool {
+ auto isEmpty = [&](int x, int y) -> bool {
TPixelCM32 *pix = ras->pixels(y) + x;
return !pix->getPaint() && pix->getTone() > 64 && !visited[y * lx + x];
};
-
for (int y = 0; y < ly; y++) {
int emptyCount = 0;
for (int x = 0; x < lx; x++) {
@@ -1065,6 +939,5 @@ void fillHoles(const TRasterCM32P &ras, const int maxSize,
emptyCount = 0;
}
}
-
delete[] visited;
}