Beispiel #1
0
bool AndroidExporter::ExportMainFile(gd::Project& project,
                                     gd::String outputDir) {
  gd::String layoutFunctionDeclarations;
  gd::String functionAssignmentCode;

  for (std::size_t i = 0; i < project.GetLayoutsCount(); ++i) {
    auto layout = project.GetLayout(i);
    gd::String layoutFunctionName =
        "GDSceneEvents" +
        gd::SceneNameMangler::GetMangledSceneName(layout.GetName());

    gd::EventsCodeGenerator codeGenerator(project, layout, CppPlatform::Get());
    layoutFunctionDeclarations += "extern \"C\" int  " + layoutFunctionName +
                                  "(RuntimeContext * runtimeContext);\n";
    functionAssignmentCode += "\t\tif (scene.GetName() == \"" +
                              codeGenerator.ConvertToString(layout.GetName()) +
                              "\") function = &" + layoutFunctionName + ";\n";
  }

  gd::String mainFile = fs.ReadFile(GetAndroidProjectPath() + "/jni/main.cpp")
                            .FindAndReplace("/* GDCPP_EVENTS_DECLARATIONS */",
                                            layoutFunctionDeclarations)
                            .FindAndReplace("/* GDCPP_EVENTS_ASSIGNMENTS */",
                                            functionAssignmentCode);

  return fs.WriteToFile(outputDir + "/jni/main.cpp", mainFile);
}
Beispiel #2
0
bool AndroidExporter::ExportEventsCode(gd::Project& project,
                                       gd::String outputDir) {
  for (std::size_t i = 0; i < project.GetLayoutsCount(); ++i) {
    gd::Layout& exportedLayout = project.GetLayout(i);
    gd::String eventsOutput =
        EventsCodeGenerator::GenerateSceneEventsCompleteCode(
            project, exportedLayout, exportedLayout.GetEvents(), true);

    gd::String filename = "scene" + gd::String::From(i) + ".cpp";

    if (!fs.WriteToFile(outputDir + "/jni/" + filename, eventsOutput))
      return false;
  }

  for (std::size_t i = 0; i < project.GetExternalEventsCount(); ++i) {
    gd::ExternalEvents& externalEvents = project.GetExternalEvents(i);

    DependenciesAnalyzer analyzer(project, externalEvents);
    if (!analyzer.ExternalEventsCanBeCompiledForAScene().empty()) {
      gd::String eventsOutput =
          EventsCodeGenerator::GenerateExternalEventsCompleteCode(
              project, externalEvents, true);

      gd::String filename = "externalEvents" + gd::String::From(i) + ".cpp";

      if (!fs.WriteToFile(outputDir + "/jni/" + filename, eventsOutput))
        return false;
    }
  }

  return true;
}
Beispiel #3
0
void ChangesNotifier::OnEventsModified(
    gd::Project& game,
    gd::Layout& scene,
    bool indirectChange,
    gd::String sourceOfTheIndirectChange) const {
#if !defined(GD_NO_WX_GUI)  // Compilation is not supported when wxWidgets
                            // support is disabled.
  std::cout << "Changes occured inside " << scene.GetName() << "...";

  scene.SetRefreshNeeded();
  if (!indirectChange ||
      !game.HasExternalEventsNamed(
          sourceOfTheIndirectChange))  // Changes occured directly in the scene:
                                       // Recompile it.
  {
    scene.SetCompilationNeeded();
    CodeCompilationHelpers::CreateSceneEventsCompilationTask(game, scene);
    std::cout << "Recompilation triggered." << std::endl;
  } else {
    DependenciesAnalyzer analyzer(
        game, game.GetExternalEvents(sourceOfTheIndirectChange));
    if (analyzer.ExternalEventsCanBeCompiledForAScene() == scene.GetName()) {
      // Do nothing: Changes occured in an external event which is compiled
      // separately
      std::cout << "But nothing to do." << std::endl;
    } else {
      // Changes occurred in an external event which is directly included in the
      // scene events.
      scene.SetCompilationNeeded();
      std::cout << "Recompilation asked for later." << std::endl;
    }
  }
#endif
}
Beispiel #4
0
void TileSet::LoadResources(gd::Project &game)
{
    try
    {
        gd::ImageResource & image = dynamic_cast<gd::ImageResource&>(game.GetResourcesManager().GetResource(textureName));
        //Load the resource into a wxBitmap (IDE only) and also get its SFMLTextureWrapper
#if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
        //Force to change the working directory to make it work
        wxString oldWorkingDir = wxGetCwd();
        wxSetWorkingDirectory(wxFileName::FileName(game.GetProjectFile()).GetPath());
#endif

        m_tilesetTexture = game.GetImageManager()->GetSFMLTexture(textureName);

#if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
        wxSetWorkingDirectory(oldWorkingDir);
        if ( wxFileExists(image.GetAbsoluteFile(game)) )
        {
            m_tilesetBitmap.LoadFile(image.GetAbsoluteFile(game), wxBITMAP_TYPE_ANY);
        }
#endif

        //Readjust the m_collidable std::vector according to the number of tiles
        m_collidable.resize(GetTilesCount(), true);
    }
    catch(...)
    {
        m_tilesetTexture = std::shared_ptr<SFMLTextureWrapper>();
    }
}
Beispiel #5
0
void TileSet::LoadResources(gd::Project &game)
{
    m_dirty = true;

    if(game.GetResourcesManager().HasResource(textureName))
    {
        gd::ImageResource & image = dynamic_cast<gd::ImageResource&>(game.GetResourcesManager().GetResource(textureName));
        //Load the resource into a wxBitmap (IDE only) and also get its SFMLTextureWrapper
#if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
        //Force to change the working directory to make it work
        wxString oldWorkingDir = wxGetCwd();
        wxSetWorkingDirectory(wxFileName::FileName(game.GetProjectFile()).GetPath());
#endif

        m_tilesetTexture = game.GetImageManager()->GetSFMLTexture(textureName);

#if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
        wxSetWorkingDirectory(oldWorkingDir);
        if ( wxFileExists(image.GetAbsoluteFile(game)) )
        {
            wxBitmap bmp( image.GetAbsoluteFile(game), wxBITMAP_TYPE_ANY);
            m_tilesetBitmap = bmp;
        }
#endif
    }
    else
    {
        m_tilesetTexture = std::shared_ptr<SFMLTextureWrapper>();
    }
}
Beispiel #6
0
bool ProjectFileWriter::LoadFromFile(gd::Project & project, const gd::String & filename)
{
    //Load the XML document structure
    TiXmlDocument doc;
    if ( !doc.LoadFile(filename.ToLocale().c_str()) )
    {
        gd::String errorTinyXmlDesc = doc.ErrorDesc();
        gd::String error = _( "Error while loading :" ) + "\n" + errorTinyXmlDesc + "\n\n" +_("Make sure the file exists and that you have the right to open the file.");

        gd::LogError( error );
        return false;
    }

    #if defined(GD_IDE_ONLY)
    project.SetProjectFile(filename);
    project.SetDirty(false);
    #endif

    TiXmlHandle hdl( &doc );
    gd::SerializerElement rootElement;

    ConvertANSIXMLFile(hdl, doc, filename);

    //Load the root element
    TiXmlElement * rootXmlElement = hdl.FirstChildElement("project").ToElement();
    //Compatibility with GD <= 3.3
    if (!rootXmlElement) rootXmlElement = hdl.FirstChildElement("Project").ToElement();
    if (!rootXmlElement) rootXmlElement = hdl.FirstChildElement("Game").ToElement();
    //End of compatibility code
    gd::Serializer::FromXML(rootElement, rootXmlElement);

    //Unsplit the project
    #if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
    wxString projectPath = wxFileName::FileName(filename).GetPath();
    gd::Splitter splitter;
    splitter.Unsplit(rootElement, [&projectPath](gd::String path, gd::String name) {
        TiXmlDocument doc;
        gd::SerializerElement rootElement;

        gd::String filename = projectPath + path + "-" + MakeFileNameSafe(name);
        if (!doc.LoadFile(filename.ToLocale().c_str()))
        {
            gd::String errorTinyXmlDesc = doc.ErrorDesc();
            gd::String error = _( "Error while loading :" ) + "\n" + errorTinyXmlDesc + "\n\n" +_("Make sure the file exists and that you have the right to open the file.");

            gd::LogError(error);
            return rootElement;
        }

        TiXmlHandle hdl( &doc );
        gd::Serializer::FromXML(rootElement, hdl.FirstChildElement().ToElement());
        return rootElement;
    });
    #endif

    //Unserialize the whole project
    project.UnserializeFrom(rootElement);

    return true;
}
Beispiel #7
0
void EventsListSerialization::UpdateInstructionsFromGD31x(gd::Project & project, std::vector < gd::Instruction > & list, bool instructionsAreActions)
{
    for (unsigned int i = 0;i<list.size();++i)
    {
        gd::Instruction & instr = list[i];

        const gd::InstructionMetadata & metadata = instructionsAreActions ?
                                             MetadataProvider::GetActionMetadata(project.GetCurrentPlatform(), instr.GetType()) :
                                             MetadataProvider::GetConditionMetadata(project.GetCurrentPlatform(), instr.GetType());

        if (instr.GetType() == "VarScene" ||
            instr.GetType() == "VarSceneTxt" ||
            instr.GetType() == "VarGlobal" ||
            instr.GetType() == "VarGlobalTxt" ||
            instr.GetType() == "ModVarScene" ||
            instr.GetType() == "ModVarSceneTxt" ||
            instr.GetType() == "ModVarGlobal" ||
            instr.GetType() == "ModVarGlobalTxt" )
        {
            std::vector< gd::Expression > parameters = instr.GetParameters();
            if ( parameters.size() >= 1 ) parameters.erase(parameters.begin()+0);
            instr.SetParameters(parameters);
        }

        if (instr.GetType() == "VarSceneDef" ||
            instr.GetType() == "VarGlobalDef" ||
            instr.GetType() == "VarObjetDef" )
        {
            instr.SetParameter(1, gd::Expression("\""+instr.GetParameter(1).GetPlainString()+"\""));
        }

        //UpdateInstructionsFromGD31x(project, instr.GetSubInstructions(), instructionsAreActions);
    }
}
Beispiel #8
0
void LinkEvent::ReplaceLinkByLinkedEvents(gd::Project & project, EventsList & eventList, unsigned int indexOfTheEventInThisList)
{
    //Finding what to link to.
    const EventsList * eventsToInclude = NULL;
    gd::ExternalEvents * linkedExternalEvents = NULL;
    if ( project.HasExternalEventsNamed(GetTarget()) )
    {
        linkedExternalEvents = &project.GetExternalEvents(GetTarget());
        eventsToInclude = &project.GetExternalEvents(GetTarget()).GetEvents();
    }
    else if ( project.HasLayoutNamed(GetTarget()) ) eventsToInclude = &project.GetLayout(GetTarget()).GetEvents();

    if ( eventsToInclude != NULL )
    {
        unsigned int firstEvent = IncludeAllEvents() ? 0 : GetIncludeStart();
        unsigned int lastEvent = IncludeAllEvents() ? eventsToInclude->size() - 1 : GetIncludeEnd();

        //Check bounds
        if ( firstEvent >= eventsToInclude->size() )
        {
            std::cout << "Unable to get events from a link ( Invalid start )" << std::endl;
            linkWasInvalid = true;
            return;
        }
        if ( lastEvent >= eventsToInclude->size() )
        {
            std::cout << "Unable to get events from a link ( Invalid end )" << std::endl;
            linkWasInvalid = true;
            return;
        }
        if ( firstEvent > lastEvent )
        {
            std::cout << "Unable to get events from a link ( End is before start )" << std::endl;
            linkWasInvalid = true;
            return;
        }

        //Insert an empty event to replace the link event ( we'll delete the link event at the end )
        //( If we just erase the link event without adding a blank event to replace it,
        //the first event inserted by the link will not be preprocessed ( and it can be annoying if it require preprocessing, such as another link event ). )
        gd::EmptyEvent emptyEvent;
        eventList.InsertEvent(emptyEvent, indexOfTheEventInThisList);
        eventList.InsertEvents(*eventsToInclude, firstEvent, lastEvent, indexOfTheEventInThisList+1);

        //Delete the link event ( which is now at the end of the list of events we've just inserted )
        eventList.RemoveEvent(indexOfTheEventInThisList + 1 + static_cast<unsigned>(lastEvent-firstEvent)+1);
    }
    else
    {
        std::cout << "Unable to get events from a link." << std::endl;
        linkWasInvalid = true;

        //Delete the link event
        eventList.RemoveEvent(indexOfTheEventInThisList);
        return;
    }

    linkWasInvalid = false;
}
Beispiel #9
0
void Layout::UpdateBehaviorsSharedData(gd::Project & project)
{
    std::vector < gd::String > allBehaviorsTypes;
    std::vector < gd::String > allBehaviorsNames;

    //Search in objects for the type and the name of every behaviors.
    for (std::size_t i = 0;i<initialObjects.size();++i)
    {
        std::vector < gd::String > objectBehaviors = initialObjects[i]->GetAllBehaviorNames();
        for (unsigned int j = 0;j<objectBehaviors.size();++j)
        {
            gd::Behavior & behavior = initialObjects[i]->GetBehavior(objectBehaviors[j]);
            allBehaviorsTypes.push_back(behavior.GetTypeName());
            allBehaviorsNames.push_back(behavior.GetName());
        }
    }
    for (std::size_t i = 0;i<project.GetObjectsCount();++i)
    {
        std::vector < gd::String > objectBehaviors = project.GetObject(i).GetAllBehaviorNames();
        for (std::size_t j = 0;j<objectBehaviors.size();++j)
        {
            gd::Behavior & behavior = project.GetObject(i).GetBehavior(objectBehaviors[j]);
            allBehaviorsTypes.push_back(behavior.GetTypeName());
            allBehaviorsNames.push_back(behavior.GetName());
        }
    }

    //Create non existing shared data
    for (std::size_t i = 0;i<allBehaviorsTypes.size() && i < allBehaviorsNames.size();++i)
    {
        if ( behaviorsInitialSharedDatas.find(allBehaviorsNames[i]) == behaviorsInitialSharedDatas.end() )
        {
            std::shared_ptr<gd::BehaviorsSharedData> behaviorsSharedDatas = project.CreateBehaviorSharedDatas(allBehaviorsTypes[i]);
            if ( behaviorsSharedDatas )
            {
                behaviorsSharedDatas->SetName(allBehaviorsNames[i]);
                behaviorsInitialSharedDatas[behaviorsSharedDatas->GetName()] = behaviorsSharedDatas;
            }
        }
    }

    //Remove useless shared data:
    //First construct the list of existing shared data.
    std::vector < gd::String > allSharedData;
    for (std::map < gd::String, std::shared_ptr<gd::BehaviorsSharedData> >::const_iterator it = behaviorsInitialSharedDatas.begin();
         it != behaviorsInitialSharedDatas.end();++it)
    {
        allSharedData.push_back(it->first);
    }

    //Then delete shared data not linked to a behavior
    for (std::size_t i = 0;i<allSharedData.size();++i)
    {
        if ( std::find(allBehaviorsNames.begin(), allBehaviorsNames.end(), allSharedData[i]) == allBehaviorsNames.end() )
            behaviorsInitialSharedDatas.erase(allSharedData[i]);
    }
}
Beispiel #10
0
void ChangesNotifier::OnBehaviorEdited(gd::Project & game, gd::Layout * scene, gd::Object & object, gd::Behavior & behavior) const
{
    if ( scene )
        scene->SetRefreshNeeded();
    else //Scene pointer is not NULL: Update shared data of all scenes
    {
        for (std::size_t i = 0;i<game.GetLayoutsCount();++i)
            game.GetLayout(i).SetRefreshNeeded();
    }
}
Beispiel #11
0
void ObjectsPropgridHelper::UpdateBehaviorsSharedData(gd::Project & project, gd::Layout * scene) const
{
    if ( scene )
        scene->UpdateBehaviorsSharedData(project);
    else //Scene pointer is NULL: Update shared data of all scenes
    {
        for (std::size_t i = 0;i<project.GetLayoutsCount();++i)
            project.GetLayout(i).UpdateBehaviorsSharedData(project);
    }
}
Beispiel #12
0
void ChangesNotifier::OnAutomatismEdited(gd::Project & game, gd::Layout * scene, gd::Object & object, gd::Automatism & automatism) const
{
    if ( scene )
        scene->SetRefreshNeeded();
    else //Scene pointer is not NULL: Update shared data of all scenes
    {
        for (unsigned int i = 0;i<game.GetLayoutsCount();++i)
            game.GetLayout(i).SetRefreshNeeded();
    }
}
Beispiel #13
0
bool ProjectFileWriter::SaveToFile(const gd::Project & project, const gd::String & filename, bool forceSingleFile)
{
    //Serialize the whole project
    gd::SerializerElement rootElement;
    project.SerializeTo(rootElement);

    #if defined(GD_IDE_ONLY) && !defined(GD_NO_WX_GUI)
    if (project.IsFolderProject() && !forceSingleFile) //Optionally split the project
    {
        wxString projectPath = wxFileName::FileName(filename).GetPath();
        gd::Splitter splitter;
        auto splitElements = splitter.Split(rootElement, {
            "/layouts/layout",
            "/externalEvents/externalEvents",
            "/externalLayouts/externalLayout",
        });
        for (auto & element : splitElements)
        {
            //Create a partial XML document
            TiXmlDocument doc;
            doc.LinkEndChild(new TiXmlDeclaration("1.0", "UTF-8", ""));

            TiXmlElement * root = new TiXmlElement("projectPartial");
            doc.LinkEndChild(root);
            gd::Serializer::ToXML(element.element, root);

            //And write the element in it
            gd::String filename = projectPath + element.path + "-" + MakeFileNameSafe(element.name);
            gd::RecursiveMkDir::MkDir(wxFileName::FileName(filename).GetPath());
            if (!doc.SaveFile(filename.ToLocale().c_str()))
            {
                gd::LogError( _( "Unable to save file ") + filename + _("!\nCheck that the drive has enough free space, is not write-protected and that you have read/write permissions." ) );
                return false;
            }
        }
    }
    #endif

    //Create the main XML document
    TiXmlDocument doc;
    doc.LinkEndChild(new TiXmlDeclaration( "1.0", "UTF-8", "" ));

    TiXmlElement * root = new TiXmlElement( "project" );
    doc.LinkEndChild(root);
    gd::Serializer::ToXML(rootElement, root);

    //Write XML to file
    if ( !doc.SaveFile( filename.ToLocale().c_str() ) )
    {
        gd::LogError( _( "Unable to save file ") + filename + _("!\nCheck that the drive has enough free space, is not write-protected and that you have read/write permissions." ) );
        return false;
    }

    return true;
}
Beispiel #14
0
void Object::UnserializeFrom(gd::Project & project, const SerializerElement & element)
{
    //Name and type are already loaded.
    objectVariables.UnserializeFrom(element.GetChild("variables", 0, "Variables"));

    //Compatibility with GD <= 3.3
    if (element.HasChild("Automatism"))
    {
        for (std::size_t i = 0; i < element.GetChildrenCount("Automatism"); ++i)
        {
            SerializerElement & behaviorElement = element.GetChild("Automatism", i);

            gd::String autoType = behaviorElement.GetStringAttribute("type", "", "Type")
                .FindAndReplace("Automatism", "Behavior");
            gd::String autoName = behaviorElement.GetStringAttribute("name", "", "Name");

            Behavior* behavior = project.CreateBehavior(autoType);
            if ( behavior != NULL )
            {
                behavior->SetName(autoName);
                behavior->UnserializeFrom(behaviorElement);
                behaviors[behavior->GetName()] = behavior;
            }
            else
                std::cout << "WARNING: Unknown behavior " << autoType << std::endl;
        }
    }
    //End of compatibility code
    else
    {
        SerializerElement & behaviorsElement = element.GetChild("behaviors", 0, "automatisms");
        behaviorsElement.ConsiderAsArrayOf("behavior", "automatism");
        for (std::size_t i = 0; i < behaviorsElement.GetChildrenCount(); ++i)
        {
            SerializerElement & behaviorElement = behaviorsElement.GetChild(i);

            gd::String autoType = behaviorElement.GetStringAttribute("type")
                .FindAndReplace("Automatism", "Behavior"); //Compatibility with GD <= 4
            gd::String autoName = behaviorElement.GetStringAttribute("name");

            Behavior* behavior = project.CreateBehavior(autoType);
            if ( behavior != NULL )
            {
                behavior->SetName(autoName);
                behavior->UnserializeFrom(behaviorElement);
                behaviors[behavior->GetName()] = behavior;
            }
            else
                std::cout << "WARNING: Unknown behavior " << autoType << std::endl;
        }
    }

    DoUnserializeFrom(project, element);
}
Beispiel #15
0
std::set < std::string > EventsVariablesFinder::FindAllGlobalVariables(const gd::Platform & platform, const gd::Project & project)
{
    std::set < std::string > results;

    for (unsigned int i = 0;i<project.GetLayoutsCount();++i)
    {
        std::set < std::string > results2 = FindArgumentsInEvents(platform, project, project.GetLayout(i), project.GetLayout(i).GetEvents(), "globalvar");
        results.insert(results2.begin(), results2.end());
    }

    return results;
}
Beispiel #16
0
void RuntimeGame::LoadFromProject(const gd::Project& project) {
  // Copy inherited project
  gd::Project::operator=(project);

  variables.Merge(project.GetVariables());
  soundManager.SetResourcesManager(&GetResourcesManager());
}
Beispiel #17
0
gd::BaseEvent::EditEventReturnType CppCodeEvent::EditEvent(
    wxWindow* parent_,
    gd::Project& game_,
    gd::Layout& scene_,
    gd::MainFrameWrapper& mainFrameWrapper_) {
#if !defined(GD_NO_WX_GUI)
  EditCppCodeEvent dialog(parent_, *this, game_, scene_);
  int returned = dialog.ShowModal();

  if (returned == 0)
    return Cancelled;
  else {
    // Force recreation of the assocaited source file
    wxFileName outputFile(associatedGDManagedSourceFile);
    outputFile.MakeAbsolute(
        wxFileName::FileName(game_.GetProjectFile()).GetPath());
    if (wxFileExists(outputFile.GetFullPath()))
      wxRemoveFile(outputFile.GetFullPath());

    EnsureAssociatedSourceFileIsUpToDate(game_);

    if (returned == 2)
      return ChangesMadeButNoNeedForEventsRecompilation;
    else
      return ChangesMade;
  }
#else
  return ChangesMade;
#endif
}
Beispiel #18
0
void gd::EventsListSerialization::OpenConditions(gd::Project & project, gd::InstructionsList & conditions, const SerializerElement & elem)
{
    elem.ConsiderAsArrayOf("condition", "Condition");
    for(std::size_t i = 0; i<elem.GetChildrenCount(); ++i)
    {
        gd::Instruction instruction;
        const SerializerElement & conditionElem = elem.GetChild(i);

        instruction.SetType(conditionElem.GetChild("type", 0, "Type").GetStringAttribute("value")
                .FindAndReplace("Automatism", "Behavior")); //Compatibility with GD <= 4
        instruction.SetInverted(conditionElem.GetChild("type", 0, "Type").GetBoolAttribute("inverted", false, "Contraire"));

        //Read parameters
        vector < gd::Expression > parameters;

        //Compatibility with GD <= 3.3
        if (conditionElem.HasChild("Parametre")) {

            for (std::size_t j = 0;j<conditionElem.GetChildrenCount("Parametre");++j)
                parameters.push_back(gd::Expression(conditionElem.GetChild("Parametre", j).GetValue().GetString()));

        }
        //end of compatibility code
        else
        {
            const SerializerElement & parametersElem = conditionElem.GetChild("parameters");
            parametersElem.ConsiderAsArrayOf("parameter");
            for (std::size_t j = 0;j<parametersElem.GetChildrenCount();++j)
                parameters.push_back(gd::Expression(parametersElem.GetChild(j).GetValue().GetString()));
        }

        instruction.SetParameters( parameters );

        //Read sub conditions
        if ( conditionElem.HasChild("subConditions", "SubConditions") )
            OpenConditions(project, instruction.GetSubInstructions(), conditionElem.GetChild("subConditions", 0, "SubConditions" ));

        conditions.Insert( instruction );
    }

    if ( project.GetLastSaveGDMajorVersion() < 3 ||
         (project.GetLastSaveGDMajorVersion() == 3 && project.GetLastSaveGDMinorVersion() <= 1 ) )
        UpdateInstructionsFromGD31x(project, conditions, false);

    if ( project.GetLastSaveGDMajorVersion() < 3 )
        UpdateInstructionsFromGD2x(project, conditions, false);
}
Beispiel #19
0
void ProjectResourcesAdder::RemoveAllUselessResources(gd::Project & project)
{
    std::vector<gd::String> unusedResources = GetAllUselessResources(project);

    for(std::size_t i = 0;i < unusedResources.size();++i) {
        project.GetResourcesManager().RemoveResource(unusedResources[i]);
    }
}
Beispiel #20
0
void gd::EventsListSerialization::OpenActions(gd::Project & project, vector < gd::Instruction > & actions, const SerializerElement & elem)
{
    elem.ConsiderAsArrayOf("action", "Action");
    for(unsigned int i = 0; i<elem.GetChildrenCount(); ++i)
    {
        gd::Instruction instruction;
        const SerializerElement & actionElem = elem.GetChild(i);

        instruction.SetType( actionElem.GetChild("type", 0, "Type").GetStringAttribute("value") );

        //Read parameters
        vector < gd::Expression > parameters;

        //Compatibility with GD <= 3.3
        if (actionElem.HasChild("Parametre")) {

            for (unsigned int j = 0;j<actionElem.GetChildrenCount("Parametre");++j)
                parameters.push_back(gd::Expression(actionElem.GetChild("Parametre", j).GetValue().GetString()));

        }
        //end of compatibility code
        else
        {
            const SerializerElement & parametersElem = actionElem.GetChild("parameters");
            parametersElem.ConsiderAsArrayOf("parameter");
            for (unsigned int j = 0;j<parametersElem.GetChildrenCount();++j)
                parameters.push_back(gd::Expression(parametersElem.GetChild(j).GetValue().GetString()));
        }

        instruction.SetParameters( parameters );

        //Read sub actions
        if ( actionElem.HasChild("subActions", "SubActions") )
            OpenActions(project, instruction.GetSubInstructions(), actionElem.GetChild("subActions", 0, "SubActions" ));

        actions.push_back( instruction );
    }

    if ( project.GetLastSaveGDMajorVersion() < 3 ||
         (project.GetLastSaveGDMajorVersion() == 3 && project.GetLastSaveGDMinorVersion() <= 1 ) )
        UpdateInstructionsFromGD31x(project, actions, true);

    if ( project.GetLastSaveGDMajorVersion() < 3 )
        UpdateInstructionsFromGD2x(project, actions, true);
}
Beispiel #21
0
bool ProjectResourcesAdder::AddAllMissingImages(gd::Project & project)
{
    gd::ImagesUsedInventorizer inventorizer;
    project.ExposeResources(inventorizer);
    std::set<gd::String> & allImages = inventorizer.GetAllUsedImages();

    ResourcesManager & resourcesManager = project.GetResourcesManager();
    for (std::set<gd::String>::const_iterator it = allImages.begin(); it != allImages.end(); ++it)
    {
        if (!resourcesManager.HasResource(*it))
        {
            std::cout << "Adding missing resource \""<<*it<<"\"to the project.";
            resourcesManager.AddResource(*it, /*filename=*/*it); //Note that AddResource add a image resource by default.
        }
    }

    return true;
}
Beispiel #22
0
gd::String EventsCodeGenerator::GenerateExternalEventsCompleteCode(gd::Project & project, gd::ExternalEvents & events, bool compilationForRuntime)
{
    DependenciesAnalyzer analyzer(project, events);
    gd::String associatedSceneName = analyzer.ExternalEventsCanBeCompiledForAScene();
    if ( associatedSceneName.empty() || !project.HasLayoutNamed(associatedSceneName) )
    {
        std::cout << "ERROR: Cannot generate code for an external event: No unique associated scene." << std::endl;
        return "";
    }
    gd::Layout & associatedScene = project.GetLayout(project.GetLayoutPosition(associatedSceneName));

    gd::String output;

    //Prepare the global context ( Used to get needed header files )
    gd::EventsCodeGenerationContext context;
    EventsCodeGenerator codeGenerator(project, associatedScene);
    codeGenerator.PreprocessEventList(events.GetEvents());
    codeGenerator.SetGenerateCodeForRuntime(compilationForRuntime);

    //Generate whole events code
    gd::String wholeEventsCode = codeGenerator.GenerateEventsListCode(events.GetEvents(), context);

    //Generate default code around events:
    //Includes
    output += "#include <vector>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <SFML/System/Clock.hpp>\n#include <SFML/System/Vector2.hpp>\n#include <SFML/Graphics/Color.hpp>\n#include \"GDCpp/RuntimeContext.h\"\n#include \"GDCpp/RuntimeObject.h\"\n";
    for ( set<gd::String>::iterator include = codeGenerator.GetIncludeFiles().begin() ; include != codeGenerator.GetIncludeFiles().end(); ++include )
        output += "#include \""+*include+"\"\n";

    //Extra declarations needed by events
    for ( set<gd::String>::iterator declaration = codeGenerator.GetCustomGlobalDeclaration().begin() ; declaration != codeGenerator.GetCustomGlobalDeclaration().end(); ++declaration )
        output += *declaration+"\n";

    output +=
    codeGenerator.GetCustomCodeOutsideMain()+
    "\n"
    "void "+EventsCodeNameMangler::Get()->GetExternalEventsFunctionMangledName(events.GetName())+"(RuntimeContext * runtimeContext)\n"
    "{\n"
	+codeGenerator.GetCustomCodeInMain()
    +wholeEventsCode+
    "return;\n"
    "}\n";

    return output;
}
Beispiel #23
0
void EventsChangesNotifier::GetScenesAndExternalEventsLinkedTo(
    const gd::EventsList& events,
    gd::Project& project,
    std::vector<gd::Layout*>& layouts,
    std::vector<gd::ExternalEvents*>& externalEvents) {
  for (std::size_t i = 0; i < events.size(); ++i) {
    try {
      const gd::LinkEvent& linkEvent =
          dynamic_cast<const gd::LinkEvent&>(events[i]);

      // We've got a link event, search now linked scene/external events
      if (project.HasExternalEventsNamed(linkEvent.GetTarget())) {
        gd::ExternalEvents& linkedExternalEvents =
            project.GetExternalEvents(linkEvent.GetTarget());

        // Protect against circular references
        if (find(externalEvents.begin(),
                 externalEvents.end(),
                 &linkedExternalEvents) == externalEvents.end()) {
          externalEvents.push_back(&linkedExternalEvents);
          GetScenesAndExternalEventsLinkedTo(linkedExternalEvents.GetEvents(),
                                             project,
                                             layouts,
                                             externalEvents);
        }
      } else if (project.HasLayoutNamed(linkEvent.GetTarget())) {
        gd::Layout& linkedLayout = project.GetLayout(linkEvent.GetTarget());

        // Protect against circular references
        if (find(layouts.begin(), layouts.end(), &linkedLayout) ==
            layouts.end()) {
          layouts.push_back(&linkedLayout);
          GetScenesAndExternalEventsLinkedTo(
              linkedLayout.GetEvents(), project, layouts, externalEvents);
        }
      }
    } catch (...) {
    }

    if (events[i].CanHaveSubEvents())
      GetScenesAndExternalEventsLinkedTo(
          events[i].GetSubEvents(), project, layouts, externalEvents);
  }
}
Beispiel #24
0
void ChangesNotifier::OnObjectVariablesChanged(gd::Project & game, gd::Layout * scene, gd::Object & object) const
{
    #if !defined(GD_NO_WX_GUI) //Compilation is not supported when wxWidgets support is disabled.
    if ( scene )
        scene->SetRefreshNeeded();
    else //Scene pointer is NULL: Update shared data of all scenes
    {
        for (std::size_t i = 0;i<game.GetLayoutsCount();++i)
        {
            game.GetLayout(i).SetRefreshNeeded();
            game.GetLayout(i).SetCompilationNeeded();
        }
        for (std::size_t i = 0;i<game.GetExternalEventsCount();++i)
        {
            game.GetExternalEvents(i).SetLastChangeTimeStamp(wxDateTime::Now().GetTicks()); //Do no forget external events as they can have been compiled separately from scenes.
        }
    }
    #endif
}
Beispiel #25
0
bool ProjectFileWriter::LoadFromJSONFile(gd::Project & project, const gd::String & filename)
{
    std::ifstream ifs(filename.ToLocale().c_str());
    if (!ifs.is_open())
    {
        gd::String error = _( "Unable to open the file.") + _("Make sure the file exists and that you have the right to open the file.");
        gd::LogError(error);
        return false;
    }

    project.SetProjectFile(filename);
    project.SetDirty(false);

    std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
    gd::SerializerElement rootElement = gd::Serializer::FromJSON(str);
    project.UnserializeFrom(rootElement);

    return true;
}
Beispiel #26
0
bool MainFrame::Save(gd::Project & project, wxString file)
{
    bool isJSON = file.EndsWith(".json");
    bool success =
        (!isJSON && gd::ProjectFileWriter::SaveToFile(project, file)) ||
        (isJSON  && gd::ProjectFileWriter::SaveToJSONFile(project, file));

    SetLastUsedFile(project.GetProjectFile());
    return success;
}
Beispiel #27
0
void ChangesNotifier::OnEventsModified(
    gd::Project& game,
    gd::ExternalEvents& events,
    bool indirectChange,
    gd::String sourceOfTheIndirectChange) const {
#if !defined(GD_NO_WX_GUI)  // Compilation is not supported when wxWidgets
                            // support is disabled.
  DependenciesAnalyzer analyzer(game, events);
  gd::String associatedScene = analyzer.ExternalEventsCanBeCompiledForAScene();
  bool externalEventsAreCompiledSeparately = !associatedScene.empty();

  if (!externalEventsAreCompiledSeparately) return;

  std::cout << "Changes occured inside " << events.GetName()
            << " (compiled separately)..." << std::endl;

  // The external events are compiled separately from the scene events:
  // We need to recompile them if the changes occured inside them.

  if (!indirectChange ||
      !game.HasExternalEventsNamed(sourceOfTheIndirectChange)) {
    // Changes occurred directly inside the external events: We need to
    // recompile them
    events.SetLastChangeTimeStamp(wxDateTime::Now().GetTicks());
    CodeCompilationHelpers::CreateExternalEventsCompilationTask(game, events);
    std::cout << "Recompilation triggered." << std::endl;
  } else {
    DependenciesAnalyzer analyzer(
        game, game.GetExternalEvents(sourceOfTheIndirectChange));
    if (analyzer.ExternalEventsCanBeCompiledForAScene() == associatedScene) {
      // Do nothing: Changes occurred in an external event which is compiled
      // separately
      std::cout << "But nothing to do." << std::endl;
    } else {
      // Changes occurred in an another external event which is directly
      // included in our external events.
      events.SetLastChangeTimeStamp(wxDateTime::Now().GetTicks());
      CodeCompilationHelpers::CreateExternalEventsCompilationTask(game, events);
      std::cout << "Recompilation triggered." << std::endl;
    }
  }
#endif
}
void GD_API CodeCompilationHelpers::CreateExternalSourceFileCompilationTask(gd::Project & game, SourceFile & file, gd::Layout * scene)
{
    CodeCompilerTask task;

    wxFileName inputFile(file.GetFileName());
    inputFile.MakeAbsolute(wxFileName::FileName(game.GetProjectFile()).GetPath());
    task.compilerCall.inputFile = ToString(inputFile.GetFullPath());
    task.compilerCall.outputFile = string(CodeCompiler::Get()->GetOutputDirectory()+"GD"+ToString(&file)+"ObjectFile.o");
    task.compilerCall.compilationForRuntime = false;
    task.compilerCall.optimize = false;
    task.compilerCall.eventsGeneratedCode = false;
    task.compilerCall.extraHeaderDirectories.push_back(ToString(wxFileName::FileName(game.GetProjectFile()).GetPath()));

    task.scene = scene;
    if ( scene ) task.postWork = std::shared_ptr<CodeCompilerExtraWork>(new SourceFileCodeCompilerPostWork(scene));

    task.userFriendlyName = "Compilation of file "+file.GetFileName();

    CodeCompiler::Get()->AddTask(task);
}
gd::String Resource::GetAbsoluteFile(const gd::Project & project) const
{
#if !defined(GD_NO_WX_GUI)
    wxString projectDir = wxFileName::FileName(project.GetProjectFile()).GetPath();
    wxFileName filename = wxFileName::FileName(GetFile());
    filename.MakeAbsolute(projectDir);
    return filename.GetFullPath();
#else
    gd::LogWarning("BAD USE: Resource::GetAbsoluteFile called when compiled with no support for wxWidgets");
    return GetFile();
#endif
}
Beispiel #30
0
void GD_CORE_API ProjectStripper::StripProjectForExport(gd::Project& project) {
  project.GetObjectGroups().Clear();
  while (project.GetExternalEventsCount() > 0)
    project.RemoveExternalEvents(project.GetExternalEvents(0).GetName());

  for (unsigned int i = 0; i < project.GetLayoutsCount(); ++i) {
    project.GetLayout(i).GetObjectGroups().Clear();
    project.GetLayout(i).GetEvents().Clear();
  }
}