forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewerInstance.cpp
3552 lines (3089 loc) · 139 KB
/
ViewerInstance.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
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <https://natrongithub.github.io/>,
* (C) 2018-2021 The Natron developers
* (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat
*
* Natron is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Natron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
// ***** BEGIN PYTHON BLOCK *****
// from <https://docs.python.org/3/c-api/intro.html#include-files>:
// "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included."
#include <Python.h>
// ***** END PYTHON BLOCK *****
#include "ViewerInstance.h"
#include "ViewerInstancePrivate.h"
#include <algorithm> // min, max
#include <stdexcept>
#include <cassert>
#include <cstring> // for std::memcpy
#include <cfloat> // DBL_MAX
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/make_shared.hpp>
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF
// /usr/local/include/boost/bind/arg.hpp:37:9: warning: unused typedef 'boost_static_assert_typedef_37' [-Wunused-local-typedef]
#include <boost/bind/bind.hpp>
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_ON
CLANG_DIAG_OFF(deprecated)
#include <QtCore/QtGlobal>
#include <QtConcurrentMap> // QtCore on Qt4, QtConcurrent on Qt5
#include <QtCore/QFutureWatcher>
#include <QtCore/QMutex>
#include <QtCore/QWaitCondition>
#include <QtCore/QCoreApplication>
#include <QtCore/QThreadPool>
CLANG_DIAG_ON(deprecated)
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/Cache.h"
#include "Engine/Image.h"
#include "Engine/Log.h"
#include "Engine/Lut.h"
#include "Engine/MemoryFile.h"
#include "Engine/MemoryInfo.h" // printAsRAM
#include "Engine/Node.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OpenGLViewerI.h"
#include "Engine/OutputSchedulerThread.h"
#include "Engine/Project.h"
#include "Engine/RenderStats.h"
#include "Engine/RotoContext.h"
#include "Engine/RotoPaint.h"
#include "Engine/RotoStrokeItem.h"
#include "Engine/Settings.h"
#include "Engine/TimeLine.h"
#include "Engine/Timer.h"
#include "Engine/UpdateViewerParams.h"
#include "Engine/Utils.h"
#include "Engine/ViewIdx.h"
using namespace boost::placeholders;
#ifndef M_LN2
#define M_LN2 0.693147180559945309417232121458176568 /* loge(2) */
#endif
#define NATRON_TIME_ELASPED_BEFORE_PROGRESS_REPORT 4. //!< do not display the progress report if estimated total time is less than this (in seconds)
NATRON_NAMESPACE_ENTER
using std::make_pair;
using boost::shared_ptr;
NATRON_NAMESPACE_ANONYMOUS_ENTER
struct MinMaxVal {
MinMaxVal(double min_, double max_)
: min(min_)
, max(max_)
{
}
MinMaxVal()
: min(DBL_MAX)
, max(-DBL_MAX)
{
}
double min;
double max;
};
NATRON_NAMESPACE_ANONYMOUS_EXIT
static void scaleToTexture8bits(const RectI& roi,
const RenderViewerArgs & args,
ViewerInstance* viewer,
const UpdateViewerParams::CachedTile& tile,
U32* output);
static void scaleToTexture32bits(const RectI& roi,
const RenderViewerArgs & args,
const UpdateViewerParams::CachedTile& tile,
float *output);
static MinMaxVal findAutoContrastVminVmax(const ImagePtr inputImage,
DisplayChannelsEnum channels,
const RectI & rect);
static void renderFunctor(const RectI& roi,
const RenderViewerArgs & args,
ViewerInstance* viewer,
UpdateViewerParams::CachedTile tile);
/**
*@brief Actually converting to ARGB... but it is called BGRA by
the texture format GL_UNSIGNED_INT_8_8_8_8_REV
**/
static unsigned int toBGRA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) WARN_UNUSED_RETURN;
unsigned int
toBGRA(unsigned char r,
unsigned char g,
unsigned char b,
unsigned char a)
{
return (a << 24) | (r << 16) | (g << 8) | b;
}
const Color::Lut*
ViewerInstance::lutFromColorspace(ViewerColorSpaceEnum cs)
{
const Color::Lut* lut;
switch (cs) {
case eViewerColorSpaceSRGB:
lut = Color::LutManager::sRGBLut();
break;
case eViewerColorSpaceRec709:
lut = Color::LutManager::Rec709Lut();
break;
case eViewerColorSpaceLinear:
default:
lut = 0;
break;
}
if (lut) {
lut->validate();
}
return lut;
}
EffectInstance*
ViewerInstance::BuildEffect(NodePtr n)
{
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
return new ViewerInstance(n);
}
ViewerInstance::ViewerInstance(NodePtr node)
: OutputEffectInstance(node)
, _imp( new ViewerInstancePrivate(this) )
{
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
setSupportsRenderScaleMaybe(EffectInstance::eSupportsYes);
QObject::connect( this, SIGNAL(disconnectTextureRequest(int,bool)), this, SLOT(executeDisconnectTextureRequestOnMainThread(int,bool)) );
QObject::connect( _imp.get(), SIGNAL(mustRedrawViewer()), this, SLOT(redrawViewer()) );
QObject::connect( this, SIGNAL(s_callRedrawOnMainThread()), this, SLOT(redrawViewer()) );
}
ViewerInstance::~ViewerInstance()
{
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
// If _imp->updateViewerRunning is true, that means that the next updateViewer call was
// not yet processed. Since we're in the main thread and it is processed in the main thread,
// there is no way to wait for it (locking the mutex would cause a deadlock).
// We don't care, after all.
//{
// QMutexLocker locker(&_imp->updateViewerMutex);
// assert(!_imp->updateViewerRunning);
//}
if (_imp->uiContext) {
_imp->uiContext->removeGUI();
}
}
RenderEngine*
ViewerInstance::createRenderEngine()
{
ViewerInstancePtr thisShared = boost::dynamic_pointer_cast<ViewerInstance>( shared_from_this() );
return new ViewerRenderEngine(thisShared);
}
void
ViewerInstance::getPluginGrouping(std::list<std::string>* grouping) const
{
grouping->push_back(PLUGIN_GROUP_IMAGE);
}
OpenGLViewerI*
ViewerInstance::getUiContext() const
{
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
return _imp->uiContext;
}
void
ViewerInstance::forceFullComputationOnNextFrame()
{
// this is called by the GUI when the user presses the "Refresh" button.
// It set the flag forceRender to true, meaning no cache will be used.
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
QMutexLocker forceRenderLocker(&_imp->forceRenderMutex);
_imp->forceRender[0] = _imp->forceRender[1] = true;
}
void
ViewerInstance::clearLastRenderedImage()
{
EffectInstance::clearLastRenderedImage();
if (_imp->uiContext) {
_imp->uiContext->clearLastRenderedImage();
}
{
QMutexLocker k(&_imp->lastRenderParamsMutex);
_imp->lastRenderParams[0].reset();
_imp->lastRenderParams[1].reset();
}
}
void
ViewerInstance::setUiContext(OpenGLViewerI* viewer)
{
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
_imp->uiContext = viewer;
}
void
ViewerInstance::invalidateUiContext()
{
// always running in the main thread
assert( qApp && qApp->thread() == QThread::currentThread() );
_imp->uiContext = NULL;
}
int
ViewerInstance::getNInputs() const
{
return 10;
}
void
ViewerInstance::getFrameRange(double *first,
double *last)
{
double inpFirst = 1, inpLast = 1;
int activeInputs[2];
getActiveInputs(activeInputs[0], activeInputs[1]);
EffectInstancePtr n1 = getInput(activeInputs[0]);
if (n1) {
n1->getFrameRange_public(n1->getRenderHash(), &inpFirst, &inpLast);
}
*first = inpFirst;
*last = inpLast;
inpFirst = 1;
inpLast = 1;
EffectInstancePtr n2 = getInput(activeInputs[1]);
if (n2) {
n2->getFrameRange_public(n2->getRenderHash(), &inpFirst, &inpLast);
if (inpFirst < *first) {
*first = inpFirst;
}
if (inpLast > *last) {
*last = inpLast;
}
}
}
void
ViewerInstance::executeDisconnectTextureRequestOnMainThread(int index,bool clearRoD)
{
assert( QThread::currentThread() == qApp->thread() );
if (_imp->uiContext) {
_imp->uiContext->disconnectInputTexture(index, clearRoD);
}
}
static bool
isRotoPaintNodeInputRecursive(Node* node,
const NodePtr& rotoPaintNode)
{
if ( node == rotoPaintNode.get() ) {
return true;
}
int maxInputs = node->getNInputs();
for (int i = 0; i < maxInputs; ++i) {
NodePtr input = node->getInput(i);
if (input) {
if (input == rotoPaintNode) {
return true;
} else {
bool ret = isRotoPaintNodeInputRecursive(input.get(), rotoPaintNode);
if (ret) {
return true;
}
}
}
}
return false;
}
static void
updateLastStrokeDataRecursively(Node* node,
const NodePtr& rotoPaintNode,
const RectD& lastStrokeBbox,
bool invalidate)
{
if ( isRotoPaintNodeInputRecursive(node, rotoPaintNode) ) {
if (invalidate) {
node->invalidateLastPaintStrokeDataNoRotopaint();
} else {
node->setLastPaintStrokeDataNoRotopaint();
}
if ( node == rotoPaintNode.get() ) {
return;
}
int maxInputs = node->getNInputs();
for (int i = 0; i < maxInputs; ++i) {
NodePtr input = node->getInput(i);
if (input) {
updateLastStrokeDataRecursively(input.get(), rotoPaintNode, lastStrokeBbox, invalidate);
}
}
}
}
class ViewerParallelRenderArgsSetter
: public ParallelRenderArgsSetter
{
NodePtr rotoNode;
NodePtr viewerNode;
NodePtr viewerInputNode;
public:
ViewerParallelRenderArgsSetter(double time,
ViewIdx view,
bool isRenderUserInteraction,
bool isSequential,
const AbortableRenderInfoPtr& abortInfo,
const NodePtr& treeRoot,
int textureIndex,
const TimeLine* timeline,
bool isAnalysis,
const NodePtr& rotoPaintNode,
const NodePtr& viewerInput,
bool draftMode,
const RenderStatsPtr& stats)
: ParallelRenderArgsSetter(time, view, isRenderUserInteraction, isSequential, abortInfo, treeRoot, textureIndex, timeline, rotoPaintNode, isAnalysis, draftMode, stats)
, rotoNode(rotoPaintNode)
, viewerNode(treeRoot)
, viewerInputNode()
{
///There can be a case where the viewer input tree does not belong to the project, for example
///for the File Dialog preview.
if ( viewerInput && !viewerInput->getGroup() ) {
viewerInputNode = viewerInput;
bool doNanHandling = appPTR->getCurrentSettings()->isNaNHandlingEnabled();
U64 nodeHash = viewerInput->getHashValue();
viewerInput->getEffectInstance()->setParallelRenderArgsTLS(time, view, isRenderUserInteraction, isSequential, nodeHash, abortInfo, treeRoot, 1, NodeFrameRequestPtr(), _openGLContext.lock(), textureIndex, timeline, isAnalysis, false, NodesList(), viewerInput->getCurrentRenderThreadSafety(), viewerInput->getCurrentOpenGLRenderSupport(), doNanHandling, draftMode, stats);
}
}
virtual ~ViewerParallelRenderArgsSetter()
{
if (rotoNode) {
updateLastStrokeDataRecursively(viewerNode.get(), rotoNode, RectD(), true);
}
if (viewerInputNode) {
viewerInputNode->getEffectInstance()->invalidateParallelRenderArgsTLS();
}
}
};
ViewerInstance::ViewerRenderRetCode
ViewerInstance::getViewerArgsAndRenderViewer(SequenceTime time,
bool canAbort,
ViewIdx view,
U64 viewerHash,
const NodePtr& rotoPaintNode,
const RotoStrokeItemPtr& activeStroke,
const RenderStatsPtr& stats,
ViewerArgsPtr* argsA,
ViewerArgsPtr* argsB)
{
///This is used only by the rotopaint while drawing. We must clear the action cache of the rotopaint node before calling
///getRoD or this will not work
assert(rotoPaintNode);
if ( !rotoPaintNode->getEffectInstance() ) {
return eViewerRenderRetCodeFail;
}
rotoPaintNode->getEffectInstance()->clearActionsCache();
ViewerRenderRetCode status[2] = {
eViewerRenderRetCodeFail, eViewerRenderRetCodeFail
};
NodePtr thisNode = getNode();
ViewerArgsPtr args[2];
for (int i = 0; i < 2; ++i) {
args[i] = boost::make_shared<ViewerArgs>();
if ( (i == 1) && (_imp->uiContext->getCompositingOperator() == eViewerCompositingOperatorNone) ) {
break;
}
AbortableRenderInfoPtr abortInfo = _imp->createNewRenderRequest(i, canAbort);
/*FrameRequestMap request;
RectI roi;
{
roi.x1 = args[i]->params->textureRect.x1;
roi.y1 = args[i]->params->textureRect.y1;
roi.x2 = args[i]->params->textureRect.x2;
roi.y2 = args[i]->params->textureRect.y2;
}
status[i] = EffectInstance::computeRequestPass(time, view, args[i]->params->mipMapLevel, roi, thisNode, request);
if (status[i] == eStatusFailed) {
continue;
}*/
ViewerParallelRenderArgsSetter tls(time,
view,
true,
false,
abortInfo,
thisNode,
i,
getTimeline().get(),
false,
rotoPaintNode,
NodePtr(),
false,
stats);
NodesList rotoPaintNodes;
if (rotoPaintNode) {
if (activeStroke) {
EffectInstancePtr rotoLive = rotoPaintNode->getEffectInstance();
assert(rotoLive);
bool ok = rotoLive->getThreadLocalRotoPaintTreeNodes(&rotoPaintNodes);
assert(ok);
if (!ok) {
throw std::logic_error("ViewerParallelRenderArgsSetter(): getThreadLocalRotoPaintTreeNodes() failed");
}
/*
Take from the stroke all the points that were input by the user so far on the main thread and set them globally to the
application. These data are the ones that are going to be used by any Roto related tool. We ensure that they all access
the same data so we only access the real Roto datas now.
*/
//The last points input by the user
std::list<std::pair<Point, double> > lastStrokePoints;
//The stroke RoD so far
RectD wholeStrokeRod;
//The bbox of the lastStrokePoints
RectD lastStrokeBbox;
//The index in the stroke of the last point we have rendered and up to the new point we have rendered
int lastAge, newAge;
//get on the app object the last point index we have rendered on this stroke
lastAge = getApp()->getStrokeLastIndex();
//Get the active paint stroke so far and its multi-stroke index
RotoStrokeItemPtr currentlyPaintedStroke;
int currentlyPaintedStrokeMultiIndex;
getApp()->getStrokeAndMultiStrokeIndex(¤tlyPaintedStroke, ¤tlyPaintedStrokeMultiIndex);
//If this crashes here that means the user could start a new stroke while this one is not done rendering.
assert(currentlyPaintedStroke == activeStroke);
//the multi-stroke index in case of a stroke containing multiple strokes from the user
int strokeIndex;
if ( activeStroke->getMostRecentStrokeChangesSinceAge(time, lastAge, currentlyPaintedStrokeMultiIndex, &lastStrokePoints, &lastStrokeBbox, &wholeStrokeRod, &newAge, &strokeIndex) ) {
getApp()->updateLastPaintStrokeData(newAge, lastStrokePoints, lastStrokeBbox, strokeIndex);
for (NodesList::iterator it = rotoPaintNodes.begin(); it != rotoPaintNodes.end(); ++it) {
(*it)->prepareForNextPaintStrokeRender();
}
updateLastStrokeDataRecursively(thisNode.get(), rotoPaintNode, lastStrokeBbox, false);
} else {
///The drawing is already up to date: all changes have been taken into account for this event
args[i].reset();
return eViewerRenderRetCodeRedraw;
}
}
}
if (args[i]) {
status[i] = getRenderViewerArgsAndCheckCache( time, false, view, i, viewerHash, rotoPaintNode, abortInfo, stats, args[i].get() );
}
if (status[i] != eViewerRenderRetCodeRender) {
/*
Either failure, black or nothing, the texture is junk, remove it from the cache
*/
if (args[i] && args[i]->params) {
for (std::list<UpdateViewerParams::CachedTile>::iterator it = args[i]->params->tiles.begin(); it != args[i]->params->tiles.end(); ++it) {
if (it->cachedData) {
//it->cachedData->setAborted(true);
//appPTR->removeFromViewerCache(it->cachedData);
it->cachedData.reset();
}
}
args[i]->params->tiles.clear();
}
}
if ( (status[i] == eViewerRenderRetCodeFail) || (status[i] == eViewerRenderRetCodeBlack) ) {
disconnectTextureRequest(i, status[i] == eViewerRenderRetCodeFail);
} else {
assert(args[i] && args[i]->params);
assert(args[i]->params->textureIndex == i);
if ( !_imp->addOngoingRender(args[i]->params->textureIndex, abortInfo) ) {
/*
This may fail if another thread already pushed a more recent render in the render ages queue
*/
status[i] = eViewerRenderRetCodeRedraw;
args[i].reset();
}
if (args[i]) {
status[i] = renderViewer_internal(view,
QThread::currentThread() == qApp->thread(), // singleThreaded
false, // isSequentialRender
viewerHash,
canAbort,
rotoPaintNode,
false, //useTLS
ViewerCurrentFrameRequestSchedulerStartArgsPtr(),
stats,
*args[i]);
args[i]->isRenderingFlag.reset();
}
if (args[i] && args[i]->params) {
if ( (status[i] == eViewerRenderRetCodeFail) || (status[i] == eViewerRenderRetCodeBlack) ) {
_imp->checkAndUpdateDisplayAge( args[i]->params->textureIndex, abortInfo->getRenderAge() );
}
_imp->removeOngoingRender( args[i]->params->textureIndex, abortInfo->getRenderAge() );
}
if (status[i] == eViewerRenderRetCodeRedraw) {
args[i].reset();
}
}
}
if ( (status[0] == eViewerRenderRetCodeFail) && (status[1] == eViewerRenderRetCodeFail) ) {
return eViewerRenderRetCodeFail;
}
*argsA = args[0];
*argsB = args[1];
return eViewerRenderRetCodeRender;
} // ViewerInstance::getViewerArgsAndRenderViewer
ViewerInstance::ViewerRenderRetCode
ViewerInstance::renderViewer(ViewIdx view,
bool singleThreaded,
bool isSequentialRender,
U64 viewerHash,
bool canAbort,
const NodePtr& rotoPaintNode,
bool useTLS,
ViewerArgsPtr args[2],
const ViewerCurrentFrameRequestSchedulerStartArgsPtr& request,
const RenderStatsPtr& stats)
{
if (!_imp->uiContext) {
return eViewerRenderRetCodeFail;
}
/**
* When entering this code, we already know that the textures are not cached for the A and B inputs
* If the an input is not connected, it's args[i] will be NULL.
* If either one of the renders fails, that means we should block playback and clear to black the viewer
**/
ViewerInstance::ViewerRenderRetCode ret[2] = {
eViewerRenderRetCodeRedraw, eViewerRenderRetCodeRedraw
};
for (int i = 0; i < 2; ++i) {
if (args[i] && args[i]->params) {
if ( (i == 1) && (_imp->uiContext->getCompositingOperator() == eViewerCompositingOperatorNone) ) {
args[i]->params->tiles.clear();
break;
}
assert(args[i]->params->textureIndex == i);
///We enable render stats just for the A input (i == 0) otherwise we would get crappy results
if (!isSequentialRender) {
if ( !_imp->addOngoingRender(args[i]->params->textureIndex, args[i]->params->abortInfo) ) {
/*
This may fail if another thread already pushed a more recent render in the render ages queue
*/
ret[i] = eViewerRenderRetCodeRedraw;
args[i].reset();
}
}
if (args[i]) {
ret[i] = renderViewer_internal(view, singleThreaded, isSequentialRender, viewerHash, canAbort, rotoPaintNode, useTLS, request,
i == 0 ? stats : RenderStatsPtr(),
*args[i]);
// Reset the rednering flag
args[i]->isRenderingFlag.reset();
}
if (ret[i] != eViewerRenderRetCodeRender) {
/*
Either failure, black or nothing, the texture is junk, remove it from the cache
*/
if (args[i] && args[i]->params) {
for (std::list<UpdateViewerParams::CachedTile>::iterator it = args[i]->params->tiles.begin(); it != args[i]->params->tiles.end(); ++it) {
if (it->cachedData) {
//it->cachedData->setAborted(true);
//appPTR->removeFromViewerCache(it->cachedData);
it->cachedData.reset();
}
}
args[i]->params->tiles.clear();
}
}
if (!isSequentialRender && args[i] && args[i]->params) {
if ( (ret[i] == eViewerRenderRetCodeFail) || (ret[i] == eViewerRenderRetCodeBlack) ) {
_imp->checkAndUpdateDisplayAge( args[i]->params->textureIndex, args[i]->params->abortInfo->getRenderAge() );
}
_imp->removeOngoingRender( args[i]->params->textureIndex, args[i]->params->abortInfo->getRenderAge() );
}
if (ret[i] == eViewerRenderRetCodeBlack) {
disconnectTexture(args[i]->params->textureIndex, false);
}
if (ret[i] == eViewerRenderRetCodeFail) {
args[i].reset();
}
}
}
if ( (ret[0] == eViewerRenderRetCodeFail) || (ret[1] == eViewerRenderRetCodeFail) ) {
return eViewerRenderRetCodeFail;
}
return eViewerRenderRetCodeRender;
} // ViewerInstance::renderViewer
static bool
checkTreeCanRender_internal(Node* node,
std::list<Node*>& marked)
{
if ( std::find(marked.begin(), marked.end(), node) != marked.end() ) {
return true;
}
marked.push_back(node);
// check that the nodes upstream have all their nonoptional inputs connected
int maxInput = node->getNInputs();
for (int i = 0; i < maxInput; ++i) {
NodePtr input = node->getInput(i);
bool optional = node->getEffectInstance()->isInputOptional(i);
if (optional) {
continue;
}
if (!input) {
return false;
} else {
bool ret = checkTreeCanRender_internal(input.get(), marked);
if (!ret) {
return false;
}
}
}
return true;
}
/**
* @brief Returns false if the tree has unconnected mandatory inputs
**/
static bool
checkTreeCanRender(Node* node)
{
std::list<Node*> marked;
bool ret = checkTreeCanRender_internal(node, marked);
return ret;
}
static unsigned char*
getTexPixel(int x,
int y,
const TextureRect& bounds,
std::size_t pixelDepth,
unsigned char* bufStart)
{
if ( ( x < bounds.x1 ) || ( x >= bounds.x2 ) || ( y < bounds.y1 ) || ( y >= bounds.y2 ) ) {
return NULL;
} else {
int compDataSize = pixelDepth * 4;
return (unsigned char*)(bufStart)
+ (qint64)( y - bounds.y1 ) * compDataSize * bounds.width()
+ (qint64)( x - bounds.x1 ) * compDataSize;
}
}
static bool
copyAndSwap(const TextureRect& srcRect,
const TextureRect& dstRect,
std::size_t dstBytesCount,
ImageBitDepthEnum bitdepth,
unsigned char* srcBuf,
unsigned char** dstBuf)
{
// Ensure it has the correct size, resize it if needed
if ( (srcRect.x1 == dstRect.x1) &&
( srcRect.y1 == dstRect.y1) &&
( srcRect.x2 == dstRect.x2) &&
( srcRect.y2 == dstRect.y2) ) {
*dstBuf = srcBuf;
return false;
}
// Use calloc so that newly allocated areas are already black and transparent
unsigned char* tmpBuf = (unsigned char*)calloc(dstBytesCount, 1);
if (!tmpBuf) {
*dstBuf = 0;
return true;
}
std::size_t pixelDepth = getSizeOfForBitDepth(bitdepth);
unsigned char* dstPixels = getTexPixel(srcRect.x1, srcRect.y1, dstRect, pixelDepth, tmpBuf);
assert(dstPixels);
const unsigned char* srcPixels = getTexPixel(srcRect.x1, srcRect.y1, srcRect, pixelDepth, srcBuf);
assert(srcPixels);
std::size_t srcRowSize = srcRect.width() * 4 * pixelDepth;
std::size_t dstRowSize = dstRect.width() * 4 * pixelDepth;
for (int y = srcRect.y1; y < srcRect.y2;
++y, srcPixels += srcRowSize, dstPixels += dstRowSize) {
std::memcpy(dstPixels, srcPixels, srcRowSize);
}
*dstBuf = tmpBuf;
return true;
}
ViewerInstance::ViewerRenderRetCode
ViewerInstance::getRenderViewerArgsAndCheckCache_public(SequenceTime time,
bool isSequential,
ViewIdx view,
int textureIndex,
U64 viewerHash,
bool canAbort,
const NodePtr& rotoPaintNode,
const RenderStatsPtr& stats,
ViewerArgs* outArgs)
{
AbortableRenderInfoPtr abortInfo = _imp->createNewRenderRequest(textureIndex, canAbort);
ViewerRenderRetCode stat = getRenderViewerArgsAndCheckCache(time, isSequential, view, textureIndex, viewerHash, rotoPaintNode, abortInfo, stats, outArgs);
if ( (stat == eViewerRenderRetCodeFail) || (stat == eViewerRenderRetCodeBlack) ) {
_imp->checkAndUpdateDisplayAge( textureIndex, abortInfo->getRenderAge() );
}
return stat;
}
void
ViewerInstance::setupMinimalUpdateViewerParams(const SequenceTime time,
const ViewIdx view,
const int textureIndex,
const AbortableRenderInfoPtr& abortInfo,
const bool isSequential,
ViewerArgs* outArgs)
{
assert(_imp->uiContext);
{
QMutexLocker l(&_imp->viewerParamsMutex);
outArgs->mipmapLevelWithoutDraft = (unsigned int)_imp->viewerMipMapLevel;
}
assert(_imp->uiContext);
// This is the current zoom factor (1. == 100%) currently set by the user in the viewport
double zoomFactor = _imp->uiContext->getZoomFactor();
// We render the image that is the nearest mipmap level higher in quality.
// For instance, if we were to render at 48% zoom factor, we would render at 50% which is mipmapLevel=1
// If on the other hand the zoom factor would be at 51%, then we would render at 100% which is mipmapLevel=0
// Adjust the mipmap level (without taking draft into account yet) as the max of the closest mipmap level of the viewer zoom
// and the requested user proxy mipmap level
if (isFullFrameProcessingEnabled()) {
outArgs->mipmapLevelWithoutDraft = 0;
} else {
int zoomMipMapLevel;
{
double closestPowerOf2 = zoomFactor >= 1 ? 1 : ipow( 2, (int)-std::ceil(std::log(zoomFactor) / M_LN2) );
zoomMipMapLevel = std::log(closestPowerOf2) / M_LN2;
}
outArgs->mipmapLevelWithoutDraft = (unsigned int)std::max( (int)outArgs->mipmapLevelWithoutDraft, (int)zoomMipMapLevel );
}
outArgs->mipMapLevelWithDraft = outArgs->mipmapLevelWithoutDraft;
outArgs->draftModeEnabled = getApp()->isDraftRenderEnabled();
// If draft mode is enabled, compute the mipmap level according to the auto-proxy setting in the preferences
if ( outArgs->draftModeEnabled && appPTR->getCurrentSettings()->isAutoProxyEnabled() ) {
unsigned int autoProxyLevel = appPTR->getCurrentSettings()->getAutoProxyMipMapLevel();
if (zoomFactor > 1) {
//Decrease draft mode at each inverse mipmaplevel level taken
unsigned int invLevel = Image::getLevelFromScale(1. / zoomFactor);
if (invLevel < autoProxyLevel) {
autoProxyLevel -= invLevel;
} else {
autoProxyLevel = 0;
}
}
outArgs->mipMapLevelWithDraft = (unsigned int)std::max( (int)outArgs->mipmapLevelWithoutDraft, (int)autoProxyLevel );
}
// The hash of the node to render, we store it and make sure we never call getHash() again for the render of this frame
outArgs->activeInputHash = outArgs->activeInputToRender->getHash();
// Initialize the flag
outArgs->mustComputeRoDAndLookupCache = true;
// Check if the render was issued from the "Refresh" button, in which case we compute images from nodes at least once
{
QMutexLocker forceRenderLocker(&_imp->forceRenderMutex);
outArgs->forceRender = _imp->forceRender[textureIndex];
_imp->forceRender[textureIndex] = false;
}
// Did the user enabled the user roi from the viewer UI?
outArgs->userRoIEnabled = _imp->uiContext->isUserRegionOfInterestEnabled();
outArgs->params = boost::make_shared<UpdateViewerParams>();
// The PAR of the input image
outArgs->params->pixelAspectRatio = outArgs->activeInputToRender->getAspectRatio(-1);
// Is it playback ?
outArgs->params->isSequential = isSequential;
// Used to identify this render when calling EffectInstance::Implementation::aborted
outArgs->params->abortInfo = abortInfo;
// Used to differentiate the 2 different textures when wipe is enabled
outArgs->params->setUniqueID(textureIndex);
// Used to determine how the viewer should handle alpha
outArgs->params->srcPremult = outArgs->activeInputToRender->getPremult();
// The user requested bitdepth of the textures
outArgs->params->depth = _imp->uiContext->getBitDepth();
// The frame number
outArgs->params->time = time;
// The view to render
outArgs->params->view = view;
// A input = 0, B input = 1
outArgs->params->textureIndex = textureIndex;
// These are the user settings from the viewer UI
{
QMutexLocker locker(&_imp->viewerParamsMutex);
outArgs->autoContrast = _imp->viewerParamsAutoContrast;
outArgs->channels = _imp->viewerParamsChannels[textureIndex];
outArgs->params->gain = _imp->viewerParamsGain;
outArgs->params->gamma = _imp->viewerParamsGamma;
outArgs->params->lut = _imp->viewerParamsLut;
outArgs->params->layer = _imp->viewerParamsLayer;
outArgs->params->alphaLayer = _imp->viewerParamsAlphaLayer;
outArgs->params->alphaChannelName = _imp->viewerParamsAlphaChannelName;
outArgs->isDoingPartialUpdates = _imp->isDoingPartialUpdates;
}
// Fill the gamma LUT if it has never been filled yet
bool gammaLookupEmpty;
{
QReadLocker k(&_imp->gammaLookupMutex);
gammaLookupEmpty = _imp->gammaLookup.empty();
}
if (gammaLookupEmpty) {
QWriteLocker k(&_imp->gammaLookupMutex);
if ( _imp->gammaLookup.empty() ) {
_imp->fillGammaLut(outArgs->params->gamma);
}
}
// Flag that we are going to render
outArgs->isRenderingFlag = boost::make_shared<RenderingFlagSetter>( getNode() );
} // ViewerInstance::setupMinimalUpdateViewerParams
void
ViewerInstance::getRegionsOfInterest(double /*time*/,
const RenderScale & /*scale*/,
const RectD & /*outputRoD*/, //!< the RoD of the effect, in canonical coordinates
const RectD & renderWindow, //!< the region to be rendered in the output image, in Canonical Coordinates
ViewIdx /*view*/,
RoIMap* ret)
{
#pragma message WARN("2.2: fix this and only add RoI for thread local input")
for (int i = 0; i < getNInputs(); ++i) {
EffectInstancePtr input = getInput(i);
if (input) {
ret->insert( std::make_pair(input, renderWindow) );
}
}
}
ViewerInstance::ViewerRenderRetCode
ViewerInstance::getViewerRoIAndTexture(const RectD& rod,
const U64 viewerHash,
const bool useCache,
const bool isDraftMode,
const unsigned int mipmapLevel,
const RenderStatsPtr& stats,
ViewerArgs* outArgs)
{
// Roi is the coordinates of the 4 corners of the texture in the bounds with the current zoom
// factor taken into account.
// When auto-contrast is enabled or user RoI, we compute exactly the image portion displayed in the rectangle and
// do not round it to Viewer tiles.
outArgs->params->tiles.clear();
outArgs->params->nbCachedTile = 0;