123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797 |
- /*
- * Copyright (c) Contributors to the Open 3D Engine Project.
- * For complete copyright and license terms please see the LICENSE at the root of this distribution.
- *
- * SPDX-License-Identifier: Apache-2.0 OR MIT
- *
- */
- // Description : A dialog for batch-rendering sequences
- #include "EditorDefs.h"
- #include "SequenceBatchRenderDialog.h"
- #include "TrackViewMessageBox.h"
- #include <Atom/RPI.Public/ViewProviderBus.h>
- #include <AzCore/Component/ComponentApplication.h>
- #include <AzFramework/Windowing/WindowBus.h>
- #include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
- // Qt
- #include <QtConcurrent>
- #include <QStringListModel>
- #include <QFileDialog>
- #include <QAction>
- // CryCommon
- #include <CryCommon/Maestro/Types/AnimNodeType.h>
- // Editor
- #include "CryEdit.h"
- #include "CustomResolutionDlg.h"
- #include "GameEngine.h"
- #include "Include/ICommandManager.h"
- #include "MainWindow.h"
- #include "ViewPane.h"
- #include "Viewport.h"
- AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING
- #include <TrackView/ui_SequenceBatchRenderDialog.h>
- AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING
- namespace
- {
- const int g_useActiveViewportResolution = -1; // reserved value to indicate the use of the active viewport resolution
- int resolutions[][2] = {
- {1280, 720},
- {1920, 1080},
- {1998, 1080},
- {2048, 858},
- {2560, 1440},
- {3840, 2160},
- { g_useActiveViewportResolution, g_useActiveViewportResolution } // active viewport res must be the last element of the resolution array
- };
- // cached current active viewport resolution
- int activeViewportWidth;
- int activeViewportHeight;
- struct SFPSPair
- {
- int fps;
- const char* fpsDesc;
- } fpsOptions[] = {
- {24, "Film(24)"}, {25, "PAL(25)"}, {30, "NTSC(30)"},
- {48, "Show(48)"}, {50, "PAL Field(50)"}, {60, "NTSC Field(60)"}
- };
- // currently supported file extensions
- const char* imageFormatExtensions[] = {"dds", "ppm"};
- const char defaultPresetFilename[] = "defaultBatchRender.preset";
- const char customResFormat[] = "Custom(%1 x %2)...";
- const char debugInfo[] = "debuginfo";
- const int kBatchRenderFileVersion = 2; // This version number should be incremented every time available options like the list of formats,
- // the list of buffers change.
- // get the actual render width to use (substitutes active viewport width if needed)
- int getResWidth(int renderItemWidth)
- {
- return (renderItemWidth == g_useActiveViewportResolution) ? activeViewportWidth : renderItemWidth;
- }
- // get the actual render height to use (substitutes active viewport height if needed)
- int getResHeight(int renderItemHeight)
- {
- return (renderItemHeight == g_useActiveViewportResolution) ? activeViewportHeight : renderItemHeight;
- }
- }
- namespace TrackView
- {
- AZ_CVAR(
- int,
- tv_SkipFramesCount,
- 30,
- nullptr,
- AZ::ConsoleFunctorFlags::Null,
- "Set the number of frames to skip during the warm up and switching to the Game Mode.");
- }; // namespace TrackView
- CSequenceBatchRenderDialog::CSequenceBatchRenderDialog(float fps, QWidget* pParent /* = nullptr */)
- : QDialog(pParent)
- , m_fpsForTimeToFrameConversion(fps)
- , m_customResH(0)
- , m_customResW(0)
- , m_customFPS(0)
- , m_bFFMPEGCommandAvailable(false)
- , m_ui(new Ui::SequenceBatchRenderDialog)
- , m_renderListModel(new QStringListModel(this))
- , CV_TrackViewRenderOutputCapturing(0)
- , m_editorIdleProcessingEnabled(true)
- , m_prefixValidator(new CPrefixValidator(this))
- {
- m_ui->setupUi(this);
- setFixedSize(size());
- m_ui->m_renderList->setModel(m_renderListModel);
- OnInitDialog();
- connect(&m_renderTimer, &QTimer::timeout, this, &CSequenceBatchRenderDialog::OnKickIdleTimout);
- m_renderTimer.setInterval(0);
- m_renderTimer.setSingleShot(true);
- REGISTER_CVAR3("TrackViewRenderOutputCapturing", CV_TrackViewRenderOutputCapturing, 0, VF_NULL, "Set to 1 when Track View is actively capturing render output.");
- }
- CSequenceBatchRenderDialog::~CSequenceBatchRenderDialog()
- = default;
- void CSequenceBatchRenderDialog::reject()
- {
- if (m_renderContext.IsInRendering())
- {
- OnCancelRender();
- }
- else
- {
- QDialog::reject();
- }
- }
- void CSequenceBatchRenderDialog::OnInitDialog()
- {
- QAction* browseAction = m_ui->m_destinationEdit->addAction(style()->standardPixmap(QStyle::SP_DirOpenIcon), QLineEdit::TrailingPosition);
- connect(browseAction, &QAction::triggered, this, [=]()
- {
- const QString dir = QFileDialog::getExistingDirectory(this);
- if (!dir.isEmpty())
- {
- m_ui->m_destinationEdit->setText(dir);
- }
- });
- void(QComboBox::* activated)(int) = &QComboBox::activated;
- void(QSpinBox::* editingFinished)() = &QSpinBox::editingFinished;
- connect(m_ui->m_shotCombo, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &CSequenceBatchRenderDialog::OnDirectorChange);
- connect(m_ui->BATCH_RENDER_ADD_SEQ, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnAddRenderItem);
- connect(m_ui->BATCH_RENDER_REMOVE_SEQ, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnRemoveRenderItem);
- connect(m_ui->BATCH_RENDER_CLEAR_SEQ, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnClearRenderItems);
- connect(m_ui->m_updateBtn, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnUpdateRenderItem);
- connect(m_ui->BATCH_RENDER_LOAD_PRESET, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnLoadPreset);
- connect(m_ui->BATCH_RENDER_SAVE_PRESET, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnSavePreset);
- connect(m_ui->BATCH_RENDER_LOAD_BATCH, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnLoadBatch);
- connect(m_ui->BATCH_RENDER_SAVE_BATCH, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnSaveBatch);
- connect(m_ui->m_pGoBtn, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnGo);
- connect(m_ui->CANCEL, &QPushButton::clicked, this, &CSequenceBatchRenderDialog::OnDone);
- connect(m_ui->m_sequenceCombo, activated, this, &CSequenceBatchRenderDialog::OnSequenceSelected);
- connect(m_ui->m_fpsCombo->lineEdit(), &QLineEdit::textEdited, this, &CSequenceBatchRenderDialog::OnFPSEditChange);
- connect(m_ui->m_fpsCombo, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &CSequenceBatchRenderDialog::OnFPSChange);
- connect(m_ui->m_renderList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &CSequenceBatchRenderDialog::OnRenderItemSelChange);
- connect(m_ui->m_resolutionCombo, activated, this, &CSequenceBatchRenderDialog::OnResolutionSelected);
- connect(m_ui->m_startFrame, editingFinished, this, &CSequenceBatchRenderDialog::OnStartFrameChange);
- connect(m_ui->m_endFrame, editingFinished, this, &CSequenceBatchRenderDialog::OnEndFrameChange);
- connect(m_ui->m_imageFormatCombo, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &CSequenceBatchRenderDialog::OnImageFormatChange);
- connect(m_ui->m_cvarsEdit,&QTextEdit::textChanged, this, &CSequenceBatchRenderDialog::OnVarsChange);
- connect(m_ui->BATCH_RENDER_FILE_PREFIX, &QLineEdit::textChanged, this, &CSequenceBatchRenderDialog::OnPrefixChange);
- connect(m_ui->m_disableDebugInfoCheckBox, &QCheckBox::toggled, this, &CSequenceBatchRenderDialog::OnDisableDebugInfoChange);
- connect(m_ui->m_createVideoCheckBox, &QCheckBox::toggled, this, &CSequenceBatchRenderDialog::OnCreateVideoChange);
- const int bigEnoughNumber = 1000000;
- m_ui->m_startFrame->setRange(0, bigEnoughNumber);
- m_ui->m_endFrame->setRange(0, bigEnoughNumber);
- // Fill the sequence combo box.
- bool activeSequenceWasSet = false;
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- for (int k = 0; k < movieSystem->GetNumSequences(); ++k)
- {
- IAnimSequence* pSequence = movieSystem->GetSequence(k);
- m_ui->m_sequenceCombo->addItem(pSequence->GetName());
- if (pSequence->IsActivated())
- {
- m_ui->m_sequenceCombo->setCurrentIndex(k);
- activeSequenceWasSet = true;
- }
- }
- }
- if (!activeSequenceWasSet)
- {
- m_ui->m_sequenceCombo->setCurrentIndex(0);
- }
- m_ui->m_fpsCombo->setEditable(true);
- // Fill the shot combos and the default frame range.
- OnSequenceSelected();
- // Fill the resolution combo box.
- for (int i = 0; i < arraysize(resolutions); ++i)
- {
- if (resolutions[i][0] == g_useActiveViewportResolution && resolutions[i][1] == g_useActiveViewportResolution)
- {
- m_ui->m_resolutionCombo->addItem(tr("Active View Resolution"));
- StashActiveViewportResolution(); // render dialog is modal, so we can stash the viewport res on init
- }
- else
- {
- m_ui->m_resolutionCombo->addItem(tr("%1 x %2").arg(resolutions[i][0]).arg(resolutions[i][1]));
- }
- }
- m_ui->m_resolutionCombo->addItem(tr("Custom..."));
- m_ui->m_resolutionCombo->setCurrentIndex(0);
- // Fill the FPS combo box.
- for (int i = 0; i < AZStd::size(fpsOptions); ++i)
- {
- m_ui->m_fpsCombo->addItem(fpsOptions[i].fpsDesc);
- }
- m_ui->m_fpsCombo->setCurrentIndex(0);
- // Fill the image format combo box.
- for (int i = 0; i < AZStd::size(imageFormatExtensions); ++i)
- {
- m_ui->m_imageFormatCombo->addItem(imageFormatExtensions[i]);
- }
- m_ui->m_imageFormatCombo->setCurrentIndex(0);
- m_ui->BATCH_RENDER_FILE_PREFIX->setText("Frame");
- m_ui->BATCH_RENDER_FILE_PREFIX->setValidator(m_prefixValidator.data());
- m_ui->m_progressStatusMsg->setText("Not running");
- m_ui->BATCH_RENDER_REMOVE_SEQ->setEnabled(false);
- m_ui->m_pGoBtn->setEnabled(false);
- m_ui->m_pGoBtn->setIcon(QPixmap(":/Trackview/clapperboard_ready.png"));
- m_ui->m_progressBar->setRange(0, 100);
- m_ui->BATCH_RENDER_FRAME_IN_FPS->setText(tr("In %1 FPS").arg(static_cast<int>(m_fpsForTimeToFrameConversion)));
- m_bFFMPEGCommandAvailable = GetIEditor()->GetICommandManager()->IsRegistered("plugin", "ffmpeg_encode");
- m_ffmpegPluginStatusMsg = m_bFFMPEGCommandAvailable ?
- QString("") :
- tr("FFMPEG plug-in isn't found(creating a video isn't supported).");
- m_ui->BATCH_RENDER_PRESS_ESC_TO_CANCEL->setText(m_ffmpegPluginStatusMsg);
- // Disable the create video checkbox if the ffmpeg command is not available
- if (!m_bFFMPEGCommandAvailable)
- {
- m_ui->m_createVideoCheckBox->setChecked(false);
- m_ui->m_createVideoCheckBox->setEnabled(false);
- }
- // Load previously saved options, if any.
- QString defaultPresetPath = Path::GetUserSandboxFolder();
- defaultPresetPath += defaultPresetFilename;
- if (CFileUtil::FileExists(defaultPresetPath))
- {
- LoadOutputOptions(defaultPresetPath);
- }
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnRenderItemSelChange()
- {
- // Enable/disable the 'remove'/'update' button properly.
- bool bNoSelection = !m_ui->m_renderList->selectionModel()->hasSelection();
- m_ui->BATCH_RENDER_REMOVE_SEQ->setEnabled(bNoSelection ? false : true);
- CheckForEnableUpdateButton();
- if (bNoSelection)
- {
- return;
- }
- // Apply the settings of the selected one to the dialog.
- const SRenderItem& item = m_renderItems[m_ui->m_renderList->currentIndex().row()];
- // sequence
- for (int i = 0; i < m_ui->m_sequenceCombo->count(); ++i)
- {
- const QString sequenceName = m_ui->m_sequenceCombo->itemText(i);
- if (sequenceName == item.pSequence->GetName())
- {
- m_ui->m_sequenceCombo->setCurrentIndex(i);
- OnSequenceSelected();
- break;
- }
- }
- // director
- for (int i = 0; i < m_ui->m_shotCombo->count(); ++i)
- {
- const QString directorName = m_ui->m_shotCombo->itemText(i);
- if (directorName == item.pDirectorNode->GetName())
- {
- m_ui->m_shotCombo->setCurrentIndex(i);
- break;
- }
- }
- // frame range
- m_ui->m_startFrame->setValue(static_cast<int>(item.frameRange.start * m_fpsForTimeToFrameConversion));
- m_ui->m_endFrame->setValue(static_cast<int>(item.frameRange.end * m_fpsForTimeToFrameConversion));
- // folder
- m_ui->m_destinationEdit->setText(item.folder);
- // fps
- bool bFound = false;
- for (int i = 0; i < arraysize(fpsOptions); ++i)
- {
- if (item.fps == fpsOptions[i].fps)
- {
- m_ui->m_fpsCombo->setCurrentIndex(i);
- bFound = true;
- break;
- }
- }
- if (bFound == false)
- {
- m_customFPS = item.fps;
- m_ui->m_fpsCombo->setCurrentText(QString::number(item.fps));
- }
- // format
- m_ui->m_imageFormatCombo->setCurrentText(item.imageFormat);
- // prefix
- m_ui->BATCH_RENDER_FILE_PREFIX->setText(item.prefix);
- m_ui->m_disableDebugInfoCheckBox->setChecked(item.disableDebugInfo);
- // create_video
- if (m_bFFMPEGCommandAvailable)
- {
- m_ui->m_createVideoCheckBox->setChecked(item.bCreateVideo);
- }
- // resolution
- bFound = false;
- for (int i = 0; i < arraysize(resolutions); ++i)
- {
- if (item.resW == resolutions[i][0] && item.resH == resolutions[i][1])
- {
- m_ui->m_resolutionCombo->setCurrentIndex(i);
- bFound = true;
- break;
- }
- }
- if (bFound == false)
- {
- int indexOfCustomRes = arraysize(resolutions);
- const QString resText = QString::fromLatin1(customResFormat).arg(item.resW).arg(item.resH);
- m_customResW = item.resW;
- m_customResH = item.resH;
- m_ui->m_resolutionCombo->removeItem(indexOfCustomRes);
- m_ui->m_resolutionCombo->addItem(resText);
- m_ui->m_resolutionCombo->setCurrentIndex(indexOfCustomRes);
- }
- // cvars
- QString cvarsText;
- for (size_t i = 0; i < item.cvars.size(); ++i)
- {
- cvarsText += item.cvars[static_cast<int>(i)];
- cvarsText += "\r\n";
- }
- m_ui->m_cvarsEdit->setPlainText(cvarsText);
- }
- void CSequenceBatchRenderDialog::CheckForEnableUpdateButton()
- {
- bool enable = false;
- // Enable the Update button if any ui elements are changed
- // from the currently selected render item.
- if (m_ui->m_renderList->selectionModel()->hasSelection())
- {
- SRenderItem item;
- if (SetUpNewRenderItem(item))
- {
- const int index = m_ui->m_renderList->currentIndex().row();
- AZ_Assert(index >= 0 && index < m_renderItems.size(), "Render item row index %i is out of range", index);
- enable = !(m_renderItems[index] == item);
- }
- }
- m_ui->m_updateBtn->setEnabled(enable);
- }
- void CSequenceBatchRenderDialog::OnAddRenderItem()
- {
- // If there is no director node, it cannot be added.
- if (m_ui->m_shotCombo->count() == 0)
- {
- QMessageBox::critical(this, tr("Cannot add"), tr("No director available!"));
- return;
- }
- // Set up a new render item.
- SRenderItem item;
- if (SetUpNewRenderItem(item) == false)
- {
- return;
- }
- // Check a duplication before adding.
- for (size_t i = 0; i < m_renderItems.size(); ++i)
- {
- if (m_renderItems[i] == item)
- {
- QMessageBox::critical(this, tr("Cannot add"), tr("The same item already exists"));
- return;
- }
- }
- AddItem(item);
- }
- void CSequenceBatchRenderDialog::OnRemoveRenderItem()
- {
- const int index = m_ui->m_renderList->currentIndex().row();
- AZ_Assert(index != CB_ERR, "Invalid row index");
- m_ui->m_renderList->model()->removeRow(index);
- m_renderItems.erase(m_renderItems.begin() + index);
- if (m_renderItems.empty())
- {
- m_ui->BATCH_RENDER_REMOVE_SEQ->setEnabled(false);
- m_ui->m_pGoBtn->setEnabled(false);
- }
- else
- {
- m_ui->m_renderList->setCurrentIndex(m_ui->m_renderList->model()->index(0, 0));
- OnRenderItemSelChange();
- }
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnClearRenderItems()
- {
- m_ui->m_renderList->model()->removeRows(0, m_ui->m_renderList->model()->rowCount());
- m_renderItems.clear();
- m_ui->BATCH_RENDER_REMOVE_SEQ->setEnabled(false);
- m_ui->m_pGoBtn->setEnabled(false);
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnUpdateRenderItem()
- {
- const int index = m_ui->m_renderList->currentIndex().row();
- AZ_Assert(index != CB_ERR, "Invalid row index");
- // Set up a new render item.
- SRenderItem item;
- if (!SetUpNewRenderItem(item))
- {
- return;
- }
- // Check a duplication before updating.
- for (size_t i = 0; i < m_renderItems.size(); ++i)
- {
- if (m_renderItems[i] == item)
- {
- QMessageBox::critical(this, tr("Cannot update"), tr("The same item already exists!"));
- return;
- }
- }
- // Update the item.
- m_renderItems[index] = item;
- // Update the list box, too.
- m_ui->m_renderList->model()->setData(m_ui->m_renderList->model()->index(index, 0), GetCaptureItemString(item));
- m_ui->m_updateBtn->setEnabled(false);
- }
- void CSequenceBatchRenderDialog::OnLoadPreset()
- {
- QString loadPath;
- if (CFileUtil::SelectFile("Preset Files (*.preset)", Path::GetUserSandboxFolder(), loadPath))
- {
- if (LoadOutputOptions(loadPath) == false)
- {
- QMessageBox::critical(this, tr("Cannot load"), tr("The file version is different!"));
- }
- }
- }
- void CSequenceBatchRenderDialog::OnSavePreset()
- {
- QString savePath;
- if (CFileUtil::SelectSaveFile("Preset Files (*.preset)", "preset", Path::GetUserSandboxFolder(), savePath))
- {
- SaveOutputOptions(savePath);
- }
- }
- void CSequenceBatchRenderDialog::StashActiveViewportResolution()
- {
- // stash active resolution in global vars
- activeViewportWidth = resolutions[0][0];
- activeViewportHeight = resolutions[0][1];
- CViewport* activeViewport = GetIEditor()->GetActiveView();
- if (activeViewport)
- {
- activeViewport->GetDimensions(&activeViewportWidth, &activeViewportHeight);
- }
- }
- void CSequenceBatchRenderDialog::OnGo()
- {
- if (m_renderContext.IsInRendering())
- {
- OnCancelRender();
- }
- else
- {
- // Start a new batch.
- m_ui->m_pGoBtn->setText("Cancel");
- m_ui->m_pGoBtn->setIcon(QPixmap(":/Trackview/clapperboard_cancel.png"));
- // Inform the movie system that it soon will be in a batch-rendering mode.
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- movieSystem->EnableBatchRenderMode(true);
- }
- // Initialize the context.
- InitializeContext();
- // Trigger the first item.
- OnMovieEvent(IMovieListener::eMovieEvent_Stopped, nullptr);
- }
- }
- void CSequenceBatchRenderDialog::OnMovieEvent(IMovieListener::EMovieEvent event, IAnimSequence* pSequence)
- {
- if (event == IMovieListener::eMovieEvent_Stopped
- || event == IMovieListener::eMovieEvent_Aborted)
- {
- // Finalize the current one, if any.
- if (pSequence)
- {
- EnterCaptureState(CaptureState::End);
- m_renderContext.endingSequence = pSequence;
- m_renderContext.canceled = (event == IMovieListener::eMovieEvent_Aborted);
- }
- else
- {
- // This is odd, but this is the condition that starts the first item capturing
- // when the user presses the start button.
- if (m_renderItems.size() > 0)
- {
- // Setup and trigger the first time
- m_renderContext.spentTime = 0.0f;
- m_renderContext.currentItemIndex = 0;
- CaptureItemStart();
- }
- }
- }
- }
- void CSequenceBatchRenderDialog::OnDone()
- {
- if (m_renderContext.IsInRendering())
- {
- OnCancelRender();
- }
- else
- {
- // Save options when closed.
- QString defaultPresetPath = Path::GetUserSandboxFolder();
- defaultPresetPath += defaultPresetFilename;
- SaveOutputOptions(defaultPresetPath);
- reject();
- }
- }
- void CSequenceBatchRenderDialog::OnSequenceSelected()
- {
- // Get the selected sequence.
- const QString seqName = m_ui->m_sequenceCombo->currentText();
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- IAnimSequence* pSequence = movieSystem ? movieSystem->FindLegacySequenceByName(seqName.toUtf8().data()) : nullptr;
- if (pSequence)
- {
- // Adjust the frame range.
- float sFrame = pSequence->GetTimeRange().start * m_fpsForTimeToFrameConversion;
- float eFrame = pSequence->GetTimeRange().end * m_fpsForTimeToFrameConversion;
- m_ui->m_startFrame->setRange(0, static_cast<int>(eFrame));
- m_ui->m_endFrame->setRange(0, static_cast<int>(eFrame));
- // Set the default start/end frames properly.
- m_ui->m_startFrame->setValue(static_cast<int>(sFrame));
- m_ui->m_endFrame->setValue(static_cast<int>(eFrame));
- m_ui->m_shotCombo->clear();
- // Fill the shot combo box with the names of director nodes.
- for (int i = 0; i < pSequence->GetNodeCount(); ++i)
- {
- if (pSequence->GetNode(i)->GetType() == AnimNodeType::Director)
- {
- m_ui->m_shotCombo->addItem(pSequence->GetNode(i)->GetName());
- }
- }
- }
- m_ui->m_shotCombo->setCurrentIndex(0);
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnFPSEditChange()
- {
- const QString fpsText = m_ui->m_fpsCombo->currentText();
- bool ok;
- const int fps = fpsText.toInt(&ok);
- bool bInvalidInput = !ok || fps <= 0;
- if (bInvalidInput)
- {
- m_ui->m_fpsCombo->setCurrentIndex(0);
- }
- else
- {
- m_customFPS = fps;
- }
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnFPSChange(int itemIndex)
- {
- m_customFPS = fpsOptions[itemIndex].fps;
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnDirectorChange([[maybe_unused]] int itemIndex)
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnImageFormatChange()
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnResolutionSelected()
- {
- int indexOfCustomRes = arraysize(resolutions);
- if (m_ui->m_resolutionCombo->currentIndex() == indexOfCustomRes)
- {
- int defaultW;
- int defaultH;
- const QString currentCustomResText = m_ui->m_resolutionCombo->currentText();
- GetResolutionFromCustomResText(currentCustomResText.toStdString().c_str(), defaultW, defaultH);
- CCustomResolutionDlg resDlg(defaultW, defaultH, this);
- if (resDlg.exec() == QDialog::Accepted)
- {
- const int maxRes = 8192;
- m_customResW = min(resDlg.GetWidth(), maxRes);
- m_customResH = min(resDlg.GetHeight(), maxRes);
- const QString resText = QString(customResFormat).arg(m_customResW).arg(m_customResH);
- m_ui->m_resolutionCombo->setItemText(indexOfCustomRes, resText);
- m_ui->m_resolutionCombo->setCurrentIndex(indexOfCustomRes);
- }
- else
- {
- m_ui->m_resolutionCombo->setCurrentIndex(0);
- }
- }
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::SaveOutputOptions(const QString& pathname) const
- {
- XmlNodeRef batchRenderOptionsNode = XmlHelpers::CreateXmlNode("batchrenderoptions");
- batchRenderOptionsNode->setAttr("version", kBatchRenderFileVersion);
- // Resolution
- XmlNodeRef resolutionNode = batchRenderOptionsNode->newChild("resolution");
- resolutionNode->setAttr("cursel", m_ui->m_resolutionCombo->currentIndex());
- if (m_ui->m_resolutionCombo->currentIndex() == arraysize(resolutions))
- {
- const QString resText = m_ui->m_resolutionCombo->currentText();
- resolutionNode->setContent(resText.toUtf8().data());
- }
- // FPS
- XmlNodeRef fpsNode = batchRenderOptionsNode->newChild("fps");
- fpsNode->setAttr("cursel", m_ui->m_fpsCombo->currentIndex());
- const QString fpsText = m_ui->m_fpsCombo->currentText();
- if (m_ui->m_fpsCombo->currentIndex() == -1 || m_ui->m_fpsCombo->findText(fpsText) == -1)
- {
- fpsNode->setContent(fpsText.toUtf8().data());
- }
- // Capture options (format, buffer, prefix, create_video)
- XmlNodeRef imageNode = batchRenderOptionsNode->newChild("image");
- imageNode->setAttr("format", m_ui->m_imageFormatCombo->currentIndex() % arraysize(imageFormatExtensions));
- const QString prefix = m_ui->BATCH_RENDER_FILE_PREFIX->text();
- imageNode->setAttr("prefix", prefix.toUtf8().data());
- bool disableDebugInfo = m_ui->m_disableDebugInfoCheckBox->isChecked();
- imageNode->setAttr("disabledebuginfo", disableDebugInfo);
- bool bCreateVideoOn = m_ui->m_createVideoCheckBox->isChecked();
- imageNode->setAttr("createvideo", bCreateVideoOn);
- // Custom configs
- XmlNodeRef cvarsNode = batchRenderOptionsNode->newChild("cvars");
- const QStringList lines = m_ui->m_cvarsEdit->toPlainText().split(QStringLiteral("\n"));
- for (const QString& line : lines)
- {
- cvarsNode->newChild("cvar")->setContent(line.toUtf8().data());
- }
- // Destination
- XmlNodeRef destinationNode = batchRenderOptionsNode->newChild("destination");
- const QString destinationText = m_ui->m_destinationEdit->text();
- destinationNode->setContent(destinationText.toUtf8().data());
- batchRenderOptionsNode->saveToFile(pathname.toUtf8().data());
- }
- bool CSequenceBatchRenderDialog::GetResolutionFromCustomResText(const char* customResText, int& retCustomWidth, int& retCustomHeight) const
- {
- // initialize to first resolution preset as default if the sscanf below doesn't scan values successfully
- retCustomWidth = resolutions[0][0];
- retCustomHeight = resolutions[0][1];
- bool scanSuccess = false;
- int scannedWidth = retCustomWidth; // initialize with default fall-back values - they'll be overwritten in the case of a succesful sscanf below.
- int scannedHeight = retCustomHeight;
- scanSuccess = (azsscanf(customResText, "Custom(%d x %d)...", &scannedWidth, &scannedHeight) == 2);
- if (scanSuccess)
- {
- retCustomWidth = scannedWidth;
- retCustomHeight = scannedHeight;
- }
- return scanSuccess;
- }
- bool CSequenceBatchRenderDialog::LoadOutputOptions(const QString& pathname)
- {
- XmlNodeRef batchRenderOptionsNode = XmlHelpers::LoadXmlFromFile(pathname.toStdString().c_str());
- if (batchRenderOptionsNode == nullptr)
- {
- return true;
- }
- int version = 0;
- batchRenderOptionsNode->getAttr("version", version);
- if (version != kBatchRenderFileVersion)
- {
- return false;
- }
- // Resolution
- XmlNodeRef resolutionNode = batchRenderOptionsNode->findChild("resolution");
- if (resolutionNode)
- {
- int curSel = CB_ERR;
- resolutionNode->getAttr("cursel", curSel);
- if (curSel == arraysize(resolutions))
- {
- const QString customResText = resolutionNode->getContent();
- m_ui->m_resolutionCombo->setItemText(curSel, customResText);
- GetResolutionFromCustomResText(customResText.toStdString().c_str(), m_customResW, m_customResH);
- }
- m_ui->m_resolutionCombo->setCurrentIndex(curSel);
- }
- // FPS
- XmlNodeRef fpsNode = batchRenderOptionsNode->findChild("fps");
- if (fpsNode)
- {
- int curSel = -1;
- fpsNode->getAttr("cursel", curSel);
- if (curSel == -1)
- {
- m_ui->m_fpsCombo->setCurrentIndex(-1);
- m_ui->m_fpsCombo->setCurrentText(fpsNode->getContent());
- m_customFPS = QString::fromLatin1(fpsNode->getContent()).toInt();
- }
- else
- {
- m_ui->m_fpsCombo->setCurrentIndex(curSel);
- }
- }
- // Capture options (format, buffer, prefix, create_video)
- XmlNodeRef imageNode = batchRenderOptionsNode->findChild("image");
- if (imageNode)
- {
- int curSel = CB_ERR;
- imageNode->getAttr("format", curSel);
- m_ui->m_imageFormatCombo->setCurrentIndex(curSel);
- curSel = CB_ERR;
- m_ui->BATCH_RENDER_FILE_PREFIX->setText(imageNode->getAttr("prefix"));
- bool disableDebugInfo = false;
- imageNode->getAttr("disabledebuginfo", disableDebugInfo);
- m_ui->m_disableDebugInfoCheckBox->setChecked(disableDebugInfo);
- if (m_bFFMPEGCommandAvailable)
- {
- bool bCreateVideoOn = false;
- imageNode->getAttr("createvideo", bCreateVideoOn);
- m_ui->m_createVideoCheckBox->setChecked(bCreateVideoOn);
- }
- }
- // Custom configs
- XmlNodeRef cvarsNode = batchRenderOptionsNode->findChild("cvars");
- if (cvarsNode)
- {
- QString cvarsText;
- for (int i = 0; i < cvarsNode->getChildCount(); ++i)
- {
- cvarsText += cvarsNode->getChild(i)->getContent();
- if (i < cvarsNode->getChildCount() - 1)
- {
- cvarsText += QStringLiteral("\r\n");
- }
- }
- m_ui->m_cvarsEdit->setPlainText(cvarsText);
- }
- // Destination
- XmlNodeRef destinationNode = batchRenderOptionsNode->findChild("destination");
- if (destinationNode)
- {
- m_ui->m_destinationEdit->setText(destinationNode->getContent());
- }
- return true;
- }
- void CSequenceBatchRenderDialog::OnStartFrameChange()
- {
- if (m_ui->m_startFrame->value() >= m_ui->m_endFrame->value())
- {
- m_ui->m_endFrame->setValue(m_ui->m_startFrame->value() + 1);
- }
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnEndFrameChange()
- {
- if (m_ui->m_startFrame->value() >= m_ui->m_endFrame->value())
- {
- m_ui->m_startFrame->setValue(m_ui->m_endFrame->value() - 1);
- }
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::InitializeContext()
- {
- m_renderContext.currentItemIndex = 0;
- m_renderContext.spentTime = 0;
- m_renderContext.expectedTotalTime = 0;
- for (size_t i = 0; i < m_renderItems.size(); ++i)
- {
- Range rng = m_renderItems[i].frameRange;
- m_renderContext.expectedTotalTime += rng.end - rng.start;
- }
- m_renderContext.captureOptions.once = false;
- m_ui->BATCH_RENDER_PRESS_ESC_TO_CANCEL->setText(tr("Press ESC to cancel"));
- }
- void CSequenceBatchRenderDialog::CaptureItemStart()
- {
- const SRenderItem& renderItem = m_renderItems[m_renderContext.currentItemIndex];
- const QString renderListName =
- m_ui->m_renderList->model()->index(m_renderContext.currentItemIndex, 0).data().toString();
- static const QString reservedCharacters("/\\:*?\"<>|");
- QString renderListNameSanitized;
- for (auto chr : renderListName)
- {
- const bool isReserved = reservedCharacters.contains(chr);
- renderListNameSanitized.append(isReserved ? '-' : chr);
- }
- AZStd::string folderName;
- AzFramework::StringFunc::Path::Join(renderItem.folder.toUtf8().data(), renderListNameSanitized.toUtf8().data(), folderName);
- // If this is a relative path, prepend the @products@ folder to match where the Renderer is going
- // to dump the frame buffer image captures.
- if (AzFramework::StringFunc::Path::IsRelative(folderName.c_str()))
- {
- AZStd::string absolutePath;
- const AZStd::string assetsRoot = AZ::IO::FileIOBase::GetInstance()->GetAlias("@products@");
- AzFramework::StringFunc::Path::Join(assetsRoot.c_str(), folderName.c_str(), absolutePath);
- folderName = absolutePath;
- }
- QString finalFolder = folderName.c_str();
- int numProbeIndex = 2;
- QString probeName = finalFolder;
- while (QFileInfo::exists(probeName))
- {
- probeName = QObject::tr("%1_v%2").arg(finalFolder).arg(numProbeIndex++);
- }
- finalFolder = probeName;
- // Create a new folder before writing any files
- const bool mkdirResult = QDir().mkdir(finalFolder);
- if (!mkdirResult)
- {
- TrackViewMessageBox::Critical(
- AzToolsFramework::GetActiveWindow(),
- QString(),
- QObject::tr("Cannot create directory %1 for output frames").arg(finalFolder));
- OnUpdateFinalize();
- return;
- }
- // Disable most of the UI in group chunks.
- // (Leave the start/cancel button and feedback elements).
- m_ui->BATCH_RENDER_LIST_GROUP_BOX->setEnabled(false);
- m_ui->BATCH_RENDER_INPUT_GROUP_BOX->setEnabled(false);
- m_ui->BATCH_RENDER_OUTPUT_GROUP_BOX->setEnabled(false);
- m_renderContext.canceled = false;
- CV_TrackViewRenderOutputCapturing = 1;
-
- m_renderContext.captureOptions.timeStep = 1.0f / renderItem.fps;
-
- // Set up the custom config cvars for this item.
- AZ::IConsole* console = AZ::Interface<AZ::IConsole>::Get();
- AZ_Assert(console, "CSequenceBatchRenderDialog requires an IConsole interface but no instance has been created.");
- if (console)
- {
- for (const auto& cvar : renderItem.cvars)
- {
- console->PerformCommand(cvar.toUtf8().data());
- }
- }
- // Set specific capture options for this item.
- m_renderContext.captureOptions.prefix = renderItem.prefix.toUtf8().data();
- m_renderContext.captureOptions.folder = finalFolder.toUtf8().data();
- // Adjust the viewport resolution
- if (CLayoutViewPane* viewPane = MainWindow::instance()->GetActiveView())
- {
- const QRect& viewportRect = viewPane->GetViewport()->rect();
- activeViewportWidth = viewportRect.width();
- activeViewportHeight = viewportRect.height();
- const int renderWidth = getResWidth(renderItem.resW);
- const int renderHeight = getResHeight(renderItem.resH);
- viewPane->ResizeViewport(renderWidth, renderHeight);
- }
- // Turn off debug info if requested
- ICVar* cvarDebugInfo = gEnv->pConsole->GetCVar("r_DisplayInfo");
- if (cvarDebugInfo)
- {
- // cache the current value to restore during OnCaptureItemEnd()
- m_renderContext.cvarDisplayInfoBU = cvarDebugInfo->GetIVal();
- if (renderItem.disableDebugInfo && cvarDebugInfo->GetIVal())
- {
- const int DISPLAY_INFO_OFF = 0;
- cvarDebugInfo->Set(DISPLAY_INFO_OFF);
- }
- }
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- movieSystem->EnableFixedStepForCapture(m_renderContext.captureOptions.timeStep);
- }
- // The capturing doesn't actually start here. It just flags the warming-up and
- // once it's done, then the capturing really begins.
- // The warming-up is necessary to settle down some post-fxs after the resolution change.
- EnterCaptureState(CaptureState::WarmingUpAfterResChange);
- m_renderTimer.start();
- }
- void CSequenceBatchRenderDialog::OnUpdateWarmingUpAfterResChange()
- {
- UpdateSpinnerProgressMessage("Warming up");
- // Spend the given frames warming up after frame buffer resolution change
- if (m_renderContext.framesSpentInCurrentPhase++ >= TrackView::tv_SkipFramesCount)
- {
- // We will handle the idle tick manually now because calling Game Update directly.
- SetEnableEditorIdleProcessing(false);
- GetIEditor()->SetInGameMode(true);
- EnterCaptureState(CaptureState::EnteringGameMode);
- }
- }
- void CSequenceBatchRenderDialog::OnUpdateEnteringGameMode()
- {
- UpdateSpinnerProgressMessage("Entering game mode");
- GetIEditor()->GetGameEngine()->Update();
- // Pause the movie player on the first frame
- if (m_renderContext.framesSpentInCurrentPhase++ == 0)
- {
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- movieSystem->Pause();
- }
- }
- // Spend the given frames warming up after changing to game mode.
- else if (m_renderContext.framesSpentInCurrentPhase++ > TrackView::tv_SkipFramesCount)
- {
- EnterCaptureState(CaptureState::BeginPlayingSequence);
- }
- }
- void CSequenceBatchRenderDialog::OnUpdateBeginPlayingSequence()
- {
- UpdateSpinnerProgressMessage("Begin Playing Sequence");
- SRenderItem& renderItem = m_renderItems[m_renderContext.currentItemIndex];
- const AZStd::string seqName = renderItem.seqName.toUtf8().data();
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- AZ_Assert(movieSystem, "Cannot get IMovieSystem");
-
- renderItem.pSequence = movieSystem->FindLegacySequenceByName(seqName.c_str());
- AZ_Assert(renderItem.pSequence, "Cannot find sequence by name %s", seqName.c_str());
- // Initialize the next one for the batch rendering.
- // Set the active shot.
- m_renderContext.pActiveDirectorBU = renderItem.pSequence->GetActiveDirector();
- renderItem.pSequence->SetActiveDirector(renderItem.pDirectorNode);
- // Back up flags and range of the sequence.
- m_renderContext.flagBU = renderItem.pSequence->GetFlags();
- m_renderContext.rangeBU = renderItem.pSequence->GetTimeRange();
- // Change flags and range of the sequence so that it automatically starts
- // once the game mode kicks in with the specified range.
- renderItem.pSequence->SetFlags(m_renderContext.flagBU | IAnimSequence::eSeqFlags_PlayOnReset);
- // Set the time range for this render, back it up 1 frame so the capture will start
- // exactly on the first frame.
- Range newRange = renderItem.frameRange;
- newRange.start -= m_renderContext.captureOptions.timeStep;
- renderItem.pSequence->SetTimeRange(newRange);
- m_renderContext.captureOptions.duration = newRange.end - newRange.start;
- if (movieSystem)
- {
- movieSystem->AddSequence(renderItem.pSequence);
- [[maybe_unused]] const bool listenerAdded = movieSystem->AddMovieListener(renderItem.pSequence, this);
- AZ_Assert(
- listenerAdded, "Failed to add movie listener for sequence %s", renderItem.pSequence->GetSequenceEntityId().ToString().c_str());
- movieSystem->Reset(true, false);
- }
- // Start the sequence playing
- if (movieSystem)
- {
- movieSystem->SetPlayingTime(renderItem.pSequence, newRange.start);
- }
- EnterCaptureState(CaptureState::Capturing);
- }
- void CSequenceBatchRenderDialog::OnUpdateCapturing()
- {
- IAnimSequence* pCurSeq = m_renderItems[m_renderContext.currentItemIndex].pSequence;
- // Make sure we are still in game mode if we are capturing, so we can never
- // get soft locked if we somehow leave game mode without this module knowing about it.
- if (!GetIEditor()->IsInGameMode())
- {
- m_renderContext.endingSequence = pCurSeq;
- m_renderContext.canceled = true;
- EnterCaptureState(CaptureState::End);
- return;
- }
- // Progress bar
- Range rng = pCurSeq->GetTimeRange();
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
-
- float elapsedTime = movieSystem ? movieSystem->GetPlayingTime(pCurSeq) - rng.start : 0.f;
- const int percentage
- = static_cast<int>(100.0f * (m_renderContext.spentTime + elapsedTime) / m_renderContext.expectedTotalTime);
- m_ui->m_progressBar->setValue(percentage);
- // Progress message
- const QString itemText = m_ui->m_renderList->model()->index(m_renderContext.currentItemIndex, 0).data().toString();
- const QString msg = tr("Rendering '%1'...(%2%)").arg(itemText).arg(static_cast<int>(100.0f * elapsedTime / (rng.end - rng.start)));
- UpdateSpinnerProgressMessage(msg.toLatin1().data());
- m_renderContext.framesSpentInCurrentPhase++;
- }
- void CSequenceBatchRenderDialog::OnUpdateEnd(IAnimSequence* sequence)
- {
- // Restore flags, range and the active director of the sequence.
- sequence->SetFlags(m_renderContext.flagBU);
- sequence->SetTimeRange(m_renderContext.rangeBU);
- sequence->SetActiveDirector(m_renderContext.pActiveDirectorBU);
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- movieSystem->DisableFixedStepForCapture();
- // Important: End batch render mode BEFORE leaving Game Mode.
- // Otherwise track view will set the active camera based on the directors in the current sequence while leaving game mode
- movieSystem->EnableBatchRenderMode(false);
- movieSystem->RemoveMovieListener(sequence, this);
- }
- GetIEditor()->SetInGameMode(false);
- GetIEditor()->GetGameEngine()->Update(); // Update is needed because SetInGameMode() queues game mode, Update() executes it.
- if (CLayoutViewPane* viewPane = MainWindow::instance()->GetActiveView())
- {
- viewPane->ResizeViewport(activeViewportWidth, activeViewportHeight);
- }
- // Restore display debug info
- ICVar* cvarDebugInfo = gEnv->pConsole->GetCVar("r_DisplayInfo");
- if (cvarDebugInfo)
- {
- cvarDebugInfo->Set(m_renderContext.cvarDisplayInfoBU);
- }
- const SRenderItem& renderItem = m_renderItems[m_renderContext.currentItemIndex];
- if (m_bFFMPEGCommandAvailable && renderItem.bCreateVideo)
- {
- // Create a video using the ffmpeg plug-in from captured images.
- m_renderContext.processingFFMPEG = true;
- const AZStd::string outputFolder = m_renderContext.captureOptions.folder;
- const AZStd::string imageFormat = m_ui->m_imageFormatCombo->currentText().toStdString().c_str();
- AZStd::string outputFile;
- AzFramework::StringFunc::Path::Join(outputFolder.c_str(), renderItem.prefix.toUtf8().data(), outputFile);
- // Create the input file string, leave the %06d unexpanded for the ffmpeg tool.
- const AZStd::string inputFile = outputFile + "_%06d." + imageFormat;
- outputFile += ".webm";
- static const char* filePattern = "__input_file__";
- QString command = AZStd::string::format(
- "plugin.ffmpeg_encode '%s' '%s' '%s' %i %i 'crop=%i:%i:0:0'",
- filePattern,
- outputFile.c_str(),
- "libvpx-vp9",
- 10240,
- renderItem.fps,
- getResWidth(renderItem.resW),
- getResHeight(renderItem.resH)).c_str();
- command = command.replace(filePattern, inputFile.c_str());
- auto future = QtConcurrent::run([command]
- {
- // Run the command
- GetIEditor()->ExecuteCommand(command);
- });
- // Use a watcher to set a flag when the ffmpeg processing is complete.
- connect(&m_renderContext.processingFFMPEGWatcher, &QFutureWatcher<void>::finished, this, [this]()
- {
- m_renderContext.processingFFMPEG = false;
- });
- m_renderContext.processingFFMPEGWatcher.setFuture(future);
- EnterCaptureState(CaptureState::FFMPEGProcessing);
- }
- else
- {
- EnterCaptureState(CaptureState::Finalize);
- }
- }
- void CSequenceBatchRenderDialog::OnUpdateFFMPEGProcessing()
- {
- UpdateSpinnerProgressMessage("FFMPEG processing");
- if (!m_renderContext.processingFFMPEG)
- {
- EnterCaptureState(CaptureState::Finalize);
- }
- }
- void CSequenceBatchRenderDialog::OnUpdateFinalize()
- {
- SetEnableEditorIdleProcessing(true);
- m_renderTimer.stop();
- // Turn disabled UI elements back on
- m_ui->BATCH_RENDER_LIST_GROUP_BOX->setEnabled(true);
- m_ui->BATCH_RENDER_INPUT_GROUP_BOX->setEnabled(true);
- m_ui->BATCH_RENDER_OUTPUT_GROUP_BOX->setEnabled(true);
- m_renderContext.frameNumber = 0;
- m_renderContext.capturingFrame = false;
- m_atomOutputFrameCapture.DestroyPipeline(*TrackView::SceneFromGameEntityContext());
- // Check to see if there is more items to process
- bool done = m_renderContext.currentItemIndex == m_renderItems.size() - 1;
- if (done)
- {
- // Update end the batch message
- if (m_renderContext.canceled)
- {
- m_ui->m_progressBar->setValue(0);
- m_ui->m_progressStatusMsg->setText(tr("Rendering canceled"));
- }
- else
- {
- m_ui->m_progressBar->setValue(100);
- m_ui->m_progressStatusMsg->setText(tr("Rendering finished"));
- }
- m_ui->m_pGoBtn->setText(tr("Start"));
- m_ui->m_pGoBtn->setIcon(QPixmap(":/Trackview/clapperboard_ready.png"));
- m_renderContext.currentItemIndex = -1;
- m_ui->BATCH_RENDER_PRESS_ESC_TO_CANCEL->setText(m_ffmpegPluginStatusMsg);
- CV_TrackViewRenderOutputCapturing = 0;
- EnterCaptureState(CaptureState::Idle);
- }
- else
- {
- // Update the context.
- m_renderContext.spentTime += m_renderContext.captureOptions.duration;
- ++m_renderContext.currentItemIndex;
- // Trigger the next item.
- CaptureItemStart();
- }
- }
- void CSequenceBatchRenderDialog::OnKickIdleTimout()
- {
- OnKickIdle();
- if (m_renderContext.IsInRendering())
- {
- m_renderTimer.start();
- }
- else
- {
- // All done with our custom OnKickIdle, restore editor idle.
- SetEnableEditorIdleProcessing(true);
- }
- //When we disable the editor idle processing. system tick is no longer invoked.
- //so we call it here to ensure rendering + other systems are updated.
- if (!m_editorIdleProcessingEnabled)
- {
- AZ::ComponentApplication* componentApplication = nullptr;
- AZ::ComponentApplicationBus::BroadcastResult(componentApplication, &AZ::ComponentApplicationRequests::GetApplication);
- if (componentApplication)
- {
- componentApplication->TickSystem();
- }
- }
- }
- void CSequenceBatchRenderDialog::OnKickIdle()
- {
- if (m_renderContext.captureState == CaptureState::WarmingUpAfterResChange)
- {
- OnUpdateWarmingUpAfterResChange();
- }
- else if (m_renderContext.captureState == CaptureState::EnteringGameMode)
- {
- OnUpdateEnteringGameMode();
- }
- else if (m_renderContext.captureState == CaptureState::BeginPlayingSequence)
- {
- OnUpdateBeginPlayingSequence();
- }
- else if (m_renderContext.captureState == CaptureState::Capturing)
- {
- OnUpdateCapturing();
- }
- else if (m_renderContext.captureState == CaptureState::End)
- {
- OnUpdateEnd(m_renderContext.endingSequence);
- m_renderContext.endingSequence = nullptr;
- }
- else if (m_renderContext.captureState == CaptureState::FFMPEGProcessing)
- {
- OnUpdateFFMPEGProcessing();
- }
- else if (m_renderContext.captureState == CaptureState::Finalize)
- {
- OnUpdateFinalize();
- }
- else
- {
- if (!m_renderContext.IsInRendering())
- {
- CheckForEnableUpdateButton();
- }
- }
- if (GetIEditor()->IsInGameMode())
- {
- // note: the internal state may change by calling GetGameEngine()->Update() so
- // we must not cache this value
- const auto capturing = [this]
- {
- return m_renderContext.captureState == CaptureState::Capturing
- // this lags behind by one frame since we are capturing the back buffer,
- // so don't bother enabling the capture on the first frame.
- && m_renderContext.framesSpentInCurrentPhase != 0;
- };
- // if we're currently trying to capture and aren't waiting for a frame
- // capture to complete, it's possible to start the next capture
- const auto canBeginFrameCapture = [capturing, this]
- {
- return capturing() && !m_renderContext.capturingFrame;
- };
- if (canBeginFrameCapture())
- {
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- // update the time so the frame number can be calculated in StartCapture()
- IAnimSequence* sequence = m_renderItems[m_renderContext.currentItemIndex].pSequence;
- m_renderContext.captureOptions.time = movieSystem->GetPlayingTime(sequence);
- movieSystem->StartCapture(m_renderContext.captureOptions, ++m_renderContext.frameNumber);
- movieSystem->ControlCapture();
- }
- }
- // if we're not capturing or we're not currently waiting for the current frame to finish
- // being captured, it's safe to move to the next step of the main update
- if (!capturing() || !m_renderContext.capturingFrame)
- {
- const auto& renderItem = m_renderItems[m_renderContext.currentItemIndex];
- // update the view given the current camera transform and projection
- if (!m_atomOutputFrameCapture.IsCreated())
- {
- // create a new atom pipeline to capture the frames of the current sequence
- m_atomOutputFrameCapture.CreatePipeline(
- *TrackView::SceneFromGameEntityContext(), "TrackViewSequencePipeline", renderItem.resW, renderItem.resH);
- }
- UpdateAtomOutputFrameCaptureView(renderItem.resW, renderItem.resH);
- GetIEditor()->GetGameEngine()->Update(); // step update (original frame capture)
- }
- if (canBeginFrameCapture())
- {
- const AZStd::string fileName = AZStd::string::format("%s_%06d", m_renderContext.captureOptions.prefix.c_str(), m_renderContext.frameNumber);
- AZStd::string filePath;
- AzFramework::StringFunc::Path::Join(
- m_renderContext.captureOptions.folder.c_str(), fileName.c_str(), filePath, /*caseInsensitive=*/true,
- /*normalize=*/false);
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- // track view callback after each frame is captured
- const auto captureFinishedCallback = [this, movieSystem]()
- {
- m_renderContext.capturingFrame = false;
- if (movieSystem)
- {
- movieSystem->EndCapture();
- movieSystem->ControlCapture();
- }
- };
- const auto imageFormatExtension = m_ui->m_imageFormatCombo->currentText();
- // readback result callback (how the image should be captured)
- // currently only .dds and .ppm
- const auto readbackCallback = [filePath,
- imageFormatExtension](const AZ::RPI::AttachmentReadback::ReadbackResult& readbackResult) {
- const auto imageFormatExtensionUtf8 = imageFormatExtension.toUtf8();
- const auto imageFormatExtensionCstr = imageFormatExtensionUtf8.constData();
- const AZStd::string fileName = AZStd::string::format("%s.%s", filePath.c_str(), imageFormatExtensionCstr);
- if (AZ::StringFunc::Equal(imageFormatExtensionCstr, "dds"))
- {
- if (const AZ::Render::FrameCaptureOutputResult result = AZ::Render::DdsFrameCaptureOutput(fileName, readbackResult);
- result.m_errorMessage.has_value())
- {
- AZ_Printf("TrackView", "Dds frame capture failed: %s", result.m_errorMessage.value().c_str());
- }
- }
- else if (AZ::StringFunc::Equal(imageFormatExtensionCstr, "ppm"))
- {
- if (const AZ::Render::FrameCaptureOutputResult result = AZ::Render::PpmFrameCaptureOutput(fileName, readbackResult);
- result.m_errorMessage.has_value())
- {
- AZ_Printf("TrackView", "Ppm frame capture failed: %s", result.m_errorMessage.value().c_str());
- }
- }
- else
- {
- AZ_Printf("TrackView", "Image format .%s not supported", imageFormatExtensionCstr);
- }
- };
- m_renderContext.capturingFrame = m_atomOutputFrameCapture.BeginCapture(readbackCallback, captureFinishedCallback);
- }
- }
- else
- {
- // Post events, this will cause an Update tick.
- qApp->sendPostedEvents();
- }
- }
- void CSequenceBatchRenderDialog::OnCancelRender()
- {
- if (m_renderContext.captureState == CaptureState::Capturing)
- {
- // In the capturing state, abort the sequence, OnMovieEvent with an abort will fire and cause
- // the transition to CaptureState::End.
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- if (movieSystem)
- {
- movieSystem->AbortSequence(m_renderItems[m_renderContext.currentItemIndex].pSequence);
- }
- }
- else if (m_renderContext.captureState == CaptureState::EnteringGameMode)
- {
- // In the EnteringGameMode state, the movie sequences hasn't started yet, so we can't count on an
- // OnMovieEvent event to end the capture early. So transition into the End state manually.
- m_renderContext.endingSequence = m_renderItems[m_renderContext.currentItemIndex].pSequence;
- m_renderContext.canceled = true;
- EnterCaptureState(CaptureState::End);
- }
- }
- void CSequenceBatchRenderDialog::OnVarsChange()
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnFormatChange()
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnPrefixChange()
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnDisableDebugInfoChange()
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnCreateVideoChange()
- {
- CheckForEnableUpdateButton();
- }
- void CSequenceBatchRenderDialog::OnLoadBatch()
- {
- QString loadPath;
- if (CFileUtil::SelectFile("Render Batch Files (*.batch)",
- Path::GetUserSandboxFolder(), loadPath))
- {
- XmlNodeRef batchRenderListNode = XmlHelpers::LoadXmlFromFile(loadPath.toStdString().c_str());
- if (batchRenderListNode == nullptr)
- {
- return;
- }
- int version = 0;
- batchRenderListNode->getAttr("version", version);
- if (version != kBatchRenderFileVersion)
- {
- QMessageBox::critical(this, tr("Cannot load"), tr("The file version is different!"));
- return;
- }
- OnClearRenderItems();
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- for (int i = 0; i < batchRenderListNode->getChildCount(); ++i)
- {
- // Get an item.
- SRenderItem item;
- XmlNodeRef itemNode = batchRenderListNode->getChild(i);
- // sequence
- const QString seqName = itemNode->getAttr("sequence");
- item.pSequence = movieSystem ? movieSystem->FindLegacySequenceByName(seqName.toUtf8().data()) : nullptr;
- if (item.pSequence == nullptr)
- {
- QMessageBox::warning(this, tr("Sequence not found"), tr("A sequence of '%1' not found! This'll be skipped.").arg(seqName));
- continue;
- }
- // director node
- const QString directorName = itemNode->getAttr("director");
- for (int k = 0; k < item.pSequence->GetNodeCount(); ++k)
- {
- IAnimNode* pNode = item.pSequence->GetNode(k);
- if (pNode->GetType() == AnimNodeType::Director && directorName == pNode->GetName())
- {
- item.pDirectorNode = pNode;
- break;
- }
- }
- if (item.pDirectorNode == nullptr)
- {
- QMessageBox::warning(this, tr("Director node not found"), tr("A director node of '%1' not found in the sequence of '%2'! This'll be skipped.").arg(directorName).arg(seqName));
- continue;
- }
- // frame range
- itemNode->getAttr("startframe", item.frameRange.start);
- itemNode->getAttr("endframe", item.frameRange.end);
- // resolution
- itemNode->getAttr("width", item.resW);
- itemNode->getAttr("height", item.resH);
- // fps
- itemNode->getAttr("fps", item.fps);
- // prefix
- item.prefix = itemNode->getAttr("prefix");
- // create_video
- itemNode->getAttr("createvideo", item.bCreateVideo);
- // folder
- item.folder = itemNode->getAttr("folder");
- itemNode->getAttr(debugInfo, item.disableDebugInfo);
- item.imageFormat = itemNode->getAttr("format");
- // cvars
- for (int k = 0; k < itemNode->getChildCount(); ++k)
- {
- const QString cvar = itemNode->getChild(k)->getContent();
- item.cvars.push_back(cvar);
- }
- AddItem(item);
- }
- }
- }
- void CSequenceBatchRenderDialog::OnSaveBatch()
- {
- QString savePath;
- if (CFileUtil::SelectSaveFile("Render Batch Files (*.batch)", "batch",
- Path::GetUserSandboxFolder(), savePath))
- {
- XmlNodeRef batchRenderListNode = XmlHelpers::CreateXmlNode("batchrenderlist");
- batchRenderListNode->setAttr("version", kBatchRenderFileVersion);
- for (size_t i = 0; i < m_renderItems.size(); ++i)
- {
- const SRenderItem& item = m_renderItems[i];
- XmlNodeRef itemNode = batchRenderListNode->newChild("item");
- // sequence
- itemNode->setAttr("sequence", item.pSequence->GetName());
- // director node
- itemNode->setAttr("director", item.pDirectorNode->GetName());
- // frame range
- itemNode->setAttr("startframe", item.frameRange.start);
- itemNode->setAttr("endframe", item.frameRange.end);
- // resolution
- itemNode->setAttr("width", item.resW);
- itemNode->setAttr("height", item.resH);
- // fps
- itemNode->setAttr("fps", item.fps);
- // prefix
- itemNode->setAttr("prefix", item.prefix.toUtf8().data());
- // create_video
- itemNode->setAttr("createvideo", item.bCreateVideo);
- // folder
- itemNode->setAttr("folder", item.folder.toUtf8().data());
- itemNode->setAttr(debugInfo, item.disableDebugInfo);
- itemNode->setAttr("format", item.imageFormat.toUtf8().data());
- // cvars
- for (size_t k = 0; k < item.cvars.size(); ++k)
- {
- itemNode->newChild("cvar")->setContent(item.cvars[static_cast<int>(k)].toUtf8().data());
- }
- }
- XmlHelpers::SaveXmlNode(GetIEditor()->GetFileUtil(), batchRenderListNode, savePath.toStdString().c_str());
- }
- }
- bool CSequenceBatchRenderDialog::SetUpNewRenderItem(SRenderItem& item)
- {
- item.seqName = m_ui->m_sequenceCombo->currentText();
- const QString shotName = m_ui->m_shotCombo->currentText();
- // folder
- item.folder = m_ui->m_destinationEdit->text();
- if (item.folder.isEmpty())
- {
- QMessageBox::critical(this, tr("Cannot add"), tr("The output folder should be specified!"));
- return false;
- }
- // sequence
- IMovieSystem* movieSystem = AZ::Interface<IMovieSystem>::Get();
- item.pSequence = movieSystem ? movieSystem->FindLegacySequenceByName(item.seqName.toUtf8().data()) : nullptr;
- AZ_Assert(item.pSequence, "Cannot find sequence by name %s", item.seqName.toUtf8().data());
- // director
- for (int i = 0; i < item.pSequence->GetNodeCount(); ++i)
- {
- IAnimNode* pNode = item.pSequence->GetNode(i);
- if (pNode->GetType() == AnimNodeType::Director && shotName == pNode->GetName())
- {
- item.pDirectorNode = pNode;
- break;
- }
- }
- if (item.pDirectorNode == nullptr)
- {
- return false;
- }
- // frame range
- item.frameRange = Range(m_ui->m_startFrame->value() / m_fpsForTimeToFrameConversion,
- m_ui->m_endFrame->value() / m_fpsForTimeToFrameConversion);
- // fps
- if (m_ui->m_fpsCombo->currentIndex() == -1 || m_ui->m_fpsCombo->currentText() != fpsOptions[m_ui->m_fpsCombo->currentIndex()].fpsDesc)
- {
- item.fps = m_customFPS;
- }
- else
- {
- item.fps = fpsOptions[m_ui->m_fpsCombo->currentIndex()].fps;
- }
- // format
- item.imageFormat = m_ui->m_imageFormatCombo->currentText();
- // prefix
- item.prefix = m_ui->BATCH_RENDER_FILE_PREFIX->text();
- // disable debug info
- item.disableDebugInfo = m_ui->m_disableDebugInfoCheckBox->isChecked();
- // create_video
- item.bCreateVideo = m_ui->m_createVideoCheckBox->isChecked();
- // resolution
- int curResSel = m_ui->m_resolutionCombo->currentIndex();
- if (curResSel < arraysize(resolutions))
- {
- item.resW = resolutions[curResSel][0];
- item.resH = resolutions[curResSel][1];
- }
- else
- {
- item.resW = m_customResW;
- item.resH = m_customResH;
- }
- // cvars
- const QStringList lines = m_ui->m_cvarsEdit->toPlainText().split('\n');
- for (const QString& line : lines)
- {
- if (!line.isEmpty())
- {
- item.cvars.push_back(line);
- }
- }
- return true;
- }
- void CSequenceBatchRenderDialog::AddItem(const SRenderItem& item)
- {
- // Add the item.
- m_renderItems.push_back(item);
- // Add it to the list box, too.
- m_renderListModel->setStringList(m_renderListModel->stringList() << GetCaptureItemString(item));
- m_ui->m_pGoBtn->setEnabled(true);
- }
- QString CSequenceBatchRenderDialog::GetCaptureItemString(const SRenderItem& item) const
- {
- return QString::fromLatin1("%1_%2_%3-%4(%5x%6,%7)%8").arg(item.pSequence->GetName())
- .arg(item.pDirectorNode->GetName())
- .arg(int(item.frameRange.start * m_fpsForTimeToFrameConversion))
- .arg(int(item.frameRange.end * m_fpsForTimeToFrameConversion))
- .arg(getResWidth(item.resW)).arg(getResHeight(item.resH)).arg(item.fps)
- .arg(item.bCreateVideo ? "[v]" : "");
- }
- void CSequenceBatchRenderDialog::UpdateSpinnerProgressMessage(const char* description)
- {
- static int count = 0;
- const char* rotatingCursor[] = { "|", "/", "-", "\\" };
- const QString msg = tr("%1 %2").arg(description).arg(rotatingCursor[(count++) % arraysize(rotatingCursor)]);
- m_ui->m_progressStatusMsg->setText(msg);
- GetIEditor()->Notify(eNotify_OnIdleUpdate);
- }
- void CSequenceBatchRenderDialog::EnterCaptureState(CaptureState captureState)
- {
- m_renderContext.captureState = captureState;
- m_renderContext.framesSpentInCurrentPhase = 0;
- }
- void CSequenceBatchRenderDialog::SetEnableEditorIdleProcessing(bool enabled)
- {
- if (enabled && !m_editorIdleProcessingEnabled)
- {
- EditorIdleProcessingBus::Broadcast(&EditorIdleProcessing::EnableIdleProcessing);
- m_editorIdleProcessingEnabled = true;
- }
- if (!enabled && m_editorIdleProcessingEnabled)
- {
- EditorIdleProcessingBus::Broadcast(&EditorIdleProcessing::DisableIdleProcessing);
- m_editorIdleProcessingEnabled = false;
- }
- }
- void CSequenceBatchRenderDialog::UpdateAtomOutputFrameCaptureView(const int width, const int height)
- {
- const AZ::EntityId activeCameraEntityId = TrackView::ActiveCameraEntityId();
- AZ_Assert(activeCameraEntityId.IsValid(), "Active camera Entity Id is invalid");
- AZ::RPI::ViewPtr view = nullptr;
- AZ::RPI::ViewProviderBus::EventResult(view, activeCameraEntityId, &AZ::RPI::ViewProvider::GetView);
- m_atomOutputFrameCapture.UpdateView(
- TrackView::TransformFromEntityId(activeCameraEntityId),
- TrackView::ProjectionFromCameraEntityId(activeCameraEntityId, aznumeric_cast<float>(width), aznumeric_cast<float>(height)),
- view);
- }
|