Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions meshroom/aliceVision/ExportMeshUSD.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
__version__ = "1.0"

from meshroom.core import desc
from meshroom.core.utils import VERBOSE_LEVEL


class ExportMeshUSD(desc.AVCommandLineNode):
commandLine = "aliceVision_exportMeshUSD {allParams}"
size = desc.DynamicNodeSize("input")

category = "Export"
documentation = """ Export a mesh (OBJ file) to USD format. """

inputs = [
desc.File(
name="input",
label="Input",
description="Input mesh file.",
value="",
),
desc.ChoiceParam(
name="fileType",
label="USD File Format",
description="Output USD file format.",
value="usda",
values=["usda", "usdc", "usdz"]
),
desc.ChoiceParam(
name="verboseLevel",
label="Verbose Level",
description="Verbosity level (fatal, error, warning, info, debug, trace).",
values=VERBOSE_LEVEL,
value="info",
),
]

outputs = [
desc.File(
name="output",
label="Output",
description="Path to the output file.",
value="{nodeCacheFolder}/output.{fileTypeValue}",
),
]
31 changes: 17 additions & 14 deletions meshroom/aliceVision/ExportUSD.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,25 @@ class ExportUSD(desc.AVCommandLineNode):
commandLine = "aliceVision_exportUSD {allParams}"
size = desc.DynamicNodeSize("input")

category = "Utils"
documentation = """ Export a mesh (OBJ file) to USD format. """
category = "Export"
documentation = """
Convert cameras from an SfM scene into an animated camera in USD format.
Based on the input image filenames, this node detects video sequences and creates the corresponding animated camera.
"""

