Skip to content

Instantly share code, notes, and snippets.

@Riztazz
Last active December 13, 2024 10:44
Show Gist options
  • Save Riztazz/3967644d2843492bce541f25c4fdf26c to your computer and use it in GitHub Desktop.
Save Riztazz/3967644d2843492bce541f25c4fdf26c to your computer and use it in GitHub Desktop.
Variant type list helper for node spawning
template <typename... NodeTypes>
struct ViewportNodes
{
using NodeSpawner = std::function<std::shared_ptr<ImFlow::BaseNode>( ImFlow::ImNodeFlow & )>;
using NodeTypeVariants = std::variant<NodeTypes...>;
struct NodeMeta
{
NodeMeta( std::string_view name, NodeSpawner spawner )
: name( name ), spawner( spawner )
{}
std::string_view name;
NodeSpawner spawner;
};
template<std::size_t N>
using AllowedNode = std::variant_alternative_t<N, NodeTypeVariants>;
template<std::size_t... Is>
static auto generateNodeMeta( std::index_sequence<Is...> )
{
return std::array<NodeMeta, sizeof...( Is )>
{
NodeMeta
{
typeid( AllowedNode<Is> ).name(),
[]( ImFlow::ImNodeFlow & graph ) -> std::shared_ptr<ImFlow::BaseNode>
{
return graph.placeNode<AllowedNode<Is>>();
}
}...
};
}
static const std::array<NodeMeta, std::variant_size_v<NodeTypeVariants>> nodeMetas;
static std::shared_ptr<ImFlow::BaseNode> CreateNode( uint32_t index, ImFlow::ImNodeFlow & graph )
{
if ( index >= nodeMetas.size() )
return nullptr;
return nodeMetas[ index ].spawner( graph );
}
static std::string_view GetNodeName( uint32_t index )
{
// TODO: not throw, maybe an error code and expected?
if ( index >= nodeMetas.size() )
throw std::out_of_range("Invalid node index");
return nodeMetas[ index ].name;
}
};
template <typename... NodeTypes>
const std::array<typename ViewportNodes<NodeTypes...>::NodeMeta, std::variant_size_v<typename ViewportNodes<NodeTypes...>::NodeTypeVariants>>
ViewportNodes<NodeTypes...>::nodeMetas = ViewportNodes<NodeTypes...>::generateNodeMeta( std::make_index_sequence<std::variant_size_v<typename ViewportNodes<NodeTypes...>::NodeTypeVariants>>() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment