33#include < scratchcpp/scratchconfiguration.h>
44#include < scratchcpp/iblocksection.h>
55#include < scratchcpp/script.h>
6+ #include < scratchcpp/sprite.h>
67#include < scratchcpp/broadcast.h>
78#include < scratchcpp/compiler.h>
89#include < scratchcpp/input.h>
@@ -258,6 +259,37 @@ void Engine::stopTarget(Target *target, VirtualMachine *exceptScript)
258259 stopScript (script);
259260}
260261
262+ void Engine::initClone (Sprite *clone)
263+ {
264+ if (!clone)
265+ return ;
266+
267+ Sprite *source = clone->cloneParent ();
268+ Target *root = clone->cloneRoot ();
269+ assert (source);
270+ assert (root);
271+
272+ if (!source || !root)
273+ return ;
274+
275+ auto it = m_cloneInitScriptsMap.find (root);
276+
277+ if (it != m_cloneInitScriptsMap.cend ()) {
278+ const auto &scripts = it->second ;
279+
280+ #ifndef NDEBUG
281+ // Since we're initializing the clone, it shouldn't have any running scripts
282+ for (const auto script : m_runningScripts)
283+ assert (script->target () != clone);
284+ #endif
285+
286+ for (auto script : scripts) {
287+ auto vm = script->start (clone);
288+ m_runningScripts.push_back (vm);
289+ }
290+ }
291+ }
292+
261293void Engine::run ()
262294{
263295 auto frameDuration = std::chrono::milliseconds (33 );
@@ -442,6 +474,7 @@ void Engine::addBroadcastScript(std::shared_ptr<Block> whenReceivedBlock, std::s
442474 auto id = findBroadcast (broadcast->name ());
443475 if (m_broadcastMap.count (id) == 1 ) {
444476 std::vector<Script *> &scripts = m_broadcastMap[id];
477+ // TODO: Do not allow adding existing scripts
445478 scripts.push_back (m_scripts[whenReceivedBlock].get ());
446479 } else {
447480 m_broadcastMap[id] = { m_scripts[whenReceivedBlock].get () };
@@ -452,6 +485,22 @@ void Engine::addBroadcastScript(std::shared_ptr<Block> whenReceivedBlock, std::s
452485 }
453486}
454487
488+ void Engine::addCloneInitScript (std::shared_ptr<Block> hatBlock)
489+ {
490+ Target *target = hatBlock->target ();
491+ Script *script = m_scripts[hatBlock].get ();
492+ auto it = m_cloneInitScriptsMap.find (target);
493+
494+ if (it == m_cloneInitScriptsMap.cend ())
495+ m_cloneInitScriptsMap[target] = { m_scripts[hatBlock].get () };
496+ else {
497+ auto &scripts = it->second ;
498+
499+ if (std::find (scripts.begin (), scripts.end (), script) == scripts.cend ())
500+ scripts.push_back (script);
501+ }
502+ }
503+
455504const std::vector<std::shared_ptr<Target>> &Engine::targets () const
456505{
457506 return m_targets;
0 commit comments