inputs = [
desc.File(
name="input",
label="Input",
description="Input mesh file.",
label="Input SfMData",
description="SfMData file containing a complete SfM.",
value="",
),
desc.ChoiceParam(
name="fileType",
label="USD File Format",
description="Output USD file format.",
value="usda",
values=["usda", "usdc", "usdz"]
desc.FloatParam(
name="frameRate",
label="Camera Frame Rate",
description="Define the camera's frames per second.",
value=24.0,
range=(1.0, 60.0, 1.0),
),
desc.ChoiceParam(
name="verboseLevel",
Expand All @@ -37,8 +40,8 @@ class ExportUSD(desc.AVCommandLineNode):
outputs = [
desc.File(
name="output",
label="Output",
description="Path to the output file.",
value="{nodeCacheFolder}/output.{fileTypeValue}",
),
label="USD filename",
description="Output usd filename",
value="{nodeCacheFolder}/animated.usda",
)
]
21 changes: 21 additions & 0 deletions src/aliceVision/sfmDataIO/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ if (ALICEVISION_HAVE_ALEMBIC)
)
endif()

if (ALICEVISION_HAVE_USD)

list(APPEND sfmDataIO_files_headers
UsdExporter.hpp
)
list(APPEND sfmDataIO_files_sources
UsdExporter.cpp
)
endif()

alicevision_add_library(aliceVision_sfmDataIO
SOURCES ${sfmDataIO_files_headers} ${sfmDataIO_files_sources}
PUBLIC_LINKS
Expand All @@ -60,6 +70,17 @@ if (ALICEVISION_HAVE_ALEMBIC)
)
endif()

if (ALICEVISION_HAVE_USD)
target_link_libraries(aliceVision_sfmDataIO
PRIVATE usd
usdGeom
gf
tf
vt
sdf
)
endif()

# Unit tests

alicevision_add_test(sfmDataIO_test.cpp
Expand Down
134 changes: 134 additions & 0 deletions src/aliceVision/sfmDataIO/UsdExporter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// This file is part of the AliceVision project.
// Copyright (c) 2025 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include <aliceVision/sfmDataIO/UsdExporter.hpp>
#include <aliceVision/camera/IntrinsicScaleOffset.hpp>
#include <aliceVision/system/Logger.hpp>

#include <pxr/usd/usd/stage.h>

#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdGeom/points.h>
#include <pxr/usd/usdGeom/camera.h>

#include <pxr/base/gf/vec3f.h>
#include <pxr/base/vt/array.h>


PXR_NAMESPACE_USING_DIRECTIVE

namespace aliceVision {
namespace sfmDataIO {


UsdExporter::UsdExporter(const std::string & filename, double frameRate)
{
_stage = UsdStage::CreateNew(filename);
if (_stage)
{
ALICEVISION_THROW_ERROR("UsdStage::CreateNew failed");
}

UsdGeomXform worldPrim = UsdGeomXform::Define(_stage, SdfPath("/World"));

_stage->SetTimeCodesPerSecond(frameRate);
_stage->SetFramesPerSecond(frameRate);
_startTimeCode = std::numeric_limits<IndexT>::max();
_endTimeCode = 0;
}

void UsdExporter::terminate()
{
// If no frames have been exported, _startTimeCode will still be at its sentinel value.
// In that case, avoid writing invalid start/end time codes to the USD stage.
if (_startTimeCode == std::numeric_limits<IndexT>::max())
{
ALICEVISION_LOG_WARNING("UsdExporter::terminate called but no frames have been exported; "
"skipping start/end time code settings.");
}
else
{
_stage->SetStartTimeCode(_startTimeCode);
_stage->SetEndTimeCode(_endTimeCode);
}

_stage->Save();
}

void UsdExporter::createNewCamera(const std::string & cameraName)
{
SdfPath cameraPath("/World/" + cameraName);
UsdGeomCamera camera = UsdGeomCamera::Define(_stage, cameraPath);

UsdAttribute projectionAttr = camera.GetProjectionAttr();
projectionAttr.Set(UsdGeomTokens->perspective);

UsdGeomXformable xformable(camera);
UsdGeomXformOp motion = xformable.MakeMatrixXform();
GfMatrix4d identity(1.0);
motion.Set(identity);
}

void UsdExporter::addFrame(const std::string & cameraName, const sfmData::CameraPose & pose, const camera::Pinhole & intrinsic, IndexT frameId)
{
SdfPath cameraPath("/World/" + cameraName);
UsdGeomCamera camera = UsdGeomCamera::Get(_stage, cameraPath);

_startTimeCode = std::min(_startTimeCode, frameId);
_endTimeCode = std::max(_endTimeCode, frameId);

UsdAttribute focalLengthAttr = camera.GetFocalLengthAttr();
UsdAttribute horizontalApertureAttr = camera.GetHorizontalApertureAttr();
UsdAttribute verticalApertureAttr = camera.GetVerticalApertureAttr();
UsdAttribute horizontalApertureOffsetAttr = camera.GetHorizontalApertureOffsetAttr();
UsdAttribute verticalApertureOffsetAttr = camera.GetVerticalApertureOffsetAttr();

horizontalApertureAttr.Set(static_cast<float>(intrinsic.sensorWidth()));
verticalApertureAttr.Set(static_cast<float>(intrinsic.sensorHeight()));

UsdTimeCode t(frameId);
double pixToMillimeters = intrinsic.sensorWidth() / intrinsic.w();

horizontalApertureOffsetAttr.Set(static_cast<float>(intrinsic.getOffset().x() * pixToMillimeters), t);
verticalApertureOffsetAttr.Set(static_cast<float>(intrinsic.getOffset().y() * pixToMillimeters), t);
focalLengthAttr.Set(static_cast<float>(intrinsic.getFocalLength()), t);



//Transform sfmData pose to usd pose
Eigen::Matrix4d glTransform = Eigen::Matrix4d::Identity();
glTransform(1, 1) = -1.0;
glTransform(2, 2) = -1.0;

// Inverse the pose and change the geometric frame
Eigen::Matrix4d camera_T_world = pose.getTransform().getHomogeneous();
Eigen::Matrix4d world_T_camera = camera_T_world.inverse();
Eigen::Matrix4d world_gl_T_camera_gl = glTransform * world_T_camera * glTransform;

//Copy element by element while transposing
GfMatrix4d usdT;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
usdT[j][i] = world_gl_T_camera_gl(i, j);
}
}

//Assign pose to motion
UsdGeomXformable xformable(camera);
bool dummy = false;
std::vector<UsdGeomXformOp> xformOps = xformable.GetOrderedXformOps(&dummy);


if (!xformOps.empty()) {
UsdGeomXformOp motion = xformOps[0];
motion.Set(usdT, t);
}
}

} // namespace sfmDataIO
} // namespace aliceVision
72 changes: 72 additions & 0 deletions src/aliceVision/sfmDataIO/UsdExporter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// This file is part of the AliceVision project.
// Copyright (c) 2025 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#pragma once

