forked from aseprite/aseprite
-
Notifications
You must be signed in to change notification settings - Fork 2
/
editor.cpp
3062 lines (2604 loc) · 89.5 KB
/
editor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Aseprite
// Copyright (C) 2018-2024 Igara Studio S.A.
// Copyright (C) 2001-2018 David Capello
//
// This program is distributed under the terms of
// the End-User License Agreement for Aseprite.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "app/ui/editor/editor.h"
#include "app/app.h"
#include "app/app_menus.h"
#include "app/color.h"
#include "app/color_picker.h"
#include "app/color_utils.h"
#include "app/commands/commands.h"
#include "app/commands/params.h"
#include "app/commands/quick_command.h"
#include "app/console.h"
#include "app/doc_event.h"
#include "app/i18n/strings.h"
#include "app/ini_file.h"
#include "app/modules/gfx.h"
#include "app/modules/gui.h"
#include "app/modules/palettes.h"
#include "app/pref/preferences.h"
#include "app/snap_to_grid.h"
#include "app/tools/active_tool.h"
#include "app/tools/controller.h"
#include "app/tools/ink.h"
#include "app/tools/tool.h"
#include "app/tools/tool_box.h"
#include "app/ui/color_bar.h"
#include "app/ui/context_bar.h"
#include "app/ui/doc_view.h"
#include "app/ui/editor/drawing_state.h"
#include "app/ui/editor/editor_customization_delegate.h"
#include "app/ui/editor/editor_decorator.h"
#include "app/ui/editor/editor_render.h"
#include "app/ui/editor/glue.h"
#include "app/ui/editor/moving_pixels_state.h"
#include "app/ui/editor/pixels_movement.h"
#include "app/ui/editor/play_state.h"
#include "app/ui/editor/scrolling_state.h"
#include "app/ui/editor/standby_state.h"
#include "app/ui/editor/zooming_state.h"
#include "app/ui/main_window.h"
#include "app/ui/skin/skin_theme.h"
#include "app/ui/status_bar.h"
#include "app/ui/timeline/timeline.h"
#include "app/ui/toolbar.h"
#include "app/ui_context.h"
#include "app/util/layer_utils.h"
#include "app/util/tile_flags_utils.h"
#include "base/chrono.h"
#include "base/convert_to.h"
#include "doc/doc.h"
#include "doc/mask_boundaries.h"
#include "doc/slice.h"
#include "fmt/format.h"
#include "os/color_space.h"
#include "os/sampling.h"
#include "os/surface.h"
#include "os/system.h"
#include "render/rasterize.h"
#include "ui/ui.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <limits>
#include <memory>
namespace app {
using namespace app::skin;
using namespace gfx;
using namespace ui;
using namespace render;
// TODO these should be grouped in some kind of "performance counters"
static base::Chrono renderChrono;
static double renderElapsed = 0.0;
class EditorPostRenderImpl : public EditorPostRender {
public:
EditorPostRenderImpl(Editor* editor, Graphics* g)
: m_editor(editor)
, m_g(g) {
}
Editor* getEditor() override {
return m_editor;
}
Graphics* getGraphics() override {
return m_g;
}
void drawLine(gfx::Color color, int x1, int y1, int x2, int y2) override {
gfx::Point a(x1, y1);
gfx::Point b(x2, y2);
a = m_editor->editorToScreen(a);
b = m_editor->editorToScreen(b);
gfx::Rect bounds = m_editor->bounds();
a.x -= bounds.x;
a.y -= bounds.y;
b.x -= bounds.x;
b.y -= bounds.y;
m_g->drawLine(color, a, b);
}
void drawRect(gfx::Color color, const gfx::Rect& rc) override {
gfx::Rect rc2 = m_editor->editorToScreen(rc);
gfx::Rect bounds = m_editor->bounds();
rc2.x -= bounds.x;
rc2.y -= bounds.y;
m_g->drawRect(color, rc2);
}
void fillRect(gfx::Color color, const gfx::Rect& rc) override {
gfx::Rect rc2 = m_editor->editorToScreen(rc);
gfx::Rect bounds = m_editor->bounds();
rc2.x -= bounds.x;
rc2.y -= bounds.y;
m_g->fillRect(color, rc2);
}
private:
Editor* m_editor;
Graphics* m_g;
};
// static
Editor* Editor::m_activeEditor = nullptr;
// static
std::unique_ptr<EditorRender> Editor::m_renderEngine = nullptr;
Editor::Editor(Doc* document, EditorFlags flags, EditorStatePtr state)
: Widget(Editor::Type())
, m_state(state == nullptr ? std::make_shared<StandbyState>(): state)
, m_decorator(NULL)
, m_document(document)
, m_sprite(m_document->sprite())
, m_layer(m_sprite->root()->firstLayer())
, m_frame(frame_t(0))
, m_docPref(Preferences::instance().document(document))
, m_tiledModeHelper(app::TiledModeHelper(m_docPref.tiled.mode(), m_sprite))
, m_brushPreview(this)
, m_toolLoopModifiers(tools::ToolLoopModifiers::kNone)
, m_padding(0, 0)
, m_antsTimer(100, this)
, m_antsOffset(0)
, m_customizationDelegate(NULL)
, m_docView(NULL)
, m_flags(flags)
, m_secondaryButton(false)
, m_flashing(Flashing::None)
, m_aniSpeed(1.0)
, m_isPlaying(false)
, m_showGuidesThisCel(nullptr)
, m_showAutoCelGuides(false)
, m_tagFocusBand(-1)
{
if (!m_renderEngine)
m_renderEngine = std::make_unique<EditorRender>();
m_proj.setPixelRatio(m_sprite->pixelRatio());
// Add the first state into the history.
m_statesHistory.push(m_state);
this->setFocusStop(true);
App::instance()->activeToolManager()->add_observer(this);
m_fgColorChangeConn =
Preferences::instance().colorBar.fgColor.AfterChange.connect(
[this]{ onFgColorChange(); });
m_samplingChangeConn =
Preferences::instance().editor.downsampling.AfterChange.connect(
[this]{ onSamplingChange(); });
m_contextBarBrushChangeConn =
App::instance()->contextBar()->BrushChange.connect(
[this]{ onContextBarBrushChange(); });
// Restore last site in preferences
{
frame_t preferredFrame = m_docPref.site.frame();
if (preferredFrame >= 0 && preferredFrame <= m_sprite->lastFrame())
setFrame(preferredFrame);
LayerList layers = m_sprite->allBrowsableLayers();
layer_t layerIndex = m_docPref.site.layer();
if (layerIndex >= 0 && layerIndex < int(layers.size()))
setLayer(layers[layerIndex]);
}
m_tiledConnBefore = m_docPref.tiled.BeforeChange.connect([this]{ onTiledModeBeforeChange(); });
m_tiledConn = m_docPref.tiled.AfterChange.connect([this]{ onTiledModeChange(); });
m_gridConn = m_docPref.grid.AfterChange.connect([this]{ invalidate(); });
m_pixelGridConn = m_docPref.pixelGrid.AfterChange.connect([this]{ invalidate(); });
m_bgConn = m_docPref.bg.AfterChange.connect([this]{ invalidate(); });
m_onionskinConn = m_docPref.onionskin.AfterChange.connect([this]{ invalidate(); });
m_symmetryModeConn = Preferences::instance().symmetryMode.enabled.AfterChange.connect([this]{ invalidateIfActive(); });
m_showExtrasConn =
m_docPref.show.AfterChange.connect(
[this]{ onShowExtrasChange(); });
m_document->add_observer(this);
m_state->onEnterState(this);
}
Editor::~Editor()
{
if (m_document && m_sprite) {
LayerList layers = m_sprite->allBrowsableLayers();
layer_t layerIndex = doc::find_layer_index(layers, layer());
m_docPref.site.frame(frame());
m_docPref.site.layer(layerIndex);
}
m_observers.notifyDestroyEditor(this);
m_document->remove_observer(this);
App::instance()->activeToolManager()->remove_observer(this);
setCustomizationDelegate(NULL);
m_antsTimer.stop();
}
void Editor::destroyEditorSharedInternals()
{
BrushPreview::destroyInternals();
if (m_renderEngine)
m_renderEngine.reset();
}
bool Editor::isUsingNewRenderEngine() const
{
ASSERT(m_sprite);
return
// TODO add an option to the ShaderRenderer to work as the "old"
// engine (screen pixel by screen pixel) or as the "new"
// engine (sprite pixel by sprite pixel)
(m_renderEngine->type() == EditorRender::Type::kShaderRenderer)
||
(Preferences::instance().experimental.newRenderEngine()
// Reference layers + zoom > 100% need the old render engine for
// sub-pixel rendering.
&& (!m_sprite->hasVisibleReferenceLayers()
|| (m_proj.scaleX() <= 1.0
&& m_proj.scaleY() <= 1.0)));
}
// static
WidgetType Editor::Type()
{
static WidgetType type = kGenericWidget;
if (type == kGenericWidget)
type = register_widget_type();
return type;
}
void Editor::setStateInternal(const EditorStatePtr& newState)
{
m_brushPreview.hide();
// Fire before change state event, set the state, and fire after
// change state event.
EditorState::LeaveAction leaveAction =
m_state->onLeaveState(this, newState.get());
// Push a new state
if (newState) {
if (leaveAction == EditorState::DiscardState)
m_statesHistory.pop();
m_statesHistory.push(newState);
m_state = newState;
}
// Go to previous state
else {
m_state->onBeforePopState(this);
// Save the current state into "m_deletedStates" just to keep a
// reference to it to avoid delete it right now. We'll delete it
// in the next Editor::onProcessMessage().
//
// This is necessary for PlayState because it removes itself
// calling Editor::stop() from PlayState::onPlaybackTick(). If we
// delete the PlayState inside the "Tick" timer signal, the
// program will crash (because we're iterating the
// PlayState::m_playTimer slots).
m_deletedStates.push(m_state);
m_statesHistory.pop();
m_state = m_statesHistory.top();
}
ASSERT(m_state);
// Change to the new state.
m_state->onEnterState(this);
// Notify observers
m_observers.notifyStateChanged(this);
// Redraw layer edges
if (m_docPref.show.layerEdges())
invalidate();
// Setup the new mouse cursor
setCursor(mousePosInDisplay());
updateStatusBar();
}
void Editor::setState(const EditorStatePtr& newState)
{
setStateInternal(newState);
}
void Editor::backToPreviousState()
{
setStateInternal(EditorStatePtr(NULL));
}
void Editor::getInvalidDecoratoredRegion(gfx::Region& region)
{
// Remove decorated region that cannot be just moved because it
// must be redrawn in another position when the Editor's scroll
// changes (e.g. symmetry handles).
if ((m_flags & kShowDecorators) && m_decorator)
m_decorator->getInvalidDecoratoredRegion(this, region);
#if ENABLE_DEVMODE
// TODO put this in other widget
if (Preferences::instance().perf.showRenderTime()) {
if (!m_perfInfoBounds.isEmpty())
region |= gfx::Region(m_perfInfoBounds);
}
#endif // ENABLE_DEVMODE
}
void Editor::setLayer(const Layer* layer)
{
const bool changed = (m_layer != layer);
const bool gridVisible = (changed && m_docPref.show.grid());
doc::Grid oldGrid, newGrid;
if (gridVisible)
oldGrid = getSite().grid();
m_observers.notifyBeforeLayerChanged(this);
// Remove extra cel information if we change between different layer
// type (e.g. from a tilemap layer to an image layer). This is
// useful to avoid a flickering effect in the preview window (using
// a non-updated extra cel to patch the new "layer" with the
// background of the previous selected "m_layer".
if ((layer == nullptr) ||
(m_layer != nullptr && m_layer->type() != layer->type())) {
m_document->setExtraCel(ExtraCelRef(nullptr));
}
m_layer = const_cast<Layer*>(layer);
m_observers.notifyAfterLayerChanged(this);
if (gridVisible)
newGrid = getSite().grid();
if (m_document && changed) {
if (// If the onion skinning depends on the active layer
m_docPref.onionskin.currentLayer() ||
// If the user want to see the active layer edges...
m_docPref.show.layerEdges() ||
// If there is a different opacity for nonactive-layers
otherLayersOpacity() < 255 ||
// If the automatic cel guides are visible...
m_showGuidesThisCel ||
// If grid settings changed
(gridVisible &&
(oldGrid.tileSize() != newGrid.tileSize() ||
oldGrid.origin() != newGrid.origin()))) {
// We've to redraw the whole editor
invalidate();
}
}
// The active layer has changed.
if (isActive())
UIContext::instance()->notifyActiveSiteChanged();
updateStatusBar();
}
void Editor::setFrame(frame_t frame)
{
if (m_frame == frame)
return;
m_observers.notifyBeforeFrameChanged(this);
{
HideBrushPreview hide(m_brushPreview);
m_frame = frame;
}
m_observers.notifyAfterFrameChanged(this);
// The active frame has changed.
if (isActive())
UIContext::instance()->notifyActiveSiteChanged();
// Invalidate canvas area
invalidateCanvas();
updateStatusBar();
}
void Editor::getSite(Site* site) const
{
site->document(m_document);
site->sprite(m_sprite);
site->layer(m_layer);
site->frame(m_frame);
if (!m_selectedSlices.empty() &&
getCurrentEditorInk()->isSlice()) {
site->selectedSlices(m_selectedSlices);
}
// TODO we should not access timeline directly here
Timeline* timeline = App::instance()->timeline();
if (timeline &&
timeline->isVisible() &&
timeline->range().enabled()) {
site->range(timeline->range());
}
if (m_layer && m_layer->isTilemap()) {
TilemapMode tilemapMode = site->tilemapMode();
TilesetMode tilesetMode = site->tilesetMode();
const ColorBar* colorbar = ColorBar::instance();
ASSERT(colorbar);
if (colorbar) {
tilemapMode = colorbar->tilemapMode();
tilesetMode = colorbar->tilesetMode();
}
site->tilemapMode(tilemapMode);
site->tilesetMode(tilesetMode);
}
}
Site Editor::getSite() const
{
Site site;
getSite(&site);
return site;
}
void Editor::setZoom(const render::Zoom& zoom)
{
if (m_proj.zoom() != zoom) {
m_proj.setZoom(zoom);
notifyZoomChanged();
if (isActive())
App::instance()->contextBar()->updateSamplingVisibility();
}
else {
// Just copy the zoom as the internal "Zoom::m_internalScale"
// value might be different and we want to keep this value updated
// for better zooming experience in StateWithWheelBehavior.
m_proj.setZoom(zoom);
}
}
void Editor::setDefaultScroll()
{
if (Preferences::instance().editor.autoFit())
setScrollAndZoomToFitScreen();
else
setScrollToCenter();
}
void Editor::setScrollToCenter()
{
View* view = View::getView(this);
Rect vp = view->viewportBounds();
gfx::Size canvas = canvasSize();
setEditorScroll(
gfx::Point(
m_padding.x - vp.w/2 + m_proj.applyX(canvas.w)/2,
m_padding.y - vp.h/2 + m_proj.applyY(canvas.h)/2));
}
void Editor::setScrollAndZoomToFitScreen()
{
View* view = View::getView(this);
gfx::Rect vp = view->viewportBounds();
gfx::Size canvas = canvasSize();
Zoom zoom = m_proj.zoom();
if (float(vp.w) / float(canvas.w) <
float(vp.h) / float(canvas.h)) {
if (vp.w < m_proj.applyX(canvas.w)) {
while (vp.w < m_proj.applyX(canvas.w)) {
if (!zoom.out())
break;
m_proj.setZoom(zoom);
}
}
else if (vp.w > m_proj.applyX(canvas.w)) {
bool out = true;
while (vp.w > m_proj.applyX(canvas.w)) {
if (!zoom.in()) {
out = false;
break;
}
m_proj.setZoom(zoom);
}
if (out) {
zoom.out();
m_proj.setZoom(zoom);
}
}
}
else {
if (vp.h < m_proj.applyY(canvas.h)) {
while (vp.h < m_proj.applyY(canvas.h)) {
if (!zoom.out())
break;
m_proj.setZoom(zoom);
}
}
else if (vp.h > m_proj.applyY(canvas.h)) {
bool out = true;
while (vp.h > m_proj.applyY(canvas.h)) {
if (!zoom.in()) {
out = false;
break;
}
m_proj.setZoom(zoom);
}
if (out) {
zoom.out();
m_proj.setZoom(zoom);
}
}
}
updateEditor(false);
setEditorScroll(
gfx::Point(
m_padding.x - vp.w/2 + m_proj.applyX(canvas.w)/2,
m_padding.y - vp.h/2 + m_proj.applyY(canvas.h)/2));
}
// Sets the scroll position of the editor
void Editor::setEditorScroll(const gfx::Point& scroll)
{
View::getView(this)->setViewScroll(scroll);
}
void Editor::setEditorZoom(const render::Zoom& zoom)
{
setZoomAndCenterInMouse(
zoom, mousePosInDisplay(),
Editor::ZoomBehavior::CENTER);
}
void Editor::updateEditor(const bool restoreScrollPos)
{
View::getView(this)->updateView(restoreScrollPos);
}
void Editor::drawOneSpriteUnclippedRect(ui::Graphics* g, const gfx::Rect& spriteRectToDraw, int dx, int dy)
{
// Clip from sprite and apply zoom
gfx::Rect rc = m_sprite->bounds().createIntersection(spriteRectToDraw);
rc = m_proj.apply(rc);
gfx::Rect dest(dx + m_padding.x + rc.x,
dy + m_padding.y + rc.y, 0, 0);
// Clip from graphics/screen
const gfx::Rect& clip = g->getClipBounds();
if (dest.x < clip.x) {
rc.x += clip.x - dest.x;
rc.w -= clip.x - dest.x;
dest.x = clip.x;
}
if (dest.y < clip.y) {
rc.y += clip.y - dest.y;
rc.h -= clip.y - dest.y;
dest.y = clip.y;
}
if (dest.x+rc.w > clip.x+clip.w) {
rc.w = clip.x+clip.w-dest.x;
}
if (dest.y+rc.h > clip.y+clip.h) {
rc.h = clip.y+clip.h-dest.y;
}
if (rc.isEmpty())
return;
// Bounds of pixels from the sprite canvas that will be exposed in
// this render cycle.
gfx::Rect expose = m_proj.remove(rc);
// If the zoom level is less than 100%, we add extra pixels to
// the exposed area. Those pixels could be shown in the
// rendering process depending on each cel position.
// E.g. when we are drawing in a cel with position < (0,0)
if (m_proj.scaleX() < 1.0)
expose.enlargeXW(int(1./m_proj.scaleX()));
// If the zoom level is more than %100 we add an extra pixel to
// expose just in case the zoom requires to display it. Note:
// this is really necessary to avoid showing invalid destination
// areas in ToolLoopImpl.
else if (m_proj.scaleX() > 1.0)
expose.enlargeXW(1);
if (m_proj.scaleY() < 1.0)
expose.enlargeYH(int(1./m_proj.scaleY()));
else if (m_proj.scaleY() > 1.0)
expose.enlargeYH(1);
expose &= m_sprite->bounds();
const int maxw = std::max(0, m_sprite->width()-expose.x);
const int maxh = std::max(0, m_sprite->height()-expose.y);
expose.w = std::clamp(expose.w, 0, maxw);
expose.h = std::clamp(expose.h, 0, maxh);
if (expose.isEmpty())
return;
// rc2 is the rectangle used to create a temporal rendered image of the sprite
const auto& pref = Preferences::instance();
const bool newEngine = isUsingNewRenderEngine();
gfx::Rect rc2;
if (newEngine) {
rc2 = expose; // New engine, exposed rectangle (without zoom)
dest.x = dx + m_padding.x + m_proj.applyX(rc2.x);
dest.y = dy + m_padding.y + m_proj.applyY(rc2.y);
dest.w = m_proj.applyX(rc2.w);
dest.h = m_proj.applyY(rc2.h);
}
else {
rc2 = rc; // Old engine, same rectangle with zoom
dest.w = rc.w;
dest.h = rc.h;
}
// Convert the render to a os::Surface
static os::SurfaceRef rendered = nullptr; // TODO move this to other centralized place
const auto& renderProperties = m_renderEngine->properties();
try {
// Generate a "expose sprite pixels" notification. This is used by
// tool managers that need to validate this region (copy pixels from
// the original cel) before it can be used by the RenderEngine.
m_document->notifyExposeSpritePixels(m_sprite, gfx::Region(expose));
m_renderEngine->setNewBlendMethod(pref.experimental.newBlend());
m_renderEngine->setRefLayersVisiblity(true);
m_renderEngine->setSelectedLayer(m_layer);
m_renderEngine->setNonactiveLayersOpacity(otherLayersOpacity());
m_renderEngine->setupBackground(m_document, IMAGE_RGB);
m_renderEngine->disableOnionskin();
if ((m_flags & kShowOnionskin) == kShowOnionskin) {
if (m_docPref.onionskin.active()) {
OnionskinOptions opts(
(m_docPref.onionskin.type() == app::gen::OnionskinType::MERGE ?
render::OnionskinType::MERGE:
(m_docPref.onionskin.type() == app::gen::OnionskinType::RED_BLUE_TINT ?
render::OnionskinType::RED_BLUE_TINT:
render::OnionskinType::NONE)));
opts.position(m_docPref.onionskin.position());
opts.prevFrames(m_docPref.onionskin.prevFrames());
opts.nextFrames(m_docPref.onionskin.nextFrames());
opts.opacityBase(m_docPref.onionskin.opacityBase());
opts.opacityStep(m_docPref.onionskin.opacityStep());
opts.layer(m_docPref.onionskin.currentLayer() ? m_layer: nullptr);
Tag* tag = nullptr;
if (m_docPref.onionskin.loopTag())
tag = m_sprite->tags().innerTag(m_frame);
opts.loopTag(tag);
m_renderEngine->setOnionskin(opts);
}
}
ExtraCelRef extraCel = m_document->extraCel();
if (extraCel &&
extraCel->type() != render::ExtraType::NONE) {
m_renderEngine->setExtraImage(
extraCel->type(),
extraCel->cel(),
extraCel->image(),
extraCel->blendMode(),
m_layer, m_frame);
}
// Render background first (e.g. new ShaderRenderer will paint the
// background on the screen first and then composite the rendered
// sprite on it.)
if (renderProperties.renderBgOnScreen) {
m_renderEngine->setProjection(m_proj);
m_renderEngine->renderCheckeredBackground(
g->getInternalSurface(),
m_sprite,
gfx::Clip(dest.x + g->getInternalDeltaX(),
dest.y + g->getInternalDeltaY(),
m_proj.apply(rc2)));
}
// Create a temporary surface to draw the sprite on it
if (!rendered ||
rendered->width() < rc2.w ||
rendered->height() < rc2.h ||
rendered->colorSpace() != m_document->osColorSpace()) {
const int maxw = std::max(rc2.w, rendered ? rendered->width(): 0);
const int maxh = std::max(rc2.h, rendered ? rendered->height(): 0);
rendered = os::instance()->makeRgbaSurface(
maxw, maxh, m_document->osColorSpace());
}
m_renderEngine->setProjection(
newEngine ? render::Projection(): m_proj);
m_renderEngine->renderSprite(
rendered.get(), m_sprite, m_frame, gfx::Clip(0, 0, rc2));
m_renderEngine->removeExtraImage();
// If the checkered background is visible in this sprite, we save
// all settings of the background for this document.
if (!m_sprite->isOpaque())
m_docPref.bg.forceSection();
}
catch (const std::exception& e) {
Console::showException(e);
}
if (rendered && rendered->nativeHandle()) {
if (newEngine) {
os::Sampling sampling;
if (m_proj.scaleX() < 1.0) {
switch (pref.editor.downsampling()) {
case gen::Downsampling::NEAREST:
sampling = os::Sampling(os::Sampling::Filter::Nearest);
break;
case gen::Downsampling::BILINEAR:
sampling = os::Sampling(os::Sampling::Filter::Linear);
break;
case gen::Downsampling::BILINEAR_MIPMAP:
sampling = os::Sampling(os::Sampling::Filter::Linear,
os::Sampling::Mipmap::Nearest);
break;
case gen::Downsampling::TRILINEAR_MIPMAP:
sampling = os::Sampling(os::Sampling::Filter::Linear,
os::Sampling::Mipmap::Linear);
break;
}
}
os::Paint p;
if (renderProperties.requiresRgbaBackbuffer)
p.blendMode(os::BlendMode::SrcOver);
else
p.blendMode(os::BlendMode::Src);
g->drawSurface(rendered.get(),
gfx::Rect(0, 0, rc2.w, rc2.h),
dest,
sampling,
&p);
}
else {
g->blit(rendered.get(), 0, 0, dest.x, dest.y, dest.w, dest.h);
}
}
// Draw grids
{
gfx::Rect enclosingRect(
m_padding.x + dx,
m_padding.y + dy,
m_proj.applyX(m_sprite->width()),
m_proj.applyY(m_sprite->height()));
IntersectClip clip(g, dest);
if (clip) {
// Draw the pixel grid
if ((m_proj.zoom().scale() > 2.0) && m_docPref.show.pixelGrid()) {
int alpha = m_docPref.pixelGrid.opacity();
if (m_docPref.pixelGrid.autoOpacity()) {
alpha = int(alpha * (m_proj.zoom().scale()-2.) / (16.-2.));
alpha = std::clamp(alpha, 0, 255);
}
drawGrid(g, enclosingRect, Rect(0, 0, 1, 1),
m_docPref.pixelGrid.color(), alpha);
// Save all pixel grid settings that are unset
m_docPref.pixelGrid.forceSection();
}
m_docPref.show.pixelGrid.forceDirtyFlag();
// Draw the grid
if (m_docPref.show.grid()) {
gfx::Rect gridrc;
if (!m_state->getGridBounds(this, gridrc))
gridrc = getSite().gridBounds();
if (m_proj.applyX(gridrc.w) > 2 &&
m_proj.applyY(gridrc.h) > 2) {
int alpha = m_docPref.grid.opacity();
if (m_docPref.grid.autoOpacity()) {
double len = (m_proj.applyX(gridrc.w) +
m_proj.applyY(gridrc.h)) / 2.;
alpha = int(alpha * len / 32.);
alpha = std::clamp(alpha, 0, 255);
}
if (alpha > 8) {
drawGrid(g, enclosingRect, gridrc,
m_docPref.grid.color(), alpha);
}
}
// Save all grid settings that are unset
m_docPref.grid.forceSection();
}
m_docPref.show.grid.forceDirtyFlag();
}
}
}
void Editor::drawBackground(ui::Graphics* g)
{
if (!(m_flags & kShowOutside))
return;
auto theme = SkinTheme::get(this);
gfx::Size canvas = canvasSize();
gfx::Rect rc(0, 0, canvas.w, canvas.h);
rc = editorToScreen(rc);
rc.offset(-bounds().origin());
// Fill the outside (parts of the editor that aren't covered by the
// sprite).
gfx::Region outside(clientBounds());
outside.createSubtraction(outside, gfx::Region(rc));
g->fillRegion(theme->colors.editorFace(), outside);
// Draw the borders that enclose the sprite.
rc.enlarge(1);
g->drawRect(theme->colors.editorSpriteBorder(), rc);
g->drawHLine(theme->colors.editorSpriteBottomBorder(), rc.x, rc.y2(), rc.w);
}
void Editor::drawSpriteUnclippedRect(ui::Graphics* g, const gfx::Rect& _rc)
{
gfx::Rect rc = _rc;
// For odd zoom scales minor than 100% we have to add an extra window
// just to make sure the whole rectangle is drawn.
if (m_proj.scaleX() < 1.0) rc.w += int(1./m_proj.scaleX());
if (m_proj.scaleY() < 1.0) rc.h += int(1./m_proj.scaleY());
gfx::Rect client = clientBounds();
gfx::Rect spriteRect(
client.x + m_padding.x,
client.y + m_padding.y,
m_proj.applyX(m_sprite->width()),
m_proj.applyY(m_sprite->height()));
gfx::Rect enclosingRect = spriteRect;
// Draw the main sprite at the center.
drawOneSpriteUnclippedRect(g, rc, 0, 0);
// Document preferences
if (int(m_docPref.tiled.mode()) & int(filters::TiledMode::X_AXIS)) {
drawOneSpriteUnclippedRect(g, rc, spriteRect.w, 0);
drawOneSpriteUnclippedRect(g, rc, spriteRect.w*2, 0);
enclosingRect = gfx::Rect(spriteRect.x, spriteRect.y, spriteRect.w*3, spriteRect.h);
}
if (int(m_docPref.tiled.mode()) & int(filters::TiledMode::Y_AXIS)) {
drawOneSpriteUnclippedRect(g, rc, 0, spriteRect.h);
drawOneSpriteUnclippedRect(g, rc, 0, spriteRect.h*2);
enclosingRect = gfx::Rect(spriteRect.x, spriteRect.y, spriteRect.w, spriteRect.h*3);
}
if (m_docPref.tiled.mode() == filters::TiledMode::BOTH) {
drawOneSpriteUnclippedRect(g, rc, spriteRect.w, spriteRect.h);
drawOneSpriteUnclippedRect(g, rc, spriteRect.w*2, spriteRect.h);
drawOneSpriteUnclippedRect(g, rc, spriteRect.w, spriteRect.h*2);
drawOneSpriteUnclippedRect(g, rc, spriteRect.w*2, spriteRect.h*2);
enclosingRect = gfx::Rect(
spriteRect.x, spriteRect.y,
spriteRect.w*3, spriteRect.h*3);
}
// Draw slices
if (m_docPref.show.slices())
drawSlices(g);
// Symmetry mode
if (isActive() &&
(m_flags & Editor::kShowSymmetryLine) &&
Preferences::instance().symmetryMode.enabled()) {
int mode = int(m_docPref.symmetry.mode());
if (mode & int(app::gen::SymmetryMode::HORIZONTAL)) {
double x = m_docPref.symmetry.xAxis();
if (x > 0) {
gfx::Color color = color_utils::color_for_ui(m_docPref.grid.color());
g->drawVLine(color,
spriteRect.x + m_proj.applyX(mainTilePosition().x) + int(m_proj.applyX<double>(x)),
enclosingRect.y,
enclosingRect.h);
}
}
if (mode & int(app::gen::SymmetryMode::VERTICAL)) {
double y = m_docPref.symmetry.yAxis();
if (y > 0) {
gfx::Color color = color_utils::color_for_ui(m_docPref.grid.color());
g->drawHLine(color,
enclosingRect.x,
spriteRect.y + m_proj.applyY(mainTilePosition().y) + int(m_proj.applyY<double>(y)),
enclosingRect.w);
}
}
}
// Draw active layer/cel edges
if ((m_docPref.show.layerEdges() || m_showAutoCelGuides) &&
// Show layer edges and possibly cel guides only on states that
// allows it (e.g scrolling state)
m_state->allowLayerEdges()) {
Cel* cel = (m_layer ? m_layer->cel(m_frame): nullptr);
if (cel) {
gfx::Color color = color_utils::color_for_ui(Preferences::instance().guides.layerEdgesColor());
drawCelBounds(g, cel, color);
// Draw tile numbers
if (m_docPref.show.tileNumbers() &&
cel->layer()->isTilemap()) {
drawTileNumbers(g, cel);
}
// Draw auto-guides to other cel
if (m_showAutoCelGuides &&
m_showGuidesThisCel != cel) {
drawCelGuides(g, cel, m_showGuidesThisCel);
}
}
}
// Draw the mask
if (m_document->hasMaskBoundaries())
drawMask(g);
// Post-render decorator.
if ((m_flags & kShowDecorators) && m_decorator) {
EditorPostRenderImpl postRender(this, g);
m_decorator->postRenderDecorator(&postRender);
}
}
void Editor::drawSpriteClipped(const gfx::Region& updateRegion)
{
Region screenRegion;
getDrawableRegion(screenRegion, kCutTopWindows);
ScreenGraphics screenGraphics(display());
GraphicsPtr editorGraphics = getGraphics(clientBounds());
for (const Rect& updateRect : updateRegion) {
for (const Rect& screenRect : screenRegion) {
IntersectClip clip(&screenGraphics, screenRect);
if (clip)
drawSpriteUnclippedRect(editorGraphics.get(), updateRect);