diff --git a/src/GafferUI/ViewportGadget.cpp b/src/GafferUI/ViewportGadget.cpp index e8d1f727465..50d824ba205 100644 --- a/src/GafferUI/ViewportGadget.cpp +++ b/src/GafferUI/ViewportGadget.cpp @@ -64,6 +64,8 @@ #include "boost/bind/bind.hpp" #include "boost/bind/placeholders.hpp" +#include "fmt/format.h" + #include #include #include @@ -1116,10 +1118,21 @@ std::vector< Gadget* > ViewportGadget::gadgetsAtInternal( const Imath::Box2f &ra std::vector< Gadget* > gadgets; for( const HitRecord &it : selection ) { - // We can assume that renderInternal has populated m_renderItem, so we can just index into it - // using the index passed to loadName ( reversing the increment-by-one used to avoid the reserved - // name "0" ) - gadgets.push_back( const_cast( m_renderItems[ it.name - 1 ].gadget ) ); + // We assume that `renderLayerInternal()` has populated `m_renderItem`, so we can just index into it + // using the index passed to `loadName()` (reversing the increment-by-one used to avoid the reserved + // name `0`). But we'd crash if we received out-of-range indices for any reason, so check. + const size_t index = it.name - 1; + if( index < m_renderItems.size() ) + { + gadgets.push_back( const_cast( m_renderItems[index].gadget ) ); + } + else + { + IECore::msg( + IECore::Msg::Warning, "ViewportGadget::gadgetsAtInternal", + fmt::format( "Got out of bounds Gadget index {}", index ) + ); + } } if( !gadgets.size() )