#include <aliceVision/sfmData/SfMData.hpp>
#include <aliceVision/camera/Pinhole.hpp>
#include <pxr/usd/usd/stage.h>

namespace aliceVision {
namespace sfmDataIO {

/**
* @brief Export SfM data to USD (Universal Scene Description) format.
*
* The UsdExporter class provides functionality to export camera poses and intrinsics
* from AliceVision's SfM data to Pixar's USD format, enabling integration with
* USD-based pipelines and DCC applications.
*/
class UsdExporter
{
public:
/**
* @brief Construct a new USD Exporter.
*
* @param filename The output USD file path
* @param frameRate The frame rate for the animation timeline (e.g., 24.0 for 24 fps)
*/
UsdExporter(const std::string & filename, double frameRate);

/**
* @brief Create a new camera in the USD stage.
*
* Creates a USD camera primitive with the specified name. This camera
* can then be animated using addFrame().
*
* @param cameraName The unique name for the camera in the USD stage
*/
void createNewCamera(const std::string & cameraName);

/**
* @brief Add a frame of camera data (pose and intrinsics) to an existing camera.
*
* Records the camera's pose and intrinsic parameters at a specific frame,
* creating keyframe animation data in the USD file.
*
* @param cameraName The name of the camera to add the frame to
* @param pose The camera pose (position and orientation) for this frame
* @param camera The pinhole camera model containing intrinsic parameters
* @param frameId The frame index/time code for this keyframe
*/
void addFrame(const std::string & cameraName, const sfmData::CameraPose & pose, const camera::Pinhole & camera, IndexT frameId);

/**
* @brief Finalize and save the USD file.
*
* Completes the USD export process and writes the data to disk.
* Should be called after all cameras and frames have been added.
*/
void terminate();

private:
pxr::UsdStageRefPtr _stage; ///< USD stage containing the scene hierarchy
IndexT _startTimeCode; ///< First frame index in the animation timeline
IndexT _endTimeCode; ///< Last frame index in the animation timeline
};

} // namespace sfmDataIO
} // namespace aliceVision
16 changes: 14 additions & 2 deletions src/software/export/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,8 @@ if (ALICEVISION_BUILD_SFM)

# Export geometry and textures as USD
if (ALICEVISION_HAVE_USD)
alicevision_add_software(aliceVision_exportUSD
SOURCE main_exportUSD.cpp
alicevision_add_software(aliceVision_exportMeshUSD
SOURCE main_exportMeshUSD.cpp
FOLDER ${FOLDER_SOFTWARE_EXPORT}
LINKS aliceVision_system
aliceVision_cmdline
Expand All @@ -214,6 +214,18 @@ if (ALICEVISION_BUILD_SFM)
usdImaging
usdShade
)

alicevision_add_software(aliceVision_exportUSD
SOURCE main_exportUSD.cpp
FOLDER ${FOLDER_SOFTWARE_EXPORT}
LINKS aliceVision_system
aliceVision_cmdline
aliceVision_sfmData
aliceVision_sfmDataIO
Boost::program_options
Boost::boost
usd
)
endif()

# Export distortion to be used in external tools
Expand Down
Loading
Loading