12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796 |
- /*
- * 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 <QAction>
- #include <QFileDialog>
- #include <QStringListModel>
- #include <QtConcurrent>
- // CryCommon
- #include <CryCommon/Maestro/Types/AnimNodeType.h>
- // Editor
- #include "MainWindow.h"
- #include "CustomResolutionDlg.h"
- #include "ViewPane.h"
- #include "GameEngine.h"
- #include "Include/ICommandManager.h"
- #include "CryEdit.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))
- {
- int index = m_ui->m_renderList->currentIndex().row();
- assert(index >= 0 && index < m_renderItems.size());
- 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()
- {
- int index = m_ui->m_renderList->currentIndex().row();
- assert(index != CB_ERR);
- 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()
- {
- int index = m_ui->m_renderList->currentIndex().row();
- assert(index != -1);
- // 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);
- }
|