@@ -305,9 +305,9 @@ void Engine::setBroadcasts(const std::vector<std::shared_ptr<Broadcast>> &broadc
305305}
306306
307307/* ! Returns the broadcast at index. */
308- Broadcast * Engine::broadcastAt (int index) const
308+ std::shared_ptr< Broadcast> Engine::broadcastAt (int index) const
309309{
310- return m_broadcasts[index]. get () ;
310+ return m_broadcasts[index];
311311}
312312
313313/* ! Returns the index of the broadcast with the given name. */
@@ -322,6 +322,29 @@ int Engine::findBroadcast(const std::string &broadcastName) const
322322 return -1 ;
323323}
324324
325+ /* ! Returns the index of the broadcast with the given ID. */
326+ int Engine::findBroadcastById (const std::string &broadcastId) const
327+ {
328+ int i = 0 ;
329+ for (auto broadcast : m_broadcasts) {
330+ if (broadcast->id () == broadcastId)
331+ return i;
332+ i++;
333+ }
334+ return -1 ;
335+ }
336+
337+ /* ! Registers the broadcast script. */
338+ void libscratchcpp::Engine::addBroadcastScript (std::shared_ptr<Block> whenReceivedBlock, std::shared_ptr<Broadcast> broadcast)
339+ {
340+ auto id = findBroadcast (broadcast->name ());
341+ if (m_broadcastMap.count (id) == 1 ) {
342+ std::vector<VirtualMachine *> &scripts = m_broadcastMap[id];
343+ scripts.push_back (m_scripts[whenReceivedBlock].get ());
344+ } else
345+ m_broadcastMap[id] = { m_scripts[whenReceivedBlock].get () };
346+ }
347+
325348/* ! Returns the list of targets. */
326349std::vector<std::shared_ptr<Target>> Engine::targets () const
327350{
@@ -431,6 +454,19 @@ std::shared_ptr<List> Engine::getList(std::string id)
431454 return nullptr ;
432455}
433456
457+ /* ! Returns the broadcast with the given ID. */
458+ std::shared_ptr<Broadcast> Engine::getBroadcast (std::string id)
459+ {
460+ if (id.empty ())
461+ return nullptr ;
462+
463+ int index = findBroadcastById (id);
464+ if (index != -1 )
465+ return broadcastAt (index);
466+
467+ return nullptr ;
468+ }
469+
434470/* ! Returns the entity with the given ID. \see IEntity */
435471std::shared_ptr<IEntity> Engine::getEntity (std::string id)
436472{
@@ -449,5 +485,10 @@ std::shared_ptr<IEntity> Engine::getEntity(std::string id)
449485 if (list)
450486 return std::static_pointer_cast<IEntity>(list);
451487
488+ // Broadcasts
489+ auto broadcast = getBroadcast (id);
490+ if (broadcast)
491+ return std::static_pointer_cast<IEntity>(broadcast);
492+
452493 return nullptr ;
453494}
0 commit comments