mirror of
https://github.com/4ian/GDevelop.git
synced 2025-10-15 10:19:04 +00:00
Compare commits
58 Commits
feature/re
...
v5.1.149
Author | SHA1 | Date | |
---|---|---|---|
![]() |
c5eb0bcc00 | ||
![]() |
a732fda4d9 | ||
![]() |
398bff8492 | ||
![]() |
f30e92a953 | ||
![]() |
8210c25acb | ||
![]() |
6a13940e17 | ||
![]() |
622aa7c08c | ||
![]() |
a71558a490 | ||
![]() |
37539aa788 | ||
![]() |
789f819f25 | ||
![]() |
52ebfb8100 | ||
![]() |
ecc5c689d2 | ||
![]() |
5b1e169557 | ||
![]() |
386e23b042 | ||
![]() |
fc76bafc7c | ||
![]() |
de53f4df4f | ||
![]() |
9fedf124db | ||
![]() |
2c68bb4bdd | ||
![]() |
2360cf899f | ||
![]() |
3fc57c2b06 | ||
![]() |
b4f41e96ae | ||
![]() |
b20108ddcb | ||
![]() |
a58b039994 | ||
![]() |
a7f218622e | ||
![]() |
8d95eb4269 | ||
![]() |
4e46690418 | ||
![]() |
db1737281e | ||
![]() |
d5eecda570 | ||
![]() |
80cb6d697c | ||
![]() |
6b08fec747 | ||
![]() |
2c92ce74ce | ||
![]() |
30643ced07 | ||
![]() |
bf27761cff | ||
![]() |
58df3aeca1 | ||
![]() |
69f8961e9e | ||
![]() |
1abb39ec17 | ||
![]() |
c5226c1e45 | ||
![]() |
d40789005b | ||
![]() |
fcbe5c364e | ||
![]() |
df3433c55f | ||
![]() |
7d892fd976 | ||
![]() |
56320d7253 | ||
![]() |
05acd061bd | ||
![]() |
7991ceb351 | ||
![]() |
bf6d18ccbe | ||
![]() |
536b7dcc62 | ||
![]() |
a157f32d4a | ||
![]() |
49f579f32d | ||
![]() |
8f4ecd373f | ||
![]() |
a3a53415b1 | ||
![]() |
c278c0a432 | ||
![]() |
862f270b83 | ||
![]() |
7232dbc2fa | ||
![]() |
78cbe48718 | ||
![]() |
e153d295de | ||
![]() |
1b8510655e | ||
![]() |
bd88127563 | ||
![]() |
01b9f09604 |
@@ -886,7 +886,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/conditions/timer24.png",
|
||||
"res/conditions/timer.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer")
|
||||
.AddParameter("expression", _("Time in seconds"))
|
||||
.SetHidden();
|
||||
|
||||
@@ -900,7 +900,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/conditions/timer24.png",
|
||||
"res/conditions/timer.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer")
|
||||
.AddParameter("relationalOperator", _("Sign of the test"), "time")
|
||||
.AddParameter("expression", _("Time in seconds"))
|
||||
.SetManipulatedType("number");
|
||||
@@ -913,7 +913,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/conditions/timerPaused24.png",
|
||||
"res/conditions/timerPaused.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
obj.AddAction(
|
||||
@@ -926,7 +926,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/actions/timer24.png",
|
||||
"res/actions/timer.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"));
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer");
|
||||
|
||||
obj.AddAction("PauseObjectTimer",
|
||||
_("Pause an object timer"),
|
||||
@@ -936,7 +936,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/actions/pauseTimer24.png",
|
||||
"res/actions/pauseTimer.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
obj.AddAction("UnPauseObjectTimer",
|
||||
@@ -947,7 +947,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/actions/unPauseTimer24.png",
|
||||
"res/actions/unPauseTimer.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
obj.AddAction("RemoveObjectTimer",
|
||||
@@ -958,7 +958,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
"res/actions/timer24.png",
|
||||
"res/actions/timer.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
obj.AddExpression("X",
|
||||
@@ -1127,7 +1127,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
_("Object timers"),
|
||||
"res/actions/time.png")
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("string", _("Timer's name"));
|
||||
.AddParameter("identifier", _("Timer's name"), "objectTimer");
|
||||
|
||||
obj.AddExpression("AngleToObject",
|
||||
_("Angle between two objects"),
|
||||
|
@@ -590,19 +590,6 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsCameraExtension(
|
||||
.SetDefaultValue("\"\"")
|
||||
.AddParameter("expression", _("New default Z order"));
|
||||
|
||||
extension
|
||||
.AddExpressionAndCondition("number",
|
||||
"LayerHighestZOrder",
|
||||
_("Layer highest Z order"),
|
||||
_("the highest Z order of objects in a layer"),
|
||||
_("the highest Z order of objects in the layer _PARAM1_"),
|
||||
"",
|
||||
"res/conditions/layer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("layer", _("Layer (base layer if empty)"), "", true)
|
||||
.SetDefaultValue("\"\"")
|
||||
.UseStandardParameters("number");
|
||||
|
||||
extension
|
||||
.AddAction(
|
||||
"SetLayerAmbientLightColor",
|
||||
|
@@ -36,7 +36,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/conditions/timer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("expression", _("Time in seconds"))
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer")
|
||||
.SetHidden();
|
||||
|
||||
extension
|
||||
@@ -50,7 +50,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/conditions/timer24.png",
|
||||
"res/conditions/timer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer")
|
||||
.AddParameter("relationalOperator", _("Sign of the test"), "time")
|
||||
.AddParameter("expression", _("Time in seconds"))
|
||||
.SetManipulatedType("number");
|
||||
@@ -78,7 +78,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/conditions/timerPaused24.png",
|
||||
"res/conditions/timerPaused.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
@@ -93,7 +93,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/actions/timer24.png",
|
||||
"res/actions/timer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"));
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer");
|
||||
|
||||
extension
|
||||
.AddAction("PauseTimer",
|
||||
@@ -105,7 +105,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/actions/pauseTimer24.png",
|
||||
"res/actions/pauseTimer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
@@ -118,7 +118,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/actions/unPauseTimer24.png",
|
||||
"res/actions/unPauseTimer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
@@ -131,7 +131,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"res/actions/timer24.png",
|
||||
"res/actions/timer.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"))
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer")
|
||||
.MarkAsAdvanced();
|
||||
|
||||
extension
|
||||
@@ -191,7 +191,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsTimeExtension(
|
||||
"",
|
||||
"res/actions/time.png")
|
||||
.AddCodeOnlyParameter("currentScene", "")
|
||||
.AddParameter("string", _("Timer's name"));
|
||||
.AddParameter("identifier", _("Timer's name"), "sceneTimer");
|
||||
|
||||
extension
|
||||
.AddExpression("TimeFromStart",
|
||||
|
@@ -199,7 +199,8 @@ class GD_CORE_API ParameterMetadata {
|
||||
parameterType == "objectAnimationName" ||
|
||||
parameterType == "functionParameterName" ||
|
||||
parameterType == "externalLayoutName" ||
|
||||
parameterType == "leaderboardId";
|
||||
parameterType == "leaderboardId" ||
|
||||
parameterType == "identifier";
|
||||
} else if (type == "variable") {
|
||||
return parameterType == "objectvar" || parameterType == "globalvar" ||
|
||||
parameterType == "scenevar";
|
||||
|
@@ -73,4 +73,54 @@ bool ArbitraryEventsWorker::VisitInstruction(gd::Instruction& instruction,
|
||||
|
||||
ArbitraryEventsWorkerWithContext::~ArbitraryEventsWorkerWithContext() {}
|
||||
|
||||
|
||||
ReadOnlyArbitraryEventsWorker::~ReadOnlyArbitraryEventsWorker() {}
|
||||
|
||||
void ReadOnlyArbitraryEventsWorker::VisitEventList(const gd::EventsList& events) {
|
||||
DoVisitEventList(events);
|
||||
|
||||
for (std::size_t i = 0; i < events.size(); ++i) {
|
||||
VisitEvent(events[i]);
|
||||
|
||||
if (events[i].CanHaveSubEvents()) {
|
||||
VisitEventList(events[i].GetSubEvents());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ReadOnlyArbitraryEventsWorker::VisitEvent(const gd::BaseEvent& event) {
|
||||
DoVisitEvent(event);
|
||||
|
||||
const vector<const gd::InstructionsList*> conditionsVectors =
|
||||
event.GetAllConditionsVectors();
|
||||
for (std::size_t j = 0; j < conditionsVectors.size(); ++j) {
|
||||
VisitInstructionList(*conditionsVectors[j], true);
|
||||
}
|
||||
|
||||
const vector<const gd::InstructionsList*> actionsVectors = event.GetAllActionsVectors();
|
||||
for (std::size_t j = 0; j < actionsVectors.size(); ++j) {
|
||||
VisitInstructionList(*actionsVectors[j], false);
|
||||
}
|
||||
}
|
||||
|
||||
void ReadOnlyArbitraryEventsWorker::VisitInstructionList(
|
||||
const gd::InstructionsList& instructions, bool areConditions) {
|
||||
DoVisitInstructionList(instructions, areConditions);
|
||||
|
||||
for (std::size_t i = 0; i < instructions.size(); ++i) {
|
||||
VisitInstruction(instructions[i], areConditions);
|
||||
if (!instructions[i].GetSubInstructions().empty()) {
|
||||
VisitInstructionList(instructions[i].GetSubInstructions(),
|
||||
areConditions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ReadOnlyArbitraryEventsWorker::VisitInstruction(const gd::Instruction& instruction,
|
||||
bool isCondition) {
|
||||
DoVisitInstruction(instruction, isCondition);
|
||||
}
|
||||
|
||||
ReadOnlyArbitraryEventsWorkerWithContext::~ReadOnlyArbitraryEventsWorkerWithContext() {}
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -121,6 +121,101 @@ class GD_CORE_API ArbitraryEventsWorkerWithContext
|
||||
const gd::ObjectsContainer* currentObjectsContainer;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief ReadOnlyArbitraryEventsWorker is an abstract class used to browse events (and
|
||||
* instructions). It can be used to implement autocompletion for example.
|
||||
*
|
||||
* \see gd::ReadOnlyArbitraryEventsWorkerWithContext
|
||||
*
|
||||
* \ingroup IDE
|
||||
*/
|
||||
class GD_CORE_API ReadOnlyArbitraryEventsWorker {
|
||||
public:
|
||||
ReadOnlyArbitraryEventsWorker(){};
|
||||
virtual ~ReadOnlyArbitraryEventsWorker();
|
||||
|
||||
/**
|
||||
* \brief Launch the worker on the specified events list.
|
||||
*/
|
||||
void Launch(const gd::EventsList& events) { VisitEventList(events); };
|
||||
|
||||
private:
|
||||
void VisitEventList(const gd::EventsList& events);
|
||||
void VisitEvent(const gd::BaseEvent& event);
|
||||
void VisitInstructionList(const gd::InstructionsList& instructions,
|
||||
bool areConditions);
|
||||
void VisitInstruction(const gd::Instruction& instruction, bool isCondition);
|
||||
|
||||
/**
|
||||
* Called to do some work on an event list.
|
||||
*/
|
||||
virtual void DoVisitEventList(const gd::EventsList& events){};
|
||||
|
||||
/**
|
||||
* Called to do some work on an event
|
||||
*/
|
||||
virtual void DoVisitEvent(const gd::BaseEvent& event) {};
|
||||
|
||||
/**
|
||||
* Called to do some work on an instruction list
|
||||
*/
|
||||
virtual void DoVisitInstructionList(const gd::InstructionsList& instructions,
|
||||
bool areConditions){};
|
||||
|
||||
/**
|
||||
* Called to do some work on an instruction.
|
||||
*/
|
||||
virtual void DoVisitInstruction(const gd::Instruction& instruction,
|
||||
bool isCondition) {};
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief An events worker that will know about the context (the objects
|
||||
* container). Useful for workers working on expressions notably.
|
||||
*
|
||||
* \see gd::ReadOnlyArbitraryEventsWorker
|
||||
*
|
||||
* \ingroup IDE
|
||||
*/
|
||||
class GD_CORE_API ReadOnlyArbitraryEventsWorkerWithContext
|
||||
: public ReadOnlyArbitraryEventsWorker {
|
||||
public:
|
||||
ReadOnlyArbitraryEventsWorkerWithContext()
|
||||
: currentGlobalObjectsContainer(nullptr),
|
||||
currentObjectsContainer(nullptr){};
|
||||
virtual ~ReadOnlyArbitraryEventsWorkerWithContext();
|
||||
|
||||
/**
|
||||
* \brief Launch the worker on the specified events list,
|
||||
* giving the objects container on which the events are applying to.
|
||||
*/
|
||||
void Launch(const gd::EventsList& events,
|
||||
const gd::ObjectsContainer& globalObjectsContainer_,
|
||||
const gd::ObjectsContainer& objectsContainer_) {
|
||||
currentGlobalObjectsContainer = &globalObjectsContainer_;
|
||||
currentObjectsContainer = &objectsContainer_;
|
||||
ReadOnlyArbitraryEventsWorker::Launch(events);
|
||||
};
|
||||
|
||||
void Launch(gd::EventsList& events) = delete;
|
||||
|
||||
protected:
|
||||
const gd::ObjectsContainer& GetGlobalObjectsContainer() {
|
||||
// Pointers are guaranteed to be not nullptr after
|
||||
// Launch was called.
|
||||
return *currentGlobalObjectsContainer;
|
||||
};
|
||||
const gd::ObjectsContainer& GetObjectsContainer() {
|
||||
// Pointers are guaranteed to be not nullptr after
|
||||
// Launch was called.
|
||||
return *currentObjectsContainer;
|
||||
};
|
||||
|
||||
private:
|
||||
const gd::ObjectsContainer* currentGlobalObjectsContainer;
|
||||
const gd::ObjectsContainer* currentObjectsContainer;
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
||||
#endif // GDCORE_ARBITRARYEVENTSWORKER_H
|
||||
|
254
Core/GDCore/IDE/Events/EventsIdentifiersFinder.cpp
Normal file
254
Core/GDCore/IDE/Events/EventsIdentifiersFinder.cpp
Normal file
@@ -0,0 +1,254 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
|
||||
#include "EventsIdentifiersFinder.h"
|
||||
#include "GDCore/Events/Event.h"
|
||||
#include "GDCore/Events/Instruction.h"
|
||||
#include "GDCore/Events/Parsers/ExpressionParser2NodePrinter.h"
|
||||
#include "GDCore/Events/Parsers/ExpressionParser2NodeWorker.h"
|
||||
#include "GDCore/Extensions/Metadata/ExpressionMetadata.h"
|
||||
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
|
||||
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
|
||||
#include "GDCore/Extensions/Platform.h"
|
||||
#include "GDCore/IDE/Events/ArbitraryEventsWorker.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Object.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/IDE/DependenciesAnalyzer.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace gd {
|
||||
namespace {
|
||||
/**
|
||||
* \brief Go through the nodes to search for identifier occurrences.
|
||||
*
|
||||
* \see gd::ExpressionParser2
|
||||
*/
|
||||
class GD_CORE_API IdentifierFinderExpressionNodeWorker
|
||||
: public ExpressionParser2NodeWorker {
|
||||
public:
|
||||
IdentifierFinderExpressionNodeWorker(std::set<gd::String>& results_,
|
||||
const gd::Platform &platform_,
|
||||
const gd::ObjectsContainer &globalObjectsContainer_,
|
||||
const gd::ObjectsContainer &objectsContainer_,
|
||||
const gd::String& identifierType_,
|
||||
const gd::String& objectName_ = "")
|
||||
: results(results_),
|
||||
platform(platform_),
|
||||
globalObjectsContainer(globalObjectsContainer_),
|
||||
objectsContainer(objectsContainer_),
|
||||
identifierType(identifierType_),
|
||||
objectName(objectName_){};
|
||||
virtual ~IdentifierFinderExpressionNodeWorker(){};
|
||||
|
||||
protected:
|
||||
void OnVisitSubExpressionNode(SubExpressionNode& node) override {
|
||||
node.expression->Visit(*this);
|
||||
}
|
||||
void OnVisitOperatorNode(OperatorNode& node) override {
|
||||
node.leftHandSide->Visit(*this);
|
||||
node.rightHandSide->Visit(*this);
|
||||
}
|
||||
void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override {
|
||||
node.factor->Visit(*this);
|
||||
}
|
||||
void OnVisitNumberNode(NumberNode& node) override {}
|
||||
void OnVisitTextNode(TextNode& node) override {}
|
||||
void OnVisitVariableNode(VariableNode& node) override {
|
||||
if (node.child) node.child->Visit(*this);
|
||||
}
|
||||
void OnVisitVariableAccessorNode(VariableAccessorNode& node) override {
|
||||
if (node.child) node.child->Visit(*this);
|
||||
}
|
||||
void OnVisitVariableBracketAccessorNode(
|
||||
VariableBracketAccessorNode& node) override {
|
||||
node.expression->Visit(*this);
|
||||
if (node.child) node.child->Visit(*this);
|
||||
}
|
||||
void OnVisitIdentifierNode(IdentifierNode& node) override {}
|
||||
void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override {}
|
||||
void OnVisitFunctionCallNode(FunctionCallNode& node) override {
|
||||
bool considerFunction = objectName.empty() || node.objectName == objectName;
|
||||
|
||||
const bool isObjectFunction = !node.objectName.empty();
|
||||
const gd::ExpressionMetadata &metadata = isObjectFunction ?
|
||||
MetadataProvider::GetObjectAnyExpressionMetadata(
|
||||
platform,
|
||||
GetTypeOfObject(globalObjectsContainer, objectsContainer, objectName),
|
||||
node.functionName):
|
||||
MetadataProvider::GetAnyExpressionMetadata(platform, node.functionName);
|
||||
|
||||
if (gd::MetadataProvider::IsBadExpressionMetadata(metadata)) {
|
||||
return;
|
||||
}
|
||||
|
||||
size_t parameterIndex = 0;
|
||||
for (size_t metadataIndex = (isObjectFunction ? 1 : 0); metadataIndex < metadata.parameters.size()
|
||||
&& parameterIndex < node.parameters.size(); ++metadataIndex) {
|
||||
auto& parameterMetadata = metadata.parameters[metadataIndex];
|
||||
if (parameterMetadata.IsCodeOnly()) {
|
||||
continue;
|
||||
}
|
||||
auto& parameterNode = node.parameters[parameterIndex];
|
||||
++parameterIndex;
|
||||
|
||||
if (considerFunction && parameterMetadata.GetType() == "identifier"
|
||||
&& parameterMetadata.GetExtraInfo() == identifierType) {
|
||||
// Store the value of the parameter
|
||||
results.insert(
|
||||
gd::ExpressionParser2NodePrinter::PrintNode(*parameterNode));
|
||||
} else {
|
||||
parameterNode->Visit(*this);
|
||||
}
|
||||
}
|
||||
}
|
||||
void OnVisitEmptyNode(EmptyNode& node) override {}
|
||||
|
||||
private:
|
||||
const gd::Platform &platform;
|
||||
const gd::ObjectsContainer &globalObjectsContainer;
|
||||
const gd::ObjectsContainer &objectsContainer;
|
||||
|
||||
std::set<gd::String>& results; ///< Reference to the std::set where argument
|
||||
///< values must be stored.
|
||||
gd::String identifierType; ///< The type of the parameters to be searched for.
|
||||
gd::String objectName; ///< If not empty, parameters will be taken into
|
||||
///< account only if related to this object.
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Go through the events to search for identifier occurrences.
|
||||
*/
|
||||
class GD_CORE_API IdentifierFinderEventWorker
|
||||
: public ReadOnlyArbitraryEventsWorkerWithContext {
|
||||
public:
|
||||
IdentifierFinderEventWorker(std::set<gd::String>& results_,
|
||||
const gd::Platform &platform_,
|
||||
const gd::String& identifierType_,
|
||||
const gd::String& objectName_ = "")
|
||||
: results(results_),
|
||||
platform(platform_),
|
||||
identifierType(identifierType_),
|
||||
objectName(objectName_){};
|
||||
virtual ~IdentifierFinderEventWorker(){};
|
||||
|
||||
void DoVisitInstructionList(const gd::InstructionsList& instructions,
|
||||
bool areConditions) override {
|
||||
for (std::size_t aId = 0; aId < instructions.size(); ++aId) {
|
||||
auto& instruction = instructions[aId];
|
||||
gd::String lastObjectParameter = "";
|
||||
const gd::InstructionMetadata& instrInfos =
|
||||
areConditions ? MetadataProvider::GetConditionMetadata(
|
||||
platform, instruction.GetType())
|
||||
: MetadataProvider::GetActionMetadata(
|
||||
platform, instruction.GetType());
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.size(); ++pNb) {
|
||||
// The parameter has the searched type...
|
||||
if (instrInfos.parameters[pNb].type == "identifier"
|
||||
&& instrInfos.parameters[pNb].supplementaryInformation == identifierType) {
|
||||
//...remember the value of the parameter.
|
||||
if (objectName.empty() || lastObjectParameter == objectName) {
|
||||
results.insert(instruction.GetParameter(pNb).GetPlainString());
|
||||
}
|
||||
}
|
||||
// Search in expressions
|
||||
else if (ParameterMetadata::IsExpression(
|
||||
"number", instrInfos.parameters[pNb].type) ||
|
||||
ParameterMetadata::IsExpression(
|
||||
"string", instrInfos.parameters[pNb].type)) {
|
||||
auto node = instruction.GetParameter(pNb).GetRootNode();
|
||||
|
||||
IdentifierFinderExpressionNodeWorker searcher(
|
||||
results,
|
||||
platform,
|
||||
GetGlobalObjectsContainer(),
|
||||
GetObjectsContainer(),
|
||||
identifierType,
|
||||
objectName);
|
||||
node->Visit(searcher);
|
||||
}
|
||||
// Remember the value of the last "object" parameter.
|
||||
else if (gd::ParameterMetadata::IsObject(
|
||||
instrInfos.parameters[pNb].type)) {
|
||||
lastObjectParameter =
|
||||
instruction.GetParameter(pNb).GetPlainString();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
const gd::Platform &platform;
|
||||
|
||||
std::set<gd::String>& results; ///< Reference to the std::set where argument
|
||||
///< values must be stored.
|
||||
gd::String identifierType; ///< The type of the parameters to be searched for.
|
||||
gd::String objectName; ///< If not empty, parameters will be taken into
|
||||
///< account only if related to this object.
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::set<gd::String> EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::String& identifierType,
|
||||
const gd::String& contextObjectName) {
|
||||
std::set<gd::String> results;
|
||||
|
||||
const bool isObjectIdentifier = identifierType.find("object") == 0;
|
||||
// The object from the context is only relevent for object identifiers.
|
||||
auto& actualObjectName = isObjectIdentifier ? contextObjectName : "";
|
||||
|
||||
FindArgumentsInEventsAndDependencies(
|
||||
results,
|
||||
platform,
|
||||
project,
|
||||
layout,
|
||||
identifierType,
|
||||
actualObjectName);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
void EventsIdentifiersFinder::FindArgumentsInEventsAndDependencies(
|
||||
std::set<gd::String>& results,
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::String& identifierType,
|
||||
const gd::String& objectName) {
|
||||
IdentifierFinderEventWorker eventWorker(results,
|
||||
platform,
|
||||
identifierType,
|
||||
objectName);
|
||||
eventWorker.Launch(layout.GetEvents(), project, layout);
|
||||
|
||||
DependenciesAnalyzer dependenciesAnalyzer = DependenciesAnalyzer(project, layout);
|
||||
dependenciesAnalyzer.Analyze();
|
||||
for (const gd::String& externalEventName : dependenciesAnalyzer.GetExternalEventsDependencies()) {
|
||||
const gd::ExternalEvents& externalEvents = project.GetExternalEvents(externalEventName);
|
||||
|
||||
IdentifierFinderEventWorker eventWorker(results,
|
||||
platform,
|
||||
identifierType,
|
||||
objectName);
|
||||
eventWorker.Launch(externalEvents.GetEvents(), project, layout);
|
||||
}
|
||||
for (const gd::String& sceneName : dependenciesAnalyzer.GetScenesDependencies()) {
|
||||
const gd::Layout& dependencyLayout = project.GetLayout(sceneName);
|
||||
|
||||
IdentifierFinderEventWorker eventWorker(results,
|
||||
platform,
|
||||
identifierType,
|
||||
objectName);
|
||||
eventWorker.Launch(dependencyLayout.GetEvents(), project, dependencyLayout);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace gd
|
81
Core/GDCore/IDE/Events/EventsIdentifiersFinder.h
Normal file
81
Core/GDCore/IDE/Events/EventsIdentifiersFinder.h
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
#ifndef EVENTSIDENTIFIERSFINDER_H
|
||||
#define EVENTSIDENTIFIERSFINDER_H
|
||||
#include <set>
|
||||
#include <vector>
|
||||
#include "GDCore/Events/Event.h"
|
||||
#include "GDCore/String.h"
|
||||
namespace gd {
|
||||
class Instruction;
|
||||
class Platform;
|
||||
class Object;
|
||||
class Project;
|
||||
class Layout;
|
||||
} // namespace gd
|
||||
|
||||
namespace gd {
|
||||
|
||||
/**
|
||||
* \brief Perform a search over a layout, searching for layout or object custom
|
||||
* identifiers.
|
||||
*
|
||||
* \todo Refactor this class using ArbitraryEventsWorker
|
||||
*
|
||||
* \ingroup IDE
|
||||
*/
|
||||
class EventsIdentifiersFinder {
|
||||
public:
|
||||
EventsIdentifiersFinder(){};
|
||||
virtual ~EventsIdentifiersFinder(){};
|
||||
|
||||
/**
|
||||
* Construct a list containing all the expressions for a given identifier used
|
||||
* in the layout.
|
||||
*
|
||||
* \param project The project to use.
|
||||
* \param layout The layout to use.
|
||||
* \param identifierType The identifier type to be analyzed.
|
||||
* \param objectName If not empty, parameters will be taken into account
|
||||
* only if the last object parameter is filled with
|
||||
* this value.
|
||||
* \return A std::set containing the names of all identifiers used.
|
||||
*/
|
||||
static std::set<gd::String> FindAllIdentifierExpressions(
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::String& identifierType,
|
||||
const gd::String& objectName = "");
|
||||
|
||||
private:
|
||||
/**
|
||||
* Construct a list containing all the expressions for a given identifier used
|
||||
* in the layout. It searches in events dependencies.
|
||||
*
|
||||
* \param results A std::set to fill with the expressions used for all parameters of the
|
||||
* specified identifier type
|
||||
* \param platform The platform of the project
|
||||
* \param project The project to use.
|
||||
* \param layout The layout to use.
|
||||
* \param events The events to be analyzed
|
||||
* \param identifierType The identifier type to be analyzed
|
||||
* \param objectName If not empty, parameters will be taken into account
|
||||
* only if the last object parameter is filled with
|
||||
* this value.
|
||||
*/
|
||||
static void FindArgumentsInEventsAndDependencies(
|
||||
std::set<gd::String>& results,
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::String& identifierType,
|
||||
const gd::String& objectName = "");
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
||||
#endif // EVENTSIDENTIFIERSFINDER_H
|
@@ -13,6 +13,7 @@
|
||||
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
|
||||
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
|
||||
#include "GDCore/Extensions/Platform.h"
|
||||
#include "GDCore/IDE/Events/ArbitraryEventsWorker.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Object.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
@@ -22,28 +23,28 @@
|
||||
using namespace std;
|
||||
|
||||
namespace gd {
|
||||
|
||||
namespace {
|
||||
/**
|
||||
* \brief Go through the nodes and change the given object name to a new one.
|
||||
* \brief Go through the nodes to search for variable occurrences.
|
||||
*
|
||||
* \see gd::ExpressionParser2
|
||||
*/
|
||||
class GD_CORE_API ExpressionParameterSearcher
|
||||
class GD_CORE_API VariableFinderExpressionNodeWorker
|
||||
: public ExpressionParser2NodeWorker {
|
||||
public:
|
||||
ExpressionParameterSearcher(const gd::Platform &platform_,
|
||||
VariableFinderExpressionNodeWorker(std::set<gd::String>& results_,
|
||||
const gd::Platform &platform_,
|
||||
const gd::ObjectsContainer &globalObjectsContainer_,
|
||||
const gd::ObjectsContainer &objectsContainer_,
|
||||
std::set<gd::String>& results_,
|
||||
const gd::String& parameterType_,
|
||||
const gd::String& objectName_ = "")
|
||||
: platform(platform_),
|
||||
: results(results_),
|
||||
platform(platform_),
|
||||
globalObjectsContainer(globalObjectsContainer_),
|
||||
objectsContainer(objectsContainer_),
|
||||
results(results_),
|
||||
parameterType(parameterType_),
|
||||
objectName(objectName_){};
|
||||
virtual ~ExpressionParameterSearcher(){};
|
||||
virtual ~VariableFinderExpressionNodeWorker(){};
|
||||
|
||||
protected:
|
||||
void OnVisitSubExpressionNode(SubExpressionNode& node) override {
|
||||
@@ -74,27 +75,34 @@ class GD_CORE_API ExpressionParameterSearcher
|
||||
void OnVisitFunctionCallNode(FunctionCallNode& node) override {
|
||||
bool considerFunction = objectName.empty() || node.objectName == objectName;
|
||||
|
||||
const gd::ExpressionMetadata &metadata = node.objectName.empty() ?
|
||||
MetadataProvider::GetAnyExpressionMetadata(platform, node.functionName) :
|
||||
const bool isObjectFunction = !node.objectName.empty();
|
||||
const gd::ExpressionMetadata &metadata = isObjectFunction ?
|
||||
MetadataProvider::GetObjectAnyExpressionMetadata(
|
||||
platform,
|
||||
GetTypeOfObject(globalObjectsContainer, objectsContainer, objectName),
|
||||
node.functionName);
|
||||
node.functionName):
|
||||
MetadataProvider::GetAnyExpressionMetadata(platform, node.functionName);
|
||||
|
||||
if (gd::MetadataProvider::IsBadExpressionMetadata(metadata)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < node.parameters.size() &&
|
||||
i < metadata.parameters.size();
|
||||
++i) {
|
||||
auto& parameterMetadata = metadata.parameters[i];
|
||||
|
||||
size_t parameterIndex = 0;
|
||||
for (size_t metadataIndex = (isObjectFunction ? 1 : 0); metadataIndex < metadata.parameters.size()
|
||||
&& parameterIndex < node.parameters.size(); ++metadataIndex) {
|
||||
auto& parameterMetadata = metadata.parameters[metadataIndex];
|
||||
if (parameterMetadata.IsCodeOnly()) {
|
||||
continue;
|
||||
}
|
||||
auto& parameterNode = node.parameters[parameterIndex];
|
||||
++parameterIndex;
|
||||
|
||||
if (considerFunction && parameterMetadata.GetType() == parameterType) {
|
||||
// Store the value of the parameter
|
||||
results.insert(
|
||||
gd::ExpressionParser2NodePrinter::PrintNode(*node.parameters[i]));
|
||||
gd::ExpressionParser2NodePrinter::PrintNode(*parameterNode));
|
||||
} else {
|
||||
node.parameters[i]->Visit(*this);
|
||||
parameterNode->Visit(*this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,18 +120,87 @@ class GD_CORE_API ExpressionParameterSearcher
|
||||
///< account only if related to this object.
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Go through the events to search for variable occurrences.
|
||||
*/
|
||||
class GD_CORE_API VariableFinderEventWorker
|
||||
: public ReadOnlyArbitraryEventsWorkerWithContext {
|
||||
public:
|
||||
VariableFinderEventWorker(std::set<gd::String>& results_,
|
||||
const gd::Platform &platform_,
|
||||
const gd::String& parameterType_,
|
||||
const gd::String& objectName_ = "")
|
||||
: results(results_),
|
||||
platform(platform_),
|
||||
parameterType(parameterType_),
|
||||
objectName(objectName_){};
|
||||
virtual ~VariableFinderEventWorker(){};
|
||||
|
||||
void DoVisitInstructionList(const gd::InstructionsList& instructions,
|
||||
bool areConditions) override {
|
||||
for (std::size_t aId = 0; aId < instructions.size(); ++aId) {
|
||||
auto& instruction = instructions[aId];
|
||||
gd::String lastObjectParameter = "";
|
||||
const gd::InstructionMetadata& instrInfos =
|
||||
areConditions ? MetadataProvider::GetConditionMetadata(
|
||||
platform, instruction.GetType())
|
||||
: MetadataProvider::GetActionMetadata(
|
||||
platform, instruction.GetType());
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.size(); ++pNb) {
|
||||
// The parameter has the searched type...
|
||||
if (instrInfos.parameters[pNb].type == parameterType) {
|
||||
//...remember the value of the parameter.
|
||||
if (objectName.empty() || lastObjectParameter == objectName)
|
||||
results.insert(instruction.GetParameter(pNb).GetPlainString());
|
||||
}
|
||||
// Search in expressions
|
||||
else if (ParameterMetadata::IsExpression(
|
||||
"number", instrInfos.parameters[pNb].type) ||
|
||||
ParameterMetadata::IsExpression(
|
||||
"string", instrInfos.parameters[pNb].type)) {
|
||||
auto node = instruction.GetParameter(pNb).GetRootNode();
|
||||
|
||||
VariableFinderExpressionNodeWorker searcher(
|
||||
results,
|
||||
platform,
|
||||
GetGlobalObjectsContainer(),
|
||||
GetObjectsContainer(),
|
||||
parameterType,
|
||||
objectName);
|
||||
node->Visit(searcher);
|
||||
}
|
||||
// Remember the value of the last "object" parameter.
|
||||
else if (gd::ParameterMetadata::IsObject(
|
||||
instrInfos.parameters[pNb].type)) {
|
||||
lastObjectParameter =
|
||||
instruction.GetParameter(pNb).GetPlainString();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
const gd::Platform &platform;
|
||||
|
||||
std::set<gd::String>& results; ///< Reference to the std::set where argument
|
||||
///< values must be stored.
|
||||
gd::String parameterType; ///< The type of the parameters to be searched for.
|
||||
gd::String objectName; ///< If not empty, parameters will be taken into
|
||||
///< account only if related to this object.
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::set<gd::String> EventsVariablesFinder::FindAllGlobalVariables(
|
||||
const gd::Platform& platform, const gd::Project& project) {
|
||||
std::set<gd::String> results;
|
||||
|
||||
for (std::size_t i = 0; i < project.GetLayoutsCount(); ++i) {
|
||||
std::set<gd::String> results2 =
|
||||
FindArgumentsInEventsAndDependencies(
|
||||
FindArgumentsInEventsAndDependencies(
|
||||
results,
|
||||
platform,
|
||||
project,
|
||||
project.GetLayout(i),
|
||||
"globalvar");
|
||||
results.insert(results2.begin(), results2.end());
|
||||
}
|
||||
|
||||
return results;
|
||||
@@ -135,9 +212,12 @@ std::set<gd::String> EventsVariablesFinder::FindAllLayoutVariables(
|
||||
const gd::Layout& layout) {
|
||||
std::set<gd::String> results;
|
||||
|
||||
std::set<gd::String> results2 = FindArgumentsInEventsAndDependencies(
|
||||
platform, project, layout, "scenevar");
|
||||
results.insert(results2.begin(), results2.end());
|
||||
FindArgumentsInEventsAndDependencies(
|
||||
results,
|
||||
platform,
|
||||
project,
|
||||
layout,
|
||||
"scenevar");
|
||||
|
||||
return results;
|
||||
}
|
||||
@@ -149,159 +229,51 @@ std::set<gd::String> EventsVariablesFinder::FindAllObjectVariables(
|
||||
const gd::Object& object) {
|
||||
std::set<gd::String> results;
|
||||
|
||||
std::set<gd::String> results2 = FindArgumentsInEventsAndDependencies(
|
||||
FindArgumentsInEventsAndDependencies(
|
||||
results,
|
||||
platform,
|
||||
project,
|
||||
layout,
|
||||
"objectvar",
|
||||
object.GetName());
|
||||
results.insert(results2.begin(), results2.end());
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
std::set<gd::String> EventsVariablesFinder::FindArgumentsInInstructions(
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::InstructionsList& instructions,
|
||||
bool instructionsAreConditions,
|
||||
const gd::String& parameterType,
|
||||
const gd::String& objectName) {
|
||||
std::set<gd::String> results;
|
||||
|
||||
for (std::size_t aId = 0; aId < instructions.size(); ++aId) {
|
||||
gd::String lastObjectParameter = "";
|
||||
const gd::InstructionMetadata& instrInfos =
|
||||
instructionsAreConditions ? MetadataProvider::GetConditionMetadata(
|
||||
platform, instructions[aId].GetType())
|
||||
: MetadataProvider::GetActionMetadata(
|
||||
platform, instructions[aId].GetType());
|
||||
for (std::size_t pNb = 0; pNb < instrInfos.parameters.size(); ++pNb) {
|
||||
// The parameter has the searched type...
|
||||
if (instrInfos.parameters[pNb].type == parameterType) {
|
||||
//...remember the value of the parameter.
|
||||
if (objectName.empty() || lastObjectParameter == objectName)
|
||||
results.insert(instructions[aId].GetParameter(pNb).GetPlainString());
|
||||
}
|
||||
// Search in expressions
|
||||
else if (ParameterMetadata::IsExpression(
|
||||
"number", instrInfos.parameters[pNb].type) ||
|
||||
ParameterMetadata::IsExpression(
|
||||
"string", instrInfos.parameters[pNb].type)) {
|
||||
auto node = instructions[aId].GetParameter(pNb).GetRootNode();
|
||||
|
||||
ExpressionParameterSearcher searcher(
|
||||
platform,
|
||||
project,
|
||||
layout,
|
||||
results,
|
||||
parameterType,
|
||||
objectName);
|
||||
node->Visit(searcher);
|
||||
}
|
||||
// Remember the value of the last "object" parameter.
|
||||
else if (gd::ParameterMetadata::IsObject(
|
||||
instrInfos.parameters[pNb].type)) {
|
||||
lastObjectParameter =
|
||||
instructions[aId].GetParameter(pNb).GetPlainString();
|
||||
}
|
||||
}
|
||||
|
||||
if (!instructions[aId].GetSubInstructions().empty())
|
||||
FindArgumentsInInstructions(platform,
|
||||
project,
|
||||
layout,
|
||||
instructions[aId].GetSubInstructions(),
|
||||
instructionsAreConditions,
|
||||
parameterType);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
std::set<gd::String> EventsVariablesFinder::FindArgumentsInEventsAndDependencies(
|
||||
void EventsVariablesFinder::FindArgumentsInEventsAndDependencies(
|
||||
std::set<gd::String>& results,
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::String& parameterType,
|
||||
const gd::String& objectName) {
|
||||
std::set<gd::String> results;
|
||||
|
||||
std::set<gd::String> results2 = FindArgumentsInEvents(
|
||||
platform, project, layout, layout.GetEvents(), parameterType, objectName);
|
||||
results.insert(results2.begin(), results2.end());
|
||||
VariableFinderEventWorker eventWorker(results,
|
||||
platform,
|
||||
parameterType,
|
||||
objectName);
|
||||
eventWorker.Launch(layout.GetEvents(), project, layout);
|
||||
|
||||
DependenciesAnalyzer dependenciesAnalyzer = DependenciesAnalyzer(project, layout);
|
||||
dependenciesAnalyzer.Analyze();
|
||||
for (const gd::String& externalEventName : dependenciesAnalyzer.GetExternalEventsDependencies()) {
|
||||
const gd::ExternalEvents& externalEvents = project.GetExternalEvents(externalEventName);
|
||||
|
||||
std::set<gd::String> results3 = FindArgumentsInEvents(
|
||||
platform, project, layout, externalEvents.GetEvents(), parameterType, objectName);
|
||||
results.insert(results3.begin(), results3.end());
|
||||
VariableFinderEventWorker eventWorker(results,
|
||||
platform,
|
||||
parameterType,
|
||||
objectName);
|
||||
eventWorker.Launch(externalEvents.GetEvents(), project, layout);
|
||||
}
|
||||
for (const gd::String& sceneName : dependenciesAnalyzer.GetScenesDependencies()) {
|
||||
const gd::Layout& dependencyLayout = project.GetLayout(sceneName);
|
||||
|
||||
std::set<gd::String> results3 = FindArgumentsInEvents(
|
||||
platform, project, dependencyLayout, dependencyLayout.GetEvents(), parameterType, objectName);
|
||||
results.insert(results3.begin(), results3.end());
|
||||
VariableFinderEventWorker eventWorker(results,
|
||||
platform,
|
||||
parameterType,
|
||||
objectName);
|
||||
eventWorker.Launch(dependencyLayout.GetEvents(), project, dependencyLayout);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
std::set<gd::String> EventsVariablesFinder::FindArgumentsInEvents(
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::EventsList& events,
|
||||
const gd::String& parameterType,
|
||||
const gd::String& objectName) {
|
||||
std::set<gd::String> results;
|
||||
for (std::size_t i = 0; i < events.size(); ++i) {
|
||||
vector<const gd::InstructionsList*> conditionsVectors =
|
||||
events[i].GetAllConditionsVectors();
|
||||
for (std::size_t j = 0; j < conditionsVectors.size(); ++j) {
|
||||
std::set<gd::String> results2 =
|
||||
FindArgumentsInInstructions(platform,
|
||||
project,
|
||||
layout,
|
||||
*conditionsVectors[j],
|
||||
/*conditions=*/true,
|
||||
parameterType,
|
||||
objectName);
|
||||
results.insert(results2.begin(), results2.end());
|
||||
}
|
||||
|
||||
vector<const gd::InstructionsList*> actionsVectors =
|
||||
events[i].GetAllActionsVectors();
|
||||
for (std::size_t j = 0; j < actionsVectors.size(); ++j) {
|
||||
std::set<gd::String> results2 =
|
||||
FindArgumentsInInstructions(platform,
|
||||
project,
|
||||
layout,
|
||||
*actionsVectors[j],
|
||||
/*conditions=*/false,
|
||||
parameterType,
|
||||
objectName);
|
||||
results.insert(results2.begin(), results2.end());
|
||||
}
|
||||
|
||||
if (events[i].CanHaveSubEvents()) {
|
||||
std::set<gd::String> results2 =
|
||||
FindArgumentsInEvents(platform,
|
||||
project,
|
||||
layout,
|
||||
events[i].GetSubEvents(),
|
||||
parameterType,
|
||||
objectName);
|
||||
results.insert(results2.begin(), results2.end());
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -23,7 +23,6 @@ namespace gd {
|
||||
* \brief Perform a search over a project or a layout, searching for layout,
|
||||
* global or object variables.
|
||||
*
|
||||
* \todo Refactor this class using ArbitraryEventsWorker
|
||||
* \todo Rework this class to return the shapes (maybe even types?) of the
|
||||
* variables (in particular for structures and arrays), so we can use this
|
||||
* for better autocompletions in the variables dialogs in the IDE.
|
||||
@@ -74,34 +73,13 @@ class EventsVariablesFinder {
|
||||
const gd::Object& object);
|
||||
|
||||
private:
|
||||
/**
|
||||
* Construct a list of the value of the arguments for parameters of type @
|
||||
* parameterType
|
||||
*
|
||||
* \param project The project used
|
||||
* \param project The layout used
|
||||
* \param instructions The instructions to be analyzed
|
||||
* \param instructionsAreConditions True if the instructions are conditions.
|
||||
* \param parameterType The parameters type to be analyzed
|
||||
* \param objectName If not empty, parameters will be taken into account only
|
||||
* if the last object parameter is filled with this value.
|
||||
*
|
||||
* \return A std::set filled with the values used for all parameters of the
|
||||
* specified type
|
||||
*/
|
||||
static std::set<gd::String> FindArgumentsInInstructions(
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::InstructionsList& instructions,
|
||||
bool instructionsAreConditions,
|
||||
const gd::String& parameterType,
|
||||
const gd::String& objectName = "");
|
||||
|
||||
/**
|
||||
* Construct a list of the value of the arguments for parameters of type @
|
||||
* parameterType. It searchs in events dependencies.
|
||||
* parameterType. It searches in events dependencies.
|
||||
*
|
||||
* \param results A std::set to fill with the values used for all parameters of the
|
||||
* specified type
|
||||
* \param platform The platform of the project
|
||||
* \param project The project used
|
||||
* \param layout The layout used
|
||||
@@ -110,40 +88,14 @@ class EventsVariablesFinder {
|
||||
* \param objectName If not empty, parameters will be taken into account
|
||||
* only if the last object parameter is filled with
|
||||
* this value.
|
||||
*
|
||||
* \return A std::set filled with the values used for all parameters of the
|
||||
* specified type
|
||||
*/
|
||||
static std::set<gd::String> FindArgumentsInEventsAndDependencies(
|
||||
static void FindArgumentsInEventsAndDependencies(
|
||||
std::set<gd::String>& results,
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::String& parameterType,
|
||||
const gd::String& objectName = "");
|
||||
|
||||
/**
|
||||
* Construct a list of the value of the arguments for parameters of type @
|
||||
* parameterType. It doesn't search in events dependencies.
|
||||
*
|
||||
* \param platform The platform of the project
|
||||
* \param project The project used
|
||||
* \param layout The layout used
|
||||
* \param events The events to be analyzed
|
||||
* \param parameterType The parameters type to be analyzed
|
||||
* \param objectName If not empty, parameters will be taken into account
|
||||
* only if the last object parameter is filled with
|
||||
* this value.
|
||||
*
|
||||
* \return A std::set filled with the values used for all parameters of the
|
||||
* specified type
|
||||
*/
|
||||
static std::set<gd::String> FindArgumentsInEvents(
|
||||
const gd::Platform& platform,
|
||||
const gd::Project& project,
|
||||
const gd::Layout& layout,
|
||||
const gd::EventsList& events,
|
||||
const gd::String& parameterType,
|
||||
const gd::String& objectName);
|
||||
};
|
||||
|
||||
} // namespace gd
|
||||
|
@@ -5,6 +5,8 @@
|
||||
*/
|
||||
#include "ProjectStripper.h"
|
||||
|
||||
#include "GDCore/Project/EventsFunctionsContainer.h"
|
||||
#include "GDCore/Project/EventsFunctionsExtension.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/Project/ExternalLayout.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
@@ -12,7 +14,7 @@
|
||||
|
||||
namespace gd {
|
||||
|
||||
void GD_CORE_API ProjectStripper::StripProjectForExport(gd::Project& project) {
|
||||
void GD_CORE_API ProjectStripper::StripProjectForExport(gd::Project &project) {
|
||||
project.GetObjectGroups().Clear();
|
||||
while (project.GetExternalEventsCount() > 0)
|
||||
project.RemoveExternalEvents(project.GetExternalEvents(0).GetName());
|
||||
@@ -22,7 +24,28 @@ void GD_CORE_API ProjectStripper::StripProjectForExport(gd::Project& project) {
|
||||
project.GetLayout(i).GetEvents().Clear();
|
||||
}
|
||||
|
||||
project.ClearEventsFunctionsExtensions();
|
||||
// Keep the EventsBasedObject object list because it's useful for the Runtime
|
||||
// to create the child-object.
|
||||
for (unsigned int extensionIndex = 0;
|
||||
extensionIndex < project.GetEventsFunctionsExtensionsCount();
|
||||
++extensionIndex) {
|
||||
auto &extension = project.GetEventsFunctionsExtension(extensionIndex);
|
||||
auto &eventsBasedObjects = extension.GetEventsBasedObjects();
|
||||
if (eventsBasedObjects.size() == 0) {
|
||||
project.RemoveEventsFunctionsExtension(extension.GetName());
|
||||
extensionIndex--;
|
||||
continue;
|
||||
}
|
||||
for (unsigned int objectIndex = 0; objectIndex < eventsBasedObjects.size();
|
||||
++objectIndex) {
|
||||
auto &eventsBasedObject = eventsBasedObjects.at(objectIndex);
|
||||
eventsBasedObject.SetFullName("");
|
||||
eventsBasedObject.SetDescription("");
|
||||
eventsBasedObject.GetEventsFunctions().GetInternalVector().clear();
|
||||
eventsBasedObject.GetPropertyDescriptors().GetInternalVector().clear();
|
||||
}
|
||||
extension.GetEventsBasedBehaviors().Clear();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace gd
|
||||
} // namespace gd
|
||||
|
@@ -22,16 +22,14 @@ void CustomObjectConfiguration::Init(const gd::CustomObjectConfiguration& object
|
||||
// There is no default copy for a map of unique_ptr like childObjectConfigurations.
|
||||
childObjectConfigurations.clear();
|
||||
for (auto& it : objectConfiguration.childObjectConfigurations) {
|
||||
childObjectConfigurations[it.first] =
|
||||
gd::make_unique<gd::ObjectConfiguration>(*it.second);
|
||||
childObjectConfigurations[it.first] = it.second->Clone();
|
||||
}
|
||||
}
|
||||
|
||||
gd::ObjectConfiguration CustomObjectConfiguration::badObjectConfiguration;
|
||||
|
||||
std::unique_ptr<gd::ObjectConfiguration> CustomObjectConfiguration::Clone() const {
|
||||
CustomObjectConfiguration* clone = new CustomObjectConfiguration(*this);
|
||||
return std::unique_ptr<gd::ObjectConfiguration>(clone);
|
||||
return gd::make_unique<gd::CustomObjectConfiguration>(*this);
|
||||
}
|
||||
|
||||
gd::ObjectConfiguration &CustomObjectConfiguration::GetChildObjectConfiguration(const gd::String &objectName) {
|
||||
@@ -51,7 +49,7 @@ gd::ObjectConfiguration &CustomObjectConfiguration::GetChildObjectConfiguration(
|
||||
if (configurationPosition == childObjectConfigurations.end()) {
|
||||
childObjectConfigurations.insert(std::make_pair(
|
||||
objectName,
|
||||
project->CreateObjectConfiguration(childObject.GetType())));
|
||||
childObject.GetConfiguration().Clone()));
|
||||
return *(childObjectConfigurations[objectName]);
|
||||
}
|
||||
else {
|
||||
|
@@ -110,6 +110,11 @@ class GD_CORE_API EffectsContainer {
|
||||
*/
|
||||
void UnserializeFrom(const SerializerElement& element);
|
||||
|
||||
/**
|
||||
* \brief Clear all effects of the container.
|
||||
*/
|
||||
inline void Clear() { effects.clear(); }
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<gd::Effect>> effects;
|
||||
static Effect badEffect;
|
||||
|
@@ -244,6 +244,15 @@ class GD_CORE_API HighestZOrderFinder : public gd::InitialInstanceFunctor {
|
||||
*/
|
||||
size_t GetInstancesCount() const { return instancesCount; }
|
||||
|
||||
void Reset() {
|
||||
highestZOrder = 0;
|
||||
lowestZOrder = 0;
|
||||
instancesCount = 0;
|
||||
firstCall = true;
|
||||
layerRestricted = false;
|
||||
layerName.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
int highestZOrder;
|
||||
int lowestZOrder;
|
||||
|
289
Core/tests/EventsIdentifiersFinder.cpp
Normal file
289
Core/tests/EventsIdentifiersFinder.cpp
Normal file
@@ -0,0 +1,289 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
/**
|
||||
* @file Tests covering common features of GDevelop Core.
|
||||
*/
|
||||
#include "GDCore/IDE/Events/EventsIdentifiersFinder.h"
|
||||
#include "GDCore/Events/Builtin/LinkEvent.h"
|
||||
#include "GDCore/Events/Builtin/StandardEvent.h"
|
||||
#include "GDCore/Events/Event.h"
|
||||
#include "GDCore/Extensions/Builtin/AllBuiltinExtensions.h"
|
||||
#include "GDCore/Extensions/Platform.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "catch.hpp"
|
||||
|
||||
namespace {
|
||||
const void DeclareTimerExtension(gd::Project &project, gd::Platform &platform) {
|
||||
std::shared_ptr<gd::PlatformExtension> extension =
|
||||
std::shared_ptr<gd::PlatformExtension>(new gd::PlatformExtension);
|
||||
gd::BuiltinExtensionsImplementer::ImplementsTimeExtension(*(extension.get()));
|
||||
gd::BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
*(extension.get()));
|
||||
// Add an instruction to test expressions.
|
||||
extension
|
||||
->AddAction("DoSomething", "Do something", "This does something",
|
||||
"Do something please", "", "", "")
|
||||
.AddParameter("expression", "Parameter 1 (a number)");
|
||||
platform.AddExtension(extension);
|
||||
project.AddPlatform(platform);
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseSceneTimer(const gd::String &name) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("ResetTimer");
|
||||
instruction.SetParametersCount(2);
|
||||
instruction.SetParameter(0, gd::Expression("scene"));
|
||||
instruction.SetParameter(1, gd::Expression("\"" + name + "\""));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseObjectTimer(const gd::String &objectName,
|
||||
const gd::String &timerName) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("ResetObjectTimer");
|
||||
instruction.SetParametersCount(2);
|
||||
instruction.SetParameter(0, gd::Expression(objectName));
|
||||
instruction.SetParameter(1, gd::Expression("\"" + timerName + "\""));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseSceneTimerInExpression(const gd::String &name) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("DoSomething");
|
||||
instruction.SetParametersCount(1);
|
||||
instruction.SetParameter(
|
||||
0, gd::Expression("1 + TimerElapsedTime(\"" + name + "\")"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent
|
||||
UseObjectTimerInExpression(const gd::String &objectName,
|
||||
const gd::String &timerName) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("DoSomething");
|
||||
instruction.SetParametersCount(1);
|
||||
instruction.SetParameter(0, gd::Expression("1 + " + objectName +
|
||||
".ObjectTimerElapsedTime(\"" + timerName +
|
||||
"\")"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const void UseExternalEvents(gd::Layout &layout,
|
||||
gd::ExternalEvents &externalEvents) {
|
||||
gd::LinkEvent linkEvent;
|
||||
linkEvent.SetTarget(externalEvents.GetName());
|
||||
layout.GetEvents().InsertEvent(linkEvent);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("EventsIdentifiersFinder (scene timers)", "[common]") {
|
||||
SECTION("Can find scene timers in scenes") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
layout.GetEvents().InsertEvent(UseSceneTimer("MySceneTimer"));
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "sceneTimer");
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MySceneTimer\"");
|
||||
}
|
||||
|
||||
SECTION("Can find scene timers in scene expressions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
layout.GetEvents().InsertEvent(UseSceneTimerInExpression("MySceneTimer"));
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "sceneTimer");
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MySceneTimer\"");
|
||||
}
|
||||
|
||||
SECTION("Can find scene timers in external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(UseSceneTimer("MySceneTimer"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "sceneTimer");
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MySceneTimer\"");
|
||||
}
|
||||
|
||||
SECTION("Can find scene timers the right scene") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout1 = project.InsertNewLayout("Layout1", 0);
|
||||
layout1.GetEvents().InsertEvent(UseSceneTimer("MySceneTimerInLayout1"));
|
||||
|
||||
auto &layout2 = project.InsertNewLayout("Layout2", 0);
|
||||
layout2.GetEvents().InsertEvent(UseSceneTimer("MySceneTimerInLayout2"));
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout1, "sceneTimer");
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MySceneTimerInLayout1\"");
|
||||
}
|
||||
|
||||
SECTION("Can find scene timers in the right external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout1 = project.InsertNewLayout("Layout1", 0);
|
||||
auto &externalEvents1 =
|
||||
project.InsertNewExternalEvents("ExternalEvents1", 0);
|
||||
externalEvents1.GetEvents().InsertEvent(
|
||||
UseSceneTimer("MySceneTimerInExternalEvents1"));
|
||||
UseExternalEvents(layout1, externalEvents1);
|
||||
|
||||
auto &layout2 = project.InsertNewLayout("Layout2", 0);
|
||||
auto &externalEvents2 =
|
||||
project.InsertNewExternalEvents("ExternalEvents2", 0);
|
||||
externalEvents2.GetEvents().InsertEvent(
|
||||
UseSceneTimer("MySceneTimerInExternalEvents2"));
|
||||
UseExternalEvents(layout2, externalEvents2);
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout1, "sceneTimer");
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) ==
|
||||
"\"MySceneTimerInExternalEvents1\"");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("EventsIdentifiersFinder (object timers)", "[common]") {
|
||||
SECTION("Can find object timers in scenes") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object = layout.InsertNewObject(project, "", "MyObject", 0);
|
||||
layout.GetEvents().InsertEvent(UseObjectTimer("MyObject", "MyObjectTimer"));
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "objectTimer", object.GetName());
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MyObjectTimer\"");
|
||||
}
|
||||
|
||||
SECTION("Can find object timers in scene expression") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object = layout.InsertNewObject(project, "", "MyObject", 0);
|
||||
layout.GetEvents().InsertEvent(UseObjectTimerInExpression("MyObject", "MyObjectTimer"));
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "objectTimer", object.GetName());
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MyObjectTimer\"");
|
||||
}
|
||||
|
||||
SECTION("Can find object timers in external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object = layout.InsertNewObject(project, "", "MyObject", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseObjectTimer("MyObject", "MyObjectTimer"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "objectTimer", object.GetName());
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MyObjectTimer\"");
|
||||
}
|
||||
|
||||
SECTION("Can find object timers in scenes for the right object") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object1 = layout.InsertNewObject(project, "", "MyObject1", 0);
|
||||
auto &object2 = layout.InsertNewObject(project, "", "MyObject2", 0);
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseObjectTimer("MyObject1", "MyObjectTimer1"));
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseObjectTimer("MyObject2", "MyObjectTimer2"));
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "objectTimer", object1.GetName());
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MyObjectTimer1\"");
|
||||
}
|
||||
|
||||
SECTION("Can find object timers in external layouts for the right object") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareTimerExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object1 = layout.InsertNewObject(project, "", "MyObject1", 0);
|
||||
auto &object2 = layout.InsertNewObject(project, "", "MyObject2", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseObjectTimer("MyObject1", "MyObjectTimer1"));
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseObjectTimer("MyObject2", "MyObjectTimer2"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto identifierExpressions =
|
||||
gd::EventsIdentifiersFinder::FindAllIdentifierExpressions(
|
||||
platform, project, layout, "objectTimer", object1.GetName());
|
||||
|
||||
REQUIRE(identifierExpressions.size() == 1);
|
||||
REQUIRE(*(identifierExpressions.begin()) == "\"MyObjectTimer1\"");
|
||||
}
|
||||
}
|
360
Core/tests/EventsVariablesFinder.cpp
Normal file
360
Core/tests/EventsVariablesFinder.cpp
Normal file
@@ -0,0 +1,360 @@
|
||||
/*
|
||||
* GDevelop Core
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
/**
|
||||
* @file Tests covering common features of GDevelop Core.
|
||||
*/
|
||||
#include "GDCore/IDE/Events/EventsVariablesFinder.h"
|
||||
#include "GDCore/Events/Builtin/LinkEvent.h"
|
||||
#include "GDCore/Events/Builtin/StandardEvent.h"
|
||||
#include "GDCore/Events/Event.h"
|
||||
#include "GDCore/Extensions/Builtin/AllBuiltinExtensions.h"
|
||||
#include "GDCore/Extensions/Platform.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "GDCore/Project/Variable.h"
|
||||
#include "catch.hpp"
|
||||
|
||||
namespace {
|
||||
const void DeclareVariableExtension(gd::Project &project,
|
||||
gd::Platform &platform) {
|
||||
std::shared_ptr<gd::PlatformExtension> extension =
|
||||
std::shared_ptr<gd::PlatformExtension>(new gd::PlatformExtension);
|
||||
gd::BuiltinExtensionsImplementer::ImplementsVariablesExtension(
|
||||
*(extension.get()));
|
||||
gd::BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
|
||||
*(extension.get()));
|
||||
// Add an instruction to test expressions.
|
||||
extension
|
||||
->AddAction("DoSomething", "Do something", "This does something",
|
||||
"Do something please", "", "", "")
|
||||
.AddParameter("expression", "Parameter 1 (a number)");
|
||||
platform.AddExtension(extension);
|
||||
project.AddPlatform(platform);
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseGlobalVariable(const gd::String &name) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("ModVarGlobal");
|
||||
instruction.SetParametersCount(2);
|
||||
instruction.SetParameter(0, gd::Expression(name));
|
||||
instruction.SetParameter(1, gd::Expression("0"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseSceneVariable(const gd::String &name) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("ModVarScene");
|
||||
instruction.SetParametersCount(2);
|
||||
instruction.SetParameter(0, gd::Expression(name));
|
||||
instruction.SetParameter(1, gd::Expression("0"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseObjectVariable(const gd::String &objectName,
|
||||
const gd::String &variableName) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("ModVarObjet");
|
||||
instruction.SetParametersCount(3);
|
||||
instruction.SetParameter(0, gd::Expression(objectName));
|
||||
instruction.SetParameter(1, gd::Expression(variableName));
|
||||
instruction.SetParameter(2, gd::Expression("0"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseGlobalVariableInExpression(const gd::String &name) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("DoSomething");
|
||||
instruction.SetParametersCount(1);
|
||||
instruction.SetParameter(0,
|
||||
gd::Expression("1 + GlobalVariable(" + name + ")"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent UseSceneVariableInExpression(const gd::String &name) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("DoSomething");
|
||||
instruction.SetParametersCount(1);
|
||||
instruction.SetParameter(0, gd::Expression("1 + Variable(" + name + ")"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const gd::StandardEvent
|
||||
UseObjectVariableInExpression(const gd::String &objectName,
|
||||
const gd::String &variableName) {
|
||||
gd::StandardEvent event;
|
||||
gd::Instruction instruction;
|
||||
instruction.SetType("DoSomething");
|
||||
instruction.SetParametersCount(1);
|
||||
instruction.SetParameter(
|
||||
0,
|
||||
gd::Expression("1 + " + objectName + ".Variable(" + variableName + ")"));
|
||||
event.GetActions().Insert(instruction);
|
||||
return event;
|
||||
}
|
||||
|
||||
const void UseExternalEvents(gd::Layout &layout,
|
||||
gd::ExternalEvents &externalEvents) {
|
||||
gd::LinkEvent linkEvent;
|
||||
linkEvent.SetTarget(externalEvents.GetName());
|
||||
layout.GetEvents().InsertEvent(linkEvent);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("EventsVariablesFinder (FindAllGlobalVariables)", "[common]") {
|
||||
SECTION("Can find global variables in scenes") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
layout.GetEvents().InsertEvent(UseGlobalVariable("MyGlobalVariable"));
|
||||
|
||||
auto variableNames =
|
||||
gd::EventsVariablesFinder::FindAllGlobalVariables(platform, project);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyGlobalVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find global variables in scene expressions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseGlobalVariableInExpression("MyGlobalVariable"));
|
||||
|
||||
auto variableNames =
|
||||
gd::EventsVariablesFinder::FindAllGlobalVariables(platform, project);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyGlobalVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find global variables in external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseGlobalVariable("MyGlobalVariable"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto variableNames =
|
||||
gd::EventsVariablesFinder::FindAllGlobalVariables(platform, project);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyGlobalVariable");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("EventsVariablesFinder (FindAllLayoutVariables)", "[common]") {
|
||||
SECTION("Can find scene variables in scenes") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
layout.GetEvents().InsertEvent(UseSceneVariable("MySceneVariable"));
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllLayoutVariables(
|
||||
platform, project, layout);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MySceneVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find scene variables in scene expressions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseSceneVariableInExpression("MySceneVariable"));
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllLayoutVariables(
|
||||
platform, project, layout);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MySceneVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find scene variables in external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(UseSceneVariable("MySceneVariable"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllLayoutVariables(
|
||||
platform, project, layout);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MySceneVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find scene variables the right scene") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout1 = project.InsertNewLayout("Layout1", 0);
|
||||
layout1.GetEvents().InsertEvent(
|
||||
UseSceneVariable("MySceneVariableInLayout1"));
|
||||
|
||||
auto &layout2 = project.InsertNewLayout("Layout2", 0);
|
||||
layout2.GetEvents().InsertEvent(
|
||||
UseSceneVariable("MySceneVariableInLayout2"));
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllLayoutVariables(
|
||||
platform, project, layout1);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MySceneVariableInLayout1");
|
||||
}
|
||||
|
||||
SECTION("Can find scene variables in the right external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout1 = project.InsertNewLayout("Layout1", 0);
|
||||
auto &externalEvents1 =
|
||||
project.InsertNewExternalEvents("ExternalEvents1", 0);
|
||||
externalEvents1.GetEvents().InsertEvent(
|
||||
UseSceneVariable("MySceneVariableInExternalEvents1"));
|
||||
UseExternalEvents(layout1, externalEvents1);
|
||||
|
||||
auto &layout2 = project.InsertNewLayout("Layout2", 0);
|
||||
auto &externalEvents2 =
|
||||
project.InsertNewExternalEvents("ExternalEvents2", 0);
|
||||
externalEvents2.GetEvents().InsertEvent(
|
||||
UseSceneVariable("MySceneVariableInExternalEvents2"));
|
||||
UseExternalEvents(layout2, externalEvents2);
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllLayoutVariables(
|
||||
platform, project, layout1);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MySceneVariableInExternalEvents1");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("EventsVariablesFinder (FindAllObjectVariables)", "[common]") {
|
||||
SECTION("Can find object variables in scenes") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object = layout.InsertNewObject(project, "", "MyObject", 0);
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseObjectVariable("MyObject", "MyObjectVariable"));
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllObjectVariables(
|
||||
platform, project, layout, object);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyObjectVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find object variables in scene expressions") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object = layout.InsertNewObject(project, "", "MyObject", 0);
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseObjectVariableInExpression("MyObject", "MyObjectVariable"));
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllObjectVariables(
|
||||
platform, project, layout, object);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyObjectVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find object variables in external layouts") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object = layout.InsertNewObject(project, "", "MyObject", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseObjectVariable("MyObject", "MyObjectVariable"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllObjectVariables(
|
||||
platform, project, layout, object);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyObjectVariable");
|
||||
}
|
||||
|
||||
SECTION("Can find object variables in scenes for the right object") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object1 = layout.InsertNewObject(project, "", "MyObject1", 0);
|
||||
auto &object2 = layout.InsertNewObject(project, "", "MyObject2", 0);
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseObjectVariable("MyObject1", "MyObjectVariable1"));
|
||||
layout.GetEvents().InsertEvent(
|
||||
UseObjectVariable("MyObject2", "MyObjectVariable2"));
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllObjectVariables(
|
||||
platform, project, layout, object1);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyObjectVariable1");
|
||||
}
|
||||
|
||||
SECTION(
|
||||
"Can find object variables in external layouts for the right object") {
|
||||
gd::Project project;
|
||||
gd::Platform platform;
|
||||
DeclareVariableExtension(project, platform);
|
||||
|
||||
auto &layout = project.InsertNewLayout("Layout1", 0);
|
||||
auto &object1 = layout.InsertNewObject(project, "", "MyObject1", 0);
|
||||
auto &object2 = layout.InsertNewObject(project, "", "MyObject2", 0);
|
||||
auto &externalEvents = project.InsertNewExternalEvents("ExternalEvents", 0);
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseObjectVariable("MyObject1", "MyObjectVariable1"));
|
||||
externalEvents.GetEvents().InsertEvent(
|
||||
UseObjectVariable("MyObject2", "MyObjectVariable2"));
|
||||
UseExternalEvents(layout, externalEvents);
|
||||
|
||||
auto variableNames = gd::EventsVariablesFinder::FindAllObjectVariables(
|
||||
platform, project, layout, object1);
|
||||
|
||||
REQUIRE(variableNames.size() == 1);
|
||||
REQUIRE(*(variableNames.begin()) == "MyObjectVariable1");
|
||||
}
|
||||
}
|
@@ -12,11 +12,12 @@
|
||||
#include "GDCore/Events/Event.h"
|
||||
#include "GDCore/Events/EventsList.h"
|
||||
#include "GDCore/Events/Serialization.h"
|
||||
#include "GDCore/Extensions/Builtin/SpriteExtension/SpriteObject.h"
|
||||
#include "GDCore/Extensions/Platform.h"
|
||||
#include "GDCore/Project/CustomObjectConfiguration.h"
|
||||
#include "GDCore/Project/EventsFunctionsExtension.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Object.h"
|
||||
#include "GDCore/Extensions/Builtin/SpriteExtension/SpriteObject.h"
|
||||
#include "GDCore/Project/ObjectsContainer.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "GDCore/Project/Variable.h"
|
||||
@@ -29,14 +30,7 @@ using namespace gd;
|
||||
|
||||
namespace {
|
||||
|
||||
void SetupProject(gd::Project &project, gd::Platform &platform) {
|
||||
SetupProjectWithDummyPlatform(project, platform);
|
||||
|
||||
gd::Layout &layout = project.InsertNewLayout("Scene", 0);
|
||||
gd::Object &object =
|
||||
layout.InsertNewObject(project, "MyExtension::Sprite", "MyObject", 0);
|
||||
|
||||
auto &configuration = object.GetConfiguration();
|
||||
void SetupSpriteConfiguration(gd::ObjectConfiguration &configuration) {
|
||||
auto *spriteConfiguration = dynamic_cast<gd::SpriteObject *>(&configuration);
|
||||
REQUIRE(spriteConfiguration != nullptr);
|
||||
gd::Animation animation;
|
||||
@@ -44,11 +38,30 @@ void SetupProject(gd::Project &project, gd::Platform &platform) {
|
||||
spriteConfiguration->AddAnimation(animation);
|
||||
};
|
||||
|
||||
void CheckSpriteConfiguration(
|
||||
SerializerElement &objectContainerElement) {
|
||||
gd::Object &SetupProjectWithSprite(gd::Project &project,
|
||||
gd::Platform &platform) {
|
||||
SetupProjectWithDummyPlatform(project, platform);
|
||||
|
||||
gd::Layout &layout = project.InsertNewLayout("Scene", 0);
|
||||
gd::Object &object =
|
||||
layout.InsertNewObject(project, "MyExtension::Sprite", "MyObject", 0);
|
||||
SetupSpriteConfiguration(object.GetConfiguration());
|
||||
|
||||
return object;
|
||||
};
|
||||
|
||||
void CheckSpriteConfigurationInElement(SerializerElement &projectElement) {
|
||||
void CheckSpriteConfigurationInObjectElement(SerializerElement &objectElement) {
|
||||
REQUIRE(objectElement.HasChild("animations"));
|
||||
auto &animationsElement = objectElement.GetChild("animations");
|
||||
animationsElement.ConsiderAsArrayOf("animation");
|
||||
REQUIRE(animationsElement.GetChildrenCount() == 1);
|
||||
auto &animationElement = animationsElement.GetChild(0);
|
||||
|
||||
REQUIRE(animationElement.GetStringAttribute("name") == "Idle");
|
||||
};
|
||||
|
||||
void CheckSpriteConfigurationInProjectElement(
|
||||
SerializerElement &projectElement) {
|
||||
auto &layoutsElement = projectElement.GetChild("layouts");
|
||||
layoutsElement.ConsiderAsArrayOf("layout");
|
||||
REQUIRE(layoutsElement.GetChildrenCount() == 1);
|
||||
@@ -64,24 +77,10 @@ void CheckSpriteConfigurationInElement(SerializerElement &projectElement) {
|
||||
|
||||
REQUIRE(objectElement.GetStringAttribute("name") == "MyObject");
|
||||
REQUIRE(objectElement.GetStringAttribute("type") == "MyExtension::Sprite");
|
||||
|
||||
REQUIRE(objectElement.HasChild("animations"));
|
||||
auto &animationsElement = objectElement.GetChild("animations");
|
||||
animationsElement.ConsiderAsArrayOf("animation");
|
||||
REQUIRE(animationsElement.GetChildrenCount() == 1);
|
||||
auto &animationElement = animationsElement.GetChild(0);
|
||||
|
||||
REQUIRE(animationElement.GetStringAttribute("name") ==
|
||||
"Idle");
|
||||
CheckSpriteConfigurationInObjectElement(objectElement);
|
||||
};
|
||||
|
||||
void CheckSpriteConfiguration(gd::Project &project) {
|
||||
auto &layout = project.GetLayout("Scene");
|
||||
auto &object = layout.GetObject("MyObject");
|
||||
REQUIRE(object.GetName() == "MyObject");
|
||||
REQUIRE(object.GetType() == "MyExtension::Sprite");
|
||||
|
||||
auto &configuration = object.GetConfiguration();
|
||||
void CheckSpriteConfiguration(gd::ObjectConfiguration &configuration) {
|
||||
auto *spriteConfiguration = dynamic_cast<gd::SpriteObject *>(&configuration);
|
||||
REQUIRE(spriteConfiguration);
|
||||
REQUIRE(spriteConfiguration->GetAnimationsCount() == 1);
|
||||
@@ -89,6 +88,88 @@ void CheckSpriteConfiguration(gd::Project &project) {
|
||||
auto &animation = spriteConfiguration->GetAnimation(0);
|
||||
REQUIRE(animation.GetName() == "Idle");
|
||||
};
|
||||
|
||||
void CheckSpriteConfiguration(gd::Object &object) {
|
||||
REQUIRE(object.GetName() == "MyObject");
|
||||
REQUIRE(object.GetType() == "MyExtension::Sprite");
|
||||
|
||||
CheckSpriteConfiguration(object.GetConfiguration());
|
||||
};
|
||||
|
||||
void CheckSpriteConfiguration(gd::Project &project) {
|
||||
auto &layout = project.GetLayout("Scene");
|
||||
auto &object = layout.GetObject("MyObject");
|
||||
CheckSpriteConfiguration(object);
|
||||
};
|
||||
|
||||
gd::Object &SetupProjectWithCustomObject(gd::Project &project,
|
||||
gd::Platform &platform) {
|
||||
SetupProjectWithDummyPlatform(project, platform);
|
||||
|
||||
auto &eventsExtension =
|
||||
project.InsertNewEventsFunctionsExtension("MyEventsExtension", 0);
|
||||
auto &eventsBasedObject = eventsExtension.GetEventsBasedObjects().InsertNew(
|
||||
"MyEventsBasedObject", 0);
|
||||
eventsBasedObject.SetFullName("My events based object");
|
||||
eventsBasedObject.SetDescription("An events based object for test");
|
||||
eventsBasedObject.InsertNewObject(project, "MyExtension::Sprite", "MyChild",
|
||||
0);
|
||||
|
||||
gd::Layout &layout = project.InsertNewLayout("Scene", 0);
|
||||
gd::Object &object = layout.InsertNewObject(
|
||||
project, "MyEventsExtension::MyEventsBasedObject", "MyObject", 0);
|
||||
auto &configuration = object.GetConfiguration();
|
||||
auto *customObjectConfiguration =
|
||||
dynamic_cast<gd::CustomObjectConfiguration *>(&configuration);
|
||||
auto &spriteConfiguration =
|
||||
customObjectConfiguration->GetChildObjectConfiguration("MyChild");
|
||||
SetupSpriteConfiguration(spriteConfiguration);
|
||||
|
||||
return object;
|
||||
};
|
||||
|
||||
void CheckCustomObjectConfigurationInProjectElement(
|
||||
SerializerElement &projectElement) {
|
||||
auto &layoutsElement = projectElement.GetChild("layouts");
|
||||
layoutsElement.ConsiderAsArrayOf("layout");
|
||||
REQUIRE(layoutsElement.GetChildrenCount() == 1);
|
||||
auto &layoutElement = layoutsElement.GetChild(0);
|
||||
|
||||
REQUIRE(layoutElement.GetStringAttribute("name") == "Scene");
|
||||
REQUIRE(layoutElement.HasChild("objects"));
|
||||
|
||||
auto &objectsElement = layoutElement.GetChild("objects");
|
||||
objectsElement.ConsiderAsArrayOf("object");
|
||||
REQUIRE(objectsElement.GetChildrenCount() == 1);
|
||||
auto &objectElement = objectsElement.GetChild(0);
|
||||
|
||||
REQUIRE(objectElement.GetStringAttribute("name") == "MyObject");
|
||||
REQUIRE(objectElement.GetStringAttribute("type") ==
|
||||
"MyEventsExtension::MyEventsBasedObject");
|
||||
auto &childrenContentElement = objectElement.GetChild("childrenContent");
|
||||
|
||||
REQUIRE(childrenContentElement.HasChild("MyChild"));
|
||||
auto &childElement = childrenContentElement.GetChild("MyChild");
|
||||
CheckSpriteConfigurationInObjectElement(childElement);
|
||||
};
|
||||
|
||||
void CheckCustomObjectConfiguration(gd::Object &object) {
|
||||
REQUIRE(object.GetName() == "MyObject");
|
||||
REQUIRE(object.GetType() == "MyEventsExtension::MyEventsBasedObject");
|
||||
|
||||
auto &configuration = object.GetConfiguration();
|
||||
auto *customObjectConfiguration =
|
||||
dynamic_cast<gd::CustomObjectConfiguration *>(&configuration);
|
||||
auto &spriteConfiguration =
|
||||
customObjectConfiguration->GetChildObjectConfiguration("MyChild");
|
||||
CheckSpriteConfiguration(spriteConfiguration);
|
||||
};
|
||||
|
||||
void CheckCustomObjectConfiguration(gd::Project &project) {
|
||||
auto &layout = project.GetLayout("Scene");
|
||||
auto &object = layout.GetObject("MyObject");
|
||||
CheckCustomObjectConfiguration(object);
|
||||
};
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("ObjectSerialization", "[common]") {
|
||||
@@ -96,16 +177,52 @@ TEST_CASE("ObjectSerialization", "[common]") {
|
||||
SECTION("Save and load a project with a sprite configuration") {
|
||||
gd::Platform platform;
|
||||
gd::Project writtenProject;
|
||||
SetupProject(writtenProject, platform);
|
||||
SetupProjectWithSprite(writtenProject, platform);
|
||||
CheckSpriteConfiguration(writtenProject);
|
||||
|
||||
SerializerElement projectElement;
|
||||
writtenProject.SerializeTo(projectElement);
|
||||
CheckSpriteConfigurationInElement(projectElement);
|
||||
CheckSpriteConfigurationInProjectElement(projectElement);
|
||||
|
||||
gd::Project readProject;
|
||||
readProject.AddPlatform(platform);
|
||||
readProject.UnserializeFrom(projectElement);
|
||||
CheckSpriteConfiguration(readProject);
|
||||
}
|
||||
|
||||
SECTION("Clone a sprite object") {
|
||||
gd::Platform platform;
|
||||
gd::Project project;
|
||||
auto &object = SetupProjectWithSprite(project, platform);
|
||||
CheckSpriteConfiguration(object);
|
||||
|
||||
auto clonedObject = object.Clone();
|
||||
CheckSpriteConfiguration(*(clonedObject.get()));
|
||||
}
|
||||
|
||||
SECTION("Save and load a project with a custom object configuration") {
|
||||
gd::Platform platform;
|
||||
gd::Project writtenProject;
|
||||
SetupProjectWithCustomObject(writtenProject, platform);
|
||||
CheckCustomObjectConfiguration(writtenProject);
|
||||
|
||||
SerializerElement projectElement;
|
||||
writtenProject.SerializeTo(projectElement);
|
||||
CheckCustomObjectConfigurationInProjectElement(projectElement);
|
||||
|
||||
gd::Project readProject;
|
||||
readProject.AddPlatform(platform);
|
||||
readProject.UnserializeFrom(projectElement);
|
||||
CheckCustomObjectConfiguration(readProject);
|
||||
}
|
||||
|
||||
SECTION("Clone a custom object") {
|
||||
gd::Platform platform;
|
||||
gd::Project project;
|
||||
auto &object = SetupProjectWithCustomObject(project, platform);
|
||||
CheckCustomObjectConfiguration(object);
|
||||
|
||||
auto clonedObject = object.Clone();
|
||||
CheckCustomObjectConfiguration(*(clonedObject.get()));
|
||||
}
|
||||
}
|
@@ -30,6 +30,8 @@
|
||||
#include "GDCore/Project/Variable.h"
|
||||
#include "catch.hpp"
|
||||
|
||||
// TODO EBO Add a test where a child is removed form the EventsBasedObject
|
||||
// and check the configuration still gives access to other child configuration.
|
||||
namespace {
|
||||
|
||||
const gd::StandardEvent &EnsureStandardEvent(const gd::BaseEvent &baseEvent) {
|
||||
|
@@ -105,9 +105,9 @@ std::map<gd::String, gd::PropertyDescriptor> AnchorBehavior::GetProperties(
|
||||
|
||||
properties[("useLegacyBottomAndRightAnchors")]
|
||||
.SetLabel(_(
|
||||
"Stretch object when anchoring right or bottom ledge (deprecated, "
|
||||
"it's recommended to let this unchecked and anchor both sides if you "
|
||||
"want Sprite to stretch instead.)"))
|
||||
"Stretch object when anchoring right or bottom edge (deprecated, "
|
||||
"it's recommended to leave this unchecked and anchor both sides if "
|
||||
"you want Sprite to stretch instead.)"))
|
||||
.SetGroup(_("Deprecated options (advanced)"))
|
||||
.SetValue(behaviorContent.GetBoolAttribute(
|
||||
"useLegacyBottomAndRightAnchors", true)
|
||||
|
@@ -17,8 +17,12 @@ namespace gdjs {
|
||||
_bottomEdgeDistance: number = 0;
|
||||
_useLegacyBottomAndRightAnchors: boolean = false;
|
||||
|
||||
constructor(runtimeScene, behaviorData, owner) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._relativeToOriginalWindowSize = !!behaviorData.relativeToOriginalWindowSize;
|
||||
this._leftEdgeAnchor = behaviorData.leftEdgeAnchor;
|
||||
this._rightEdgeAnchor = behaviorData.rightEdgeAnchor;
|
||||
@@ -65,11 +69,15 @@ namespace gdjs {
|
||||
this._invalidDistances = true;
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene) {
|
||||
const game = runtimeScene.getGame();
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
gdjs.AnchorRuntimeBehavior.prototype.doStepPreEvents
|
||||
) as FloatPoint;
|
||||
// TODO EBO Make it work with event based objects or hide this behavior for them.
|
||||
const game = instanceContainer.getGame();
|
||||
let rendererWidth = game.getGameResolutionWidth();
|
||||
let rendererHeight = game.getGameResolutionHeight();
|
||||
const layer = runtimeScene.getLayer(this.owner.getLayer());
|
||||
const layer = instanceContainer.getLayer(this.owner.getLayer());
|
||||
if (this._invalidDistances) {
|
||||
if (this._relativeToOriginalWindowSize) {
|
||||
rendererWidth = game.getOriginalWidth();
|
||||
@@ -79,7 +87,9 @@ namespace gdjs {
|
||||
//Calculate the distances from the window's bounds.
|
||||
const topLeftPixel = layer.convertCoords(
|
||||
this.owner.getDrawableX(),
|
||||
this.owner.getDrawableY()
|
||||
this.owner.getDrawableY(),
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
|
||||
//Left edge
|
||||
@@ -125,9 +135,12 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
}
|
||||
// It's fine to reuse workingPoint as topLeftPixel is no longer used.
|
||||
const bottomRightPixel = layer.convertCoords(
|
||||
this.owner.getDrawableX() + this.owner.getWidth(),
|
||||
this.owner.getDrawableY() + this.owner.getHeight()
|
||||
this.owner.getDrawableY() + this.owner.getHeight(),
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
|
||||
//Right edge
|
||||
@@ -268,11 +281,24 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
}
|
||||
const topLeftCoord = layer.convertInverseCoords(leftPixel, topPixel);
|
||||
// It's fine to reuse workingPoint as topLeftPixel is no longer used.
|
||||
const topLeftCoord = layer.convertInverseCoords(
|
||||
leftPixel,
|
||||
topPixel,
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
const left = topLeftCoord[0];
|
||||
const top = topLeftCoord[1];
|
||||
|
||||
const bottomRightCoord = layer.convertInverseCoords(
|
||||
rightPixel,
|
||||
bottomPixel
|
||||
bottomPixel,
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
const right = bottomRightCoord[0];
|
||||
const bottom = bottomRightCoord[1];
|
||||
|
||||
// Compatibility with GD <= 5.0.133
|
||||
if (this._useLegacyBottomAndRightAnchors) {
|
||||
@@ -281,25 +307,25 @@ namespace gdjs {
|
||||
this._rightEdgeAnchor !==
|
||||
AnchorRuntimeBehavior.HorizontalAnchor.NONE
|
||||
) {
|
||||
this.owner.setWidth(bottomRightCoord[0] - topLeftCoord[0]);
|
||||
this.owner.setWidth(right - left);
|
||||
}
|
||||
if (
|
||||
this._bottomEdgeAnchor !== AnchorRuntimeBehavior.VerticalAnchor.NONE
|
||||
) {
|
||||
this.owner.setHeight(bottomRightCoord[1] - topLeftCoord[1]);
|
||||
this.owner.setHeight(bottom - top);
|
||||
}
|
||||
if (
|
||||
this._leftEdgeAnchor !== AnchorRuntimeBehavior.HorizontalAnchor.NONE
|
||||
) {
|
||||
this.owner.setX(
|
||||
topLeftCoord[0] + this.owner.getX() - this.owner.getDrawableX()
|
||||
left + this.owner.getX() - this.owner.getDrawableX()
|
||||
);
|
||||
}
|
||||
if (
|
||||
this._topEdgeAnchor !== AnchorRuntimeBehavior.VerticalAnchor.NONE
|
||||
) {
|
||||
this.owner.setY(
|
||||
topLeftCoord[1] + this.owner.getY() - this.owner.getDrawableY()
|
||||
top + this.owner.getY() - this.owner.getDrawableY()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -311,15 +337,15 @@ namespace gdjs {
|
||||
AnchorRuntimeBehavior.HorizontalAnchor.NONE &&
|
||||
this._leftEdgeAnchor !== AnchorRuntimeBehavior.HorizontalAnchor.NONE
|
||||
) {
|
||||
this.owner.setWidth(bottomRightCoord[0] - topLeftCoord[0]);
|
||||
this.owner.setX(topLeftCoord[0]);
|
||||
this.owner.setWidth(right - left);
|
||||
this.owner.setX(left);
|
||||
} else {
|
||||
if (
|
||||
this._leftEdgeAnchor !==
|
||||
AnchorRuntimeBehavior.HorizontalAnchor.NONE
|
||||
) {
|
||||
this.owner.setX(
|
||||
topLeftCoord[0] + this.owner.getX() - this.owner.getDrawableX()
|
||||
left + this.owner.getX() - this.owner.getDrawableX()
|
||||
);
|
||||
}
|
||||
if (
|
||||
@@ -327,7 +353,7 @@ namespace gdjs {
|
||||
AnchorRuntimeBehavior.HorizontalAnchor.NONE
|
||||
) {
|
||||
this.owner.setX(
|
||||
bottomRightCoord[0] +
|
||||
right +
|
||||
this.owner.getX() -
|
||||
this.owner.getDrawableX() -
|
||||
this.owner.getWidth()
|
||||
@@ -340,14 +366,14 @@ namespace gdjs {
|
||||
AnchorRuntimeBehavior.VerticalAnchor.NONE &&
|
||||
this._topEdgeAnchor !== AnchorRuntimeBehavior.VerticalAnchor.NONE
|
||||
) {
|
||||
this.owner.setHeight(bottomRightCoord[1] - topLeftCoord[1]);
|
||||
this.owner.setY(topLeftCoord[1]);
|
||||
this.owner.setHeight(bottom - top);
|
||||
this.owner.setY(top);
|
||||
} else {
|
||||
if (
|
||||
this._topEdgeAnchor !== AnchorRuntimeBehavior.VerticalAnchor.NONE
|
||||
) {
|
||||
this.owner.setY(
|
||||
topLeftCoord[1] + this.owner.getY() - this.owner.getDrawableY()
|
||||
top + this.owner.getY() - this.owner.getDrawableY()
|
||||
);
|
||||
}
|
||||
if (
|
||||
@@ -355,7 +381,7 @@ namespace gdjs {
|
||||
AnchorRuntimeBehavior.VerticalAnchor.NONE
|
||||
) {
|
||||
this.owner.setY(
|
||||
bottomRightCoord[1] +
|
||||
bottom +
|
||||
this.owner.getY() -
|
||||
this.owner.getDrawableY() -
|
||||
this.owner.getHeight()
|
||||
@@ -366,7 +392,7 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene) {}
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
static HorizontalAnchor = {
|
||||
NONE: 0,
|
||||
|
@@ -10,11 +10,11 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* @param runtimeObject The object to render
|
||||
* @param runtimeScene The gdjs.RuntimeScene in which the object is
|
||||
* @param instanceContainer The gdjs.RuntimeInstanceContainer in which the object is
|
||||
*/
|
||||
constructor(
|
||||
runtimeObject: gdjs.BBTextRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace gdjs {
|
||||
if (this._pixiObject === undefined) {
|
||||
this._pixiObject = new MultiStyleText(runtimeObject._text, {
|
||||
default: {
|
||||
fontFamily: runtimeScene
|
||||
fontFamily: instanceContainer
|
||||
.getGame()
|
||||
.getFontManager()
|
||||
.getFontFamily(runtimeObject._fontFamily),
|
||||
@@ -44,7 +44,7 @@ namespace gdjs {
|
||||
this.updateFontFamily();
|
||||
this.updateFontSize();
|
||||
}
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._pixiObject, runtimeObject.getZOrder());
|
||||
@@ -95,7 +95,8 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateFontFamily(): void {
|
||||
this._pixiObject.textStyles.default.fontFamily = this._object._runtimeScene
|
||||
this._pixiObject.textStyles.default.fontFamily = this._object
|
||||
.getInstanceContainer()
|
||||
.getGame()
|
||||
.getFontManager()
|
||||
.getFontFamily(this._object._fontFamily);
|
||||
|
@@ -48,11 +48,14 @@ namespace gdjs {
|
||||
hidden: boolean;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param objectData The object data used to initialize the object
|
||||
*/
|
||||
constructor(runtimeScene: gdjs.RuntimeScene, objectData: BBTextObjectData) {
|
||||
super(runtimeScene, objectData);
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objectData: BBTextObjectData
|
||||
) {
|
||||
super(instanceContainer, objectData);
|
||||
// @ts-ignore - parseFloat should not be required, but GDevelop 5.0 beta 92 and below were storing it as a string.
|
||||
this._opacity = parseFloat(objectData.content.opacity);
|
||||
this._text = objectData.content.text;
|
||||
@@ -62,7 +65,10 @@ namespace gdjs {
|
||||
this._fontSize = parseFloat(objectData.content.fontSize);
|
||||
this._wordWrap = objectData.content.wordWrap;
|
||||
this._align = objectData.content.align;
|
||||
this._renderer = new gdjs.BBTextRuntimeObjectRenderer(this, runtimeScene);
|
||||
this._renderer = new gdjs.BBTextRuntimeObjectRenderer(
|
||||
this,
|
||||
instanceContainer
|
||||
);
|
||||
this.hidden = !objectData.content.visible;
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
@@ -122,8 +128,8 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -239,7 +245,7 @@ namespace gdjs {
|
||||
|
||||
this._wrappingWidth = width;
|
||||
this._renderer.updateWrappingWidth();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -254,7 +260,7 @@ namespace gdjs {
|
||||
|
||||
this._wordWrap = wordWrap;
|
||||
this._renderer.updateWordWrap();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getWordWrap() {
|
||||
|
@@ -10,16 +10,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* @param runtimeObject The object to render
|
||||
* @param runtimeScene The gdjs.RuntimeScene in which the object is
|
||||
* @param instanceContainer The container in which the object is
|
||||
*/
|
||||
constructor(
|
||||
runtimeObject: gdjs.BitmapTextRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
|
||||
// Obtain the bitmap font to use in the object.
|
||||
const bitmapFont = runtimeScene
|
||||
const bitmapFont = instanceContainer
|
||||
.getGame()
|
||||
.getBitmapFontManager()
|
||||
.obtainBitmapFont(
|
||||
@@ -32,7 +32,7 @@ namespace gdjs {
|
||||
});
|
||||
|
||||
// Set the object on the scene
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._pixiObject, runtimeObject.getZOrder());
|
||||
@@ -59,7 +59,8 @@ namespace gdjs {
|
||||
|
||||
onDestroy() {
|
||||
// Mark the font from the object as not used anymore.
|
||||
this._object._runtimeScene
|
||||
this._object
|
||||
.getInstanceContainer()
|
||||
.getGame()
|
||||
.getBitmapFontManager()
|
||||
.releaseBitmapFont(this._pixiObject.fontName);
|
||||
@@ -73,7 +74,8 @@ namespace gdjs {
|
||||
|
||||
updateFont(): void {
|
||||
// Get the new bitmap font to use
|
||||
const bitmapFont = this._object._runtimeScene
|
||||
const bitmapFont = this._object
|
||||
.getInstanceContainer()
|
||||
.getGame()
|
||||
.getBitmapFontManager()
|
||||
.obtainBitmapFont(
|
||||
@@ -82,7 +84,8 @@ namespace gdjs {
|
||||
);
|
||||
|
||||
// Mark the old font as not used anymore
|
||||
this._object._runtimeScene
|
||||
this._object
|
||||
.getInstanceContainer()
|
||||
.getGame()
|
||||
.getBitmapFontManager()
|
||||
.releaseBitmapFont(this._pixiObject.fontName);
|
||||
|
@@ -50,14 +50,14 @@ namespace gdjs {
|
||||
_renderer: gdjs.BitmapTextRuntimeObjectPixiRenderer;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param objectData The object data used to initialize the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objectData: BitmapTextObjectData
|
||||
) {
|
||||
super(runtimeScene, objectData);
|
||||
super(instanceContainer, objectData);
|
||||
|
||||
this._opacity = objectData.content.opacity;
|
||||
this._text = objectData.content.text;
|
||||
@@ -73,7 +73,7 @@ namespace gdjs {
|
||||
|
||||
this._renderer = new gdjs.BitmapTextRuntimeObjectRenderer(
|
||||
this,
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
@@ -137,8 +137,8 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene: gdjs.RuntimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
this._renderer.onDestroy();
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ namespace gdjs {
|
||||
setText(text: string): void {
|
||||
this._text = text;
|
||||
this._renderer.updateTextContent();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,7 +170,7 @@ namespace gdjs {
|
||||
setScale(scale: float): void {
|
||||
this._scale = scale;
|
||||
this._renderer.updateScale();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getScale(): float {
|
||||
@@ -276,7 +276,7 @@ namespace gdjs {
|
||||
setWrappingWidth(width: float): void {
|
||||
this._wrappingWidth = width;
|
||||
this._renderer.updateWrappingWidth();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,7 +289,7 @@ namespace gdjs {
|
||||
setWordWrap(wordWrap: boolean): void {
|
||||
this._wordWrap = wordWrap;
|
||||
this._renderer.updateWrappingWidth();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getWordWrap(): boolean {
|
||||
|
@@ -7,10 +7,12 @@ namespace gdjs {
|
||||
export namespace debuggerTools {
|
||||
/**
|
||||
* Stop the game execution.
|
||||
* @param runtimeScene - The current scene.
|
||||
* @param instanceContainer - The current container.
|
||||
*/
|
||||
export const pause = function (runtimeScene: gdjs.RuntimeScene) {
|
||||
runtimeScene.getGame().pause(true);
|
||||
export const pause = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
instanceContainer.getGame().pause(true);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -29,20 +31,20 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Enable or disable the debug draw.
|
||||
* @param runtimeScene - The current scene.
|
||||
* @param instanceContainer - The current container.
|
||||
* @param enableDebugDraw - true to enable the debug draw, false to disable it.
|
||||
* @param showHiddenInstances - true to apply the debug draw to hidden objects.
|
||||
* @param showPointsNames - true to show point names.
|
||||
* @param showCustomPoints - true to show custom points of Sprite objects.
|
||||
*/
|
||||
export const enableDebugDraw = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
enableDebugDraw: boolean,
|
||||
showHiddenInstances: boolean,
|
||||
showPointsNames: boolean,
|
||||
showCustomPoints: boolean
|
||||
) {
|
||||
runtimeScene.enableDebugDraw(
|
||||
instanceContainer.enableDebugDraw(
|
||||
enableDebugDraw,
|
||||
showHiddenInstances,
|
||||
showPointsNames,
|
||||
|
@@ -11,8 +11,12 @@ namespace gdjs {
|
||||
export class DestroyOutsideRuntimeBehavior extends gdjs.RuntimeBehavior {
|
||||
_extraBorder: any;
|
||||
|
||||
constructor(runtimeScene, behaviorData, owner) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner
|
||||
) {
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._extraBorder = behaviorData.extraBorder || 0;
|
||||
}
|
||||
|
||||
@@ -23,14 +27,14 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene) {
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// TODO: This would better be done using the object AABB (getAABB), as (`getCenterX`;`getCenterY`) point
|
||||
// is not necessarily in the middle of the object (for sprites for example).
|
||||
const ow = this.owner.getWidth();
|
||||
const oh = this.owner.getHeight();
|
||||
const ocx = this.owner.getDrawableX() + this.owner.getCenterX();
|
||||
const ocy = this.owner.getDrawableY() + this.owner.getCenterY();
|
||||
const layer = runtimeScene.getLayer(this.owner.getLayer());
|
||||
const layer = instanceContainer.getLayer(this.owner.getLayer());
|
||||
const boundingCircleRadius = Math.sqrt(ow * ow + oh * oh) / 2.0;
|
||||
if (
|
||||
ocx + boundingCircleRadius + this._extraBorder <
|
||||
@@ -43,7 +47,7 @@ namespace gdjs {
|
||||
layer.getCameraY() + layer.getCameraHeight() / 2
|
||||
) {
|
||||
//We are outside the camera area.
|
||||
this.owner.deleteFromScene(runtimeScene);
|
||||
this.owner.deleteFromScene(instanceContainer);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -30,16 +30,16 @@ namespace gdjs {
|
||||
/**
|
||||
* Load the Dialogue Tree data from a JSON resource.
|
||||
*
|
||||
* @param runtimeScene The scene where the dialogue is running.
|
||||
* @param instanceContainer The scene where the dialogue is running.
|
||||
* @param jsonResourceName The JSON resource where to load the Dialogue Tree data from. The data is a JSON string usually created with [Yarn Dialogue Editor](https://github.com/InfiniteAmmoInc/Yarn).
|
||||
* @param startDialogueNode The Dialogue Branch to start the Dialogue Tree from. If left empty, the data will only be loaded, but can later be initialized via another action
|
||||
*/
|
||||
gdjs.dialogueTree.loadFromJsonFile = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
jsonResourceName: string,
|
||||
startDialogueNode: string
|
||||
) {
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getGame()
|
||||
.getJsonManager()
|
||||
.loadJson(jsonResourceName, function (error, content) {
|
||||
|
@@ -28,13 +28,11 @@ class GD_EXTENSION_API DraggableBehavior : public gd::Behavior {
|
||||
return new DraggableBehavior(*this);
|
||||
}
|
||||
|
||||
#if defined(GD_IDE_ONLY)
|
||||
virtual std::map<gd::String, gd::PropertyDescriptor> GetProperties(
|
||||
const gd::SerializerElement& behaviorContent) const override;
|
||||
virtual bool UpdateProperty(gd::SerializerElement& behaviorContent,
|
||||
const gd::String& name,
|
||||
const gd::String& value) override;
|
||||
#endif
|
||||
|
||||
virtual void InitializeContent(
|
||||
gd::SerializerElement& behaviorContent) override;
|
||||
|
@@ -34,10 +34,9 @@ void DeclareDraggableBehaviorExtension(gd::PlatformExtension& extension) {
|
||||
std::make_shared<DraggableBehavior>(),
|
||||
std::shared_ptr<gd::BehaviorsSharedData>());
|
||||
|
||||
#if defined(GD_IDE_ONLY)
|
||||
aut.AddCondition("Dragged",
|
||||
_("Being dragged"),
|
||||
_("Check if the object is being dragged"),
|
||||
_("Check if the object is being dragged."),
|
||||
_("_PARAM0_ is being dragged"),
|
||||
"",
|
||||
"CppPlatform/Extensions/draggableicon24.png",
|
||||
@@ -46,5 +45,16 @@ void DeclareDraggableBehaviorExtension(gd::PlatformExtension& extension) {
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "Draggable")
|
||||
.SetFunctionName("IsDragged");
|
||||
#endif
|
||||
|
||||
aut.AddCondition("Dropped",
|
||||
_("Was just dropped"),
|
||||
_("Check if the object was just dropped after being dragged."),
|
||||
_("_PARAM0_ was just dropped"),
|
||||
"",
|
||||
"CppPlatform/Extensions/draggableicon24.png",
|
||||
"CppPlatform/Extensions/draggableicon16.png")
|
||||
|
||||
.AddParameter("object", _("Object"))
|
||||
.AddParameter("behavior", _("Behavior"), "Draggable")
|
||||
.SetFunctionName("WasJustDropped");
|
||||
}
|
||||
|
@@ -4,7 +4,6 @@ GDevelop - Draggable Behavior Extension
|
||||
Copyright (c) 2014-2016 Florian Rival (Florian.Rival@gmail.com)
|
||||
This project is released under the MIT License.
|
||||
*/
|
||||
#if defined(GD_IDE_ONLY)
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
|
||||
@@ -32,6 +31,11 @@ class DraggableBehaviorJsExtension : public gd::PlatformExtension {
|
||||
.SetFunctionName("isDragged")
|
||||
.SetIncludeFile(
|
||||
"Extensions/DraggableBehavior/draggableruntimebehavior.js");
|
||||
GetAllConditionsForBehavior(
|
||||
"DraggableBehavior::Draggable")["DraggableBehavior::Dropped"]
|
||||
.SetFunctionName("wasJustDropped")
|
||||
.SetIncludeFile(
|
||||
"Extensions/DraggableBehavior/draggableruntimebehavior.js");
|
||||
GD_COMPLETE_EXTENSION_COMPILATION_INFORMATION();
|
||||
};
|
||||
};
|
||||
@@ -49,4 +53,3 @@ extern "C" gd::PlatformExtension* GD_EXTENSION_API CreateGDJSExtension() {
|
||||
return new DraggableBehaviorJsExtension;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
@@ -15,9 +15,14 @@ namespace gdjs {
|
||||
*/
|
||||
_draggedByDraggableManager: DraggableManager | null = null;
|
||||
_checkCollisionMask: boolean;
|
||||
_justDropped = false;
|
||||
|
||||
constructor(runtimeScene, behaviorData, owner) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner
|
||||
) {
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._checkCollisionMask = behaviorData.checkCollisionMask ? true : false;
|
||||
}
|
||||
|
||||
@@ -37,6 +42,7 @@ namespace gdjs {
|
||||
_endDrag() {
|
||||
if (this._draggedByDraggableManager) {
|
||||
this._draggedByDraggableManager.endDrag();
|
||||
this._justDropped = true;
|
||||
}
|
||||
this._draggedByDraggableManager = null;
|
||||
}
|
||||
@@ -45,21 +51,21 @@ namespace gdjs {
|
||||
this._draggedByDraggableManager = null;
|
||||
}
|
||||
|
||||
_tryBeginDrag(runtimeScene) {
|
||||
_tryBeginDrag(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
if (this._draggedByDraggableManager) {
|
||||
return false;
|
||||
}
|
||||
const inputManager = runtimeScene.getGame().getInputManager();
|
||||
const inputManager = instanceContainer.getGame().getInputManager();
|
||||
|
||||
//Try mouse
|
||||
const mouseDraggableManager = DraggableManager.getMouseManager(
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
if (
|
||||
inputManager.isMouseButtonPressed(0) &&
|
||||
!mouseDraggableManager.isDragging(this)
|
||||
) {
|
||||
if (mouseDraggableManager.tryAndTakeDragging(runtimeScene, this)) {
|
||||
if (mouseDraggableManager.tryAndTakeDragging(instanceContainer, this)) {
|
||||
this._draggedByDraggableManager = mouseDraggableManager;
|
||||
return true;
|
||||
}
|
||||
@@ -68,13 +74,15 @@ namespace gdjs {
|
||||
const touchIds = inputManager.getStartedTouchIdentifiers();
|
||||
for (let i = 0; i < touchIds.length; ++i) {
|
||||
const touchDraggableManager = DraggableManager.getTouchManager(
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
touchIds[i]
|
||||
);
|
||||
if (touchDraggableManager.isDragging(this)) {
|
||||
continue;
|
||||
}
|
||||
if (touchDraggableManager.tryAndTakeDragging(runtimeScene, this)) {
|
||||
if (
|
||||
touchDraggableManager.tryAndTakeDragging(instanceContainer, this)
|
||||
) {
|
||||
this._draggedByDraggableManager = touchDraggableManager;
|
||||
return true;
|
||||
}
|
||||
@@ -83,42 +91,54 @@ namespace gdjs {
|
||||
return false;
|
||||
}
|
||||
|
||||
_shouldEndDrag(runtimeScene) {
|
||||
_shouldEndDrag(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
if (!this._draggedByDraggableManager) {
|
||||
return false;
|
||||
}
|
||||
return this._draggedByDraggableManager.shouldEndDrag(runtimeScene, this);
|
||||
return this._draggedByDraggableManager.shouldEndDrag(
|
||||
instanceContainer,
|
||||
this
|
||||
);
|
||||
}
|
||||
|
||||
_updateObjectPosition(runtimeScene) {
|
||||
_updateObjectPosition(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
if (!this._draggedByDraggableManager) {
|
||||
return false;
|
||||
}
|
||||
this._draggedByDraggableManager.updateObjectPosition(runtimeScene, this);
|
||||
this._draggedByDraggableManager.updateObjectPosition(
|
||||
instanceContainer,
|
||||
this
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene) {
|
||||
this._tryBeginDrag(runtimeScene);
|
||||
if (this._shouldEndDrag(runtimeScene)) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
this._tryBeginDrag(instanceContainer);
|
||||
if (this._shouldEndDrag(instanceContainer)) {
|
||||
this._endDrag();
|
||||
}
|
||||
this._updateObjectPosition(runtimeScene);
|
||||
this._updateObjectPosition(instanceContainer);
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene) {
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
const mouseDraggableManager = DraggableManager.getMouseManager(
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
mouseDraggableManager.leftPressedLastFrame = runtimeScene
|
||||
mouseDraggableManager.leftPressedLastFrame = instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonPressed(0);
|
||||
|
||||
this._justDropped = false;
|
||||
}
|
||||
|
||||
isDragged(runtimeScene): boolean {
|
||||
isDragged(): boolean {
|
||||
return !!this._draggedByDraggableManager;
|
||||
}
|
||||
|
||||
wasJustDropped(): boolean {
|
||||
return this._justDropped;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -137,53 +157,53 @@ namespace gdjs {
|
||||
protected _xOffset: number = 0;
|
||||
protected _yOffset: number = 0;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene) {}
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
/**
|
||||
* Get the platforms manager of a scene.
|
||||
* Get the platforms manager of an instance container.
|
||||
*/
|
||||
static getMouseManager(
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): MouseDraggableManager {
|
||||
// @ts-ignore
|
||||
if (!runtimeScene.mouseDraggableManager) {
|
||||
if (!instanceContainer.mouseDraggableManager) {
|
||||
//Create the shared manager if necessary.
|
||||
// @ts-ignore
|
||||
runtimeScene.mouseDraggableManager = new MouseDraggableManager(
|
||||
runtimeScene
|
||||
instanceContainer.mouseDraggableManager = new MouseDraggableManager(
|
||||
instanceContainer
|
||||
);
|
||||
}
|
||||
// @ts-ignore
|
||||
return runtimeScene.mouseDraggableManager;
|
||||
return instanceContainer.mouseDraggableManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the platforms manager of a scene.
|
||||
* Get the platforms manager of an instance container.
|
||||
*/
|
||||
static getTouchManager(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
touchId: integer
|
||||
): DraggableManager {
|
||||
// @ts-ignore
|
||||
if (!runtimeScene.touchDraggableManagers) {
|
||||
if (!instanceContainer.touchDraggableManagers) {
|
||||
//Create the shared manager if necessary.
|
||||
// @ts-ignore
|
||||
runtimeScene.touchDraggableManagers = [];
|
||||
instanceContainer.touchDraggableManagers = [];
|
||||
}
|
||||
// @ts-ignore
|
||||
if (!runtimeScene.touchDraggableManagers[touchId]) {
|
||||
if (!instanceContainer.touchDraggableManagers[touchId]) {
|
||||
//Create the shared manager if necessary.
|
||||
// @ts-ignore
|
||||
runtimeScene.touchDraggableManagers[
|
||||
instanceContainer.touchDraggableManagers[
|
||||
touchId
|
||||
] = new TouchDraggableManager(runtimeScene, touchId);
|
||||
] = new TouchDraggableManager(instanceContainer, touchId);
|
||||
}
|
||||
// @ts-ignore
|
||||
return runtimeScene.touchDraggableManagers[touchId];
|
||||
return instanceContainer.touchDraggableManagers[touchId];
|
||||
}
|
||||
|
||||
tryAndTakeDragging(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
) {
|
||||
if (
|
||||
@@ -193,7 +213,10 @@ namespace gdjs {
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const position = this.getPosition(runtimeScene, draggableRuntimeBehavior);
|
||||
const position = this.getPosition(
|
||||
instanceContainer,
|
||||
draggableRuntimeBehavior
|
||||
);
|
||||
if (
|
||||
!draggableRuntimeBehavior.owner.insideObject(position[0], position[1])
|
||||
) {
|
||||
@@ -218,10 +241,13 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
updateObjectPosition(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
) {
|
||||
const position = this.getPosition(runtimeScene, draggableRuntimeBehavior);
|
||||
const position = this.getPosition(
|
||||
instanceContainer,
|
||||
draggableRuntimeBehavior
|
||||
);
|
||||
if (
|
||||
draggableRuntimeBehavior.owner.getX() != position[0] - this._xOffset ||
|
||||
draggableRuntimeBehavior.owner.getY() != position[1] - this._yOffset
|
||||
@@ -241,11 +267,11 @@ namespace gdjs {
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): boolean;
|
||||
abstract shouldEndDrag(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): boolean;
|
||||
abstract getPosition(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): FloatPoint;
|
||||
}
|
||||
@@ -257,8 +283,8 @@ namespace gdjs {
|
||||
/** Used to only start dragging when clicking. */
|
||||
leftPressedLastFrame = false;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene) {
|
||||
super(runtimeScene);
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
super(instanceContainer);
|
||||
}
|
||||
|
||||
isDragging(draggableRuntimeBehavior: DraggableRuntimeBehavior): boolean {
|
||||
@@ -266,20 +292,28 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
getPosition(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): FloatPoint {
|
||||
const inputManager = runtimeScene.getGame().getInputManager();
|
||||
return runtimeScene
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
MouseDraggableManager.prototype.getPosition
|
||||
) as FloatPoint;
|
||||
const inputManager = instanceContainer.getGame().getInputManager();
|
||||
return instanceContainer
|
||||
.getLayer(draggableRuntimeBehavior.owner.getLayer())
|
||||
.convertCoords(inputManager.getMouseX(), inputManager.getMouseY());
|
||||
.convertCoords(
|
||||
inputManager.getMouseX(),
|
||||
inputManager.getMouseY(),
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
}
|
||||
|
||||
shouldEndDrag(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): boolean {
|
||||
const inputManager = runtimeScene.getGame().getInputManager();
|
||||
const inputManager = instanceContainer.getGame().getInputManager();
|
||||
return !inputManager.isMouseButtonPressed(0);
|
||||
}
|
||||
}
|
||||
@@ -290,8 +324,11 @@ namespace gdjs {
|
||||
class TouchDraggableManager extends DraggableManager {
|
||||
private _touchId: integer;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene, touchId: integer) {
|
||||
super(runtimeScene);
|
||||
constructor(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
touchId: integer
|
||||
) {
|
||||
super(instanceContainer);
|
||||
this._touchId = touchId;
|
||||
}
|
||||
|
||||
@@ -300,23 +337,28 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
getPosition(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): FloatPoint {
|
||||
const inputManager = runtimeScene.getGame().getInputManager();
|
||||
return runtimeScene
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
TouchDraggableManager.prototype.getPosition
|
||||
) as FloatPoint;
|
||||
const inputManager = instanceContainer.getGame().getInputManager();
|
||||
return instanceContainer
|
||||
.getLayer(draggableRuntimeBehavior.owner.getLayer())
|
||||
.convertCoords(
|
||||
inputManager.getTouchX(this._touchId),
|
||||
inputManager.getTouchY(this._touchId)
|
||||
inputManager.getTouchY(this._touchId),
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
}
|
||||
|
||||
shouldEndDrag(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
draggableRuntimeBehavior: DraggableRuntimeBehavior
|
||||
): boolean {
|
||||
const inputManager = runtimeScene.getGame().getInputManager();
|
||||
const inputManager = instanceContainer.getGame().getInputManager();
|
||||
return (
|
||||
inputManager.getAllTouchIdentifiers().indexOf(this._touchId) === -1
|
||||
);
|
||||
|
@@ -11,11 +11,11 @@ namespace gdjs {
|
||||
_textToSet: string;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData: any,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
|
||||
// Here you can access to the behavior data (JSON declared in JsExtension.js)
|
||||
// using behaviorData:
|
||||
@@ -37,7 +37,7 @@ namespace gdjs {
|
||||
|
||||
onDeActivate() {}
|
||||
|
||||
doStepPreEvents(runtimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// This is run at every frame, before events are launched.
|
||||
this.owner
|
||||
.getVariables()
|
||||
@@ -45,7 +45,7 @@ namespace gdjs {
|
||||
.setString(this._textToSet);
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene) {
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// This is run at every frame, after events are launched.
|
||||
}
|
||||
}
|
||||
|
@@ -11,11 +11,11 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* @param runtimeObject The object to render
|
||||
* @param runtimeScene The gdjs.RuntimeScene in which the object is
|
||||
* @param instanceContainer The gdjs.RuntimeScene in which the object is
|
||||
*/
|
||||
constructor(
|
||||
runtimeObject: gdjs.DummyRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
|
||||
@@ -27,12 +27,12 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
// You can also create a PIXI sprite or other PIXI object
|
||||
// this._imageManager = runtimeScene.getGame().getImageManager();
|
||||
// this._imageManager = instanceContainer.getGame().getImageManager();
|
||||
// if ( this._sprite === undefined )
|
||||
// this._sprite = new PIXI.Sprite(this._imageManager.getInvalidPIXITexture());
|
||||
this._text.anchor.x = 0.5;
|
||||
this._text.anchor.y = 0.5;
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._text, runtimeObject.getZOrder());
|
||||
|
@@ -14,11 +14,14 @@ namespace gdjs {
|
||||
// @ts-expect-error ts-migrate(2564) FIXME: Property 'opacity' has no initializer and is not d... Remove this comment to see the full error message
|
||||
opacity: float;
|
||||
|
||||
constructor(runtimeScene, objectData) {
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer, objectData) {
|
||||
// *ALWAYS* call the base gdjs.RuntimeObject constructor.
|
||||
super(runtimeScene, objectData);
|
||||
super(instanceContainer, objectData);
|
||||
this._property1 = objectData.content.property1;
|
||||
this._renderer = new gdjs.DummyRuntimeObjectRenderer(this, runtimeScene);
|
||||
this._renderer = new gdjs.DummyRuntimeObjectRenderer(
|
||||
this,
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
@@ -40,9 +43,9 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Called once during the game loop, before events and rendering.
|
||||
* @param runtimeScene The gdjs.RuntimeScene the object belongs to.
|
||||
* @param instanceContainer The gdjs.RuntimeScene the object belongs to.
|
||||
*/
|
||||
update(runtimeScene: gdjs.RuntimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
// This is an example: typically you want to make sure the renderer
|
||||
// is up to date with the object.
|
||||
this._renderer.ensureUpToDate();
|
||||
|
@@ -4,20 +4,20 @@ namespace gdjs {
|
||||
_textToSet: string;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData: any,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
|
||||
// Here you can access to the behavior data (JSON declared in JsExtension.js)
|
||||
// using behaviorData:
|
||||
this._textToSet = behaviorData.property1;
|
||||
|
||||
// You can also access to the shared data:
|
||||
const sharedData = runtimeScene.getInitialSharedDataForBehavior(
|
||||
behaviorData.name
|
||||
);
|
||||
const sharedData = instanceContainer
|
||||
.getScene()
|
||||
.getInitialSharedDataForBehavior(behaviorData.name);
|
||||
this._textToSet = (sharedData as any).sharedProperty1;
|
||||
|
||||
// You can also run arbitrary code at the creation of the behavior:
|
||||
@@ -40,7 +40,7 @@ namespace gdjs {
|
||||
|
||||
onDeActivate() {}
|
||||
|
||||
doStepPreEvents(runtimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// This is run at every frame, before events are launched.
|
||||
this.owner
|
||||
.getVariables()
|
||||
@@ -48,7 +48,7 @@ namespace gdjs {
|
||||
.setString(this._textToSet);
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene) {
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// This is run at every frame, after events are launched.
|
||||
}
|
||||
}
|
||||
|
@@ -25,7 +25,9 @@ namespace gdjs {
|
||||
* In **rare cases** you may want to run code at the start of the scene. You can define a callback
|
||||
* that will be called at this moment.
|
||||
*/
|
||||
gdjs.registerRuntimeSceneLoadedCallback(function (runtimeScene) {
|
||||
gdjs.registerRuntimeSceneLoadedCallback(function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
) {
|
||||
logger.log('A gdjs.RuntimeScene was loaded:', runtimeScene);
|
||||
});
|
||||
|
||||
@@ -33,7 +35,9 @@ namespace gdjs {
|
||||
* In **rare cases** you may want to run code at the end of a scene. You can define a callback
|
||||
* that will be called at this moment.
|
||||
*/
|
||||
gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) {
|
||||
gdjs.registerRuntimeSceneUnloadedCallback(function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
) {
|
||||
logger.log('A gdjs.RuntimeScene was unloaded:', runtimeScene);
|
||||
});
|
||||
|
||||
@@ -41,12 +45,12 @@ namespace gdjs {
|
||||
* In **very rare cases** you may want to run code whenever an object is deleted.
|
||||
*/
|
||||
gdjs.registerObjectDeletedFromSceneCallback(function (
|
||||
runtimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
runtimeObject
|
||||
) {
|
||||
logger.log(
|
||||
'A gdjs.RuntimeObject was deleted from a gdjs.RuntimeScene:',
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
runtimeObject
|
||||
);
|
||||
});
|
||||
|
@@ -203,6 +203,18 @@ module.exports = {
|
||||
'',
|
||||
true
|
||||
)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Normalize the file content (recommended)'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'This replaces Windows new lines characters ("CRLF") by a single new line character.'
|
||||
)
|
||||
)
|
||||
.setDefaultValue('yes')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/FileSystem/filesystemtools.js')
|
||||
.setFunctionName('gdjs.fileSystem.loadStringFromFileAsync');
|
||||
@@ -229,6 +241,18 @@ module.exports = {
|
||||
'',
|
||||
true
|
||||
)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Normalize the file content (recommended)'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'This replaces Windows new lines characters ("CRLF") by a single new line character.'
|
||||
)
|
||||
)
|
||||
.setDefaultValue('yes')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/FileSystem/filesystemtools.js')
|
||||
.setFunctionName('gdjs.fileSystem.loadStringFromFile');
|
||||
@@ -255,6 +279,18 @@ module.exports = {
|
||||
'',
|
||||
true
|
||||
)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Normalize the file content (recommended)'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'This replaces Windows new lines characters ("CRLF") by a single new line character.'
|
||||
)
|
||||
)
|
||||
.setDefaultValue('yes')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/FileSystem/filesystemtools.js')
|
||||
.setFunctionName('gdjs.fileSystem.loadVariableFromJSONFile');
|
||||
@@ -281,6 +317,18 @@ module.exports = {
|
||||
'',
|
||||
true
|
||||
)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Normalize the file content (recommended)'),
|
||||
'',
|
||||
true
|
||||
)
|
||||
.setParameterLongDescription(
|
||||
_(
|
||||
'This replaces Windows new lines characters ("CRLF") by a single new line character.'
|
||||
)
|
||||
)
|
||||
.setDefaultValue('yes')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/FileSystem/filesystemtools.js')
|
||||
.setFunctionName('gdjs.fileSystem.loadVariableFromJSONFileAsync');
|
||||
|
@@ -48,13 +48,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to 'Desktop' folder.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to the desktop folder
|
||||
*/
|
||||
export const getDesktopPath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('desktop') || '';
|
||||
@@ -65,13 +68,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to 'Documents' folder.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to the documents folder
|
||||
*/
|
||||
export const getDocumentsPath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('documents') || '';
|
||||
@@ -82,13 +88,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to 'Pictures' folder.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to the pictures folder
|
||||
*/
|
||||
export const getPicturesPath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('pictures') || '';
|
||||
@@ -99,13 +108,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to this application 'Executable' file.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to this applications executable file
|
||||
*/
|
||||
export const getExecutablePath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('exe') || '';
|
||||
@@ -116,14 +128,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to this application 'Executable' folder.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to this applications executable folder
|
||||
*/
|
||||
export const getExecutableFolderPath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const path = gdjs.fileSystem._getPath();
|
||||
const executablePath = gdjs.fileSystem.getExecutablePath(runtimeScene);
|
||||
const executablePath = gdjs.fileSystem.getExecutablePath(
|
||||
instanceContainer
|
||||
);
|
||||
if (!path) {
|
||||
return '';
|
||||
}
|
||||
@@ -132,13 +146,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to 'UserData' folder.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to userdata folder
|
||||
*/
|
||||
export const getUserdataPath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('userData') || '';
|
||||
@@ -152,9 +169,12 @@ namespace gdjs {
|
||||
* @return The path to user's "home" folder
|
||||
*/
|
||||
export const getUserHomePath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('home') || '';
|
||||
@@ -165,13 +185,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Get the path to 'Temp' folder.
|
||||
* @param runtimeScene The current scene
|
||||
* @param instanceContainer The current container
|
||||
* @return The path to temp folder
|
||||
*/
|
||||
export const getTempPath = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): string {
|
||||
const remote = runtimeScene.getGame().getRenderer().getElectronRemote();
|
||||
const remote = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getElectronRemote();
|
||||
const app = remote ? remote.app : null;
|
||||
if (app) {
|
||||
return app.getPath('temp') || '';
|
||||
@@ -338,11 +361,13 @@ namespace gdjs {
|
||||
* @param stringVar Variable where to store the content
|
||||
* @param loadPath Path to the file
|
||||
* @param resultVar The variable where to store the result of the operation
|
||||
* @param removeCRCharacters If true, will remove \r characters usually added by Windows when editing files
|
||||
*/
|
||||
export const loadStringFromFile = function (
|
||||
stringVar: gdjs.Variable,
|
||||
loadPath: string,
|
||||
resultVar: gdjs.Variable
|
||||
resultVar: gdjs.Variable,
|
||||
removeCRCharacters: boolean
|
||||
) {
|
||||
const fileSystem = gdjs.fileSystem._getFs();
|
||||
let result = 'error';
|
||||
@@ -350,7 +375,9 @@ namespace gdjs {
|
||||
try {
|
||||
const data = fileSystem.readFileSync(loadPath, 'utf8');
|
||||
if (data) {
|
||||
stringVar.setString(data);
|
||||
stringVar.setString(
|
||||
removeCRCharacters ? data.replace(/\r/g, '') : data
|
||||
);
|
||||
result = 'ok';
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -368,11 +395,13 @@ namespace gdjs {
|
||||
* @param variable Variable to store the variable
|
||||
* @param loadPath Path to the file
|
||||
* @param resultVar The variable where to store the result of the operation
|
||||
* @param removeCRCharacters If true, will remove \r characters usually added by Windows when editing files
|
||||
*/
|
||||
export const loadVariableFromJSONFile = function (
|
||||
variable: gdjs.Variable,
|
||||
loadPath: string,
|
||||
resultVar: gdjs.Variable
|
||||
resultVar: gdjs.Variable,
|
||||
removeCRCharacters: boolean
|
||||
) {
|
||||
const fileSystem = gdjs.fileSystem._getFs();
|
||||
let result = 'error';
|
||||
@@ -380,7 +409,9 @@ namespace gdjs {
|
||||
try {
|
||||
const data = fileSystem.readFileSync(loadPath, 'utf8');
|
||||
if (data) {
|
||||
variable.fromJSON(data);
|
||||
variable.fromJSON(
|
||||
removeCRCharacters ? data.replace(/\r/g, '') : data
|
||||
);
|
||||
result = 'ok';
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -400,17 +431,21 @@ namespace gdjs {
|
||||
* @param variable Variable to store the variable
|
||||
* @param loadPath Path to the file
|
||||
* @param resultVar The variable where to store the result of the operation
|
||||
* @param removeCRCharacters If true, will remove \r characters usually added by Windows when editing files
|
||||
*/
|
||||
export const loadVariableFromJSONFileAsync = function (
|
||||
variable: gdjs.Variable,
|
||||
loadPath: string,
|
||||
resultVar: gdjs.Variable
|
||||
resultVar: gdjs.Variable,
|
||||
removeCRCharacters: boolean
|
||||
) {
|
||||
const fileSystem = gdjs.fileSystem._getFs();
|
||||
if (fileSystem) {
|
||||
fileSystem.readFile(loadPath, 'utf8', (err, data) => {
|
||||
if (data) {
|
||||
variable.fromJSON(data);
|
||||
variable.fromJSON(
|
||||
removeCRCharacters ? data.replace(/\r/g, '') : data
|
||||
);
|
||||
resultVar.setString('ok');
|
||||
}
|
||||
if (err) {
|
||||
@@ -431,17 +466,21 @@ namespace gdjs {
|
||||
* @param stringVar Variable where to store the content
|
||||
* @param loadPath Path to the file
|
||||
* @param resultVar The variable where to store the result of the operation
|
||||
* @param removeCRCharacters If true, will remove \r characters usually added by Windows when editing files
|
||||
*/
|
||||
export const loadStringFromFileAsync = function (
|
||||
stringVar: gdjs.Variable,
|
||||
loadPath: string,
|
||||
resultVar: gdjs.Variable
|
||||
resultVar: gdjs.Variable,
|
||||
removeCRCharacters: boolean
|
||||
) {
|
||||
const fileSystem = gdjs.fileSystem._getFs();
|
||||
if (fileSystem) {
|
||||
fileSystem.readFile(loadPath, 'utf8', (err, data) => {
|
||||
if (data) {
|
||||
stringVar.setString(data);
|
||||
stringVar.setString(
|
||||
removeCRCharacters ? data.replace(/\r/g, '') : data
|
||||
);
|
||||
resultVar.setString('ok');
|
||||
}
|
||||
if (err) {
|
||||
|
@@ -1,7 +1,13 @@
|
||||
namespace gdjs {
|
||||
export interface RuntimeGame {
|
||||
inventories: { [name: string]: gdjs.Inventory };
|
||||
}
|
||||
export class InventoryManager {
|
||||
static get(runtimeScene, name): gdjs.Inventory {
|
||||
const game = runtimeScene.getGame();
|
||||
static get(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
name: string
|
||||
): gdjs.Inventory {
|
||||
const game = instanceContainer.getGame();
|
||||
if (!game.inventories) {
|
||||
game.inventories = {};
|
||||
}
|
||||
@@ -15,70 +21,106 @@ namespace gdjs {
|
||||
|
||||
export namespace evtTools {
|
||||
export namespace inventory {
|
||||
export const add = function (runtimeScene, inventoryName, name) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).add(name);
|
||||
export const add = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string
|
||||
) {
|
||||
return InventoryManager.get(instanceContainer, inventoryName).add(name);
|
||||
};
|
||||
|
||||
export const remove = function (runtimeScene, inventoryName, name) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).remove(name);
|
||||
export const remove = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string
|
||||
) {
|
||||
return InventoryManager.get(instanceContainer, inventoryName).remove(
|
||||
name
|
||||
);
|
||||
};
|
||||
|
||||
export const count = function (runtimeScene, inventoryName, name) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).count(name);
|
||||
export const count = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string
|
||||
) {
|
||||
return InventoryManager.get(instanceContainer, inventoryName).count(
|
||||
name
|
||||
);
|
||||
};
|
||||
|
||||
export const has = function (runtimeScene, inventoryName, name) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).has(name);
|
||||
export const has = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string
|
||||
) {
|
||||
return InventoryManager.get(instanceContainer, inventoryName).has(name);
|
||||
};
|
||||
|
||||
export const setMaximum = function (
|
||||
runtimeScene,
|
||||
inventoryName,
|
||||
name,
|
||||
maxCount
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string,
|
||||
maxCount: number
|
||||
) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).setMaximum(
|
||||
name,
|
||||
maxCount
|
||||
);
|
||||
return InventoryManager.get(
|
||||
instanceContainer,
|
||||
inventoryName
|
||||
).setMaximum(name, maxCount);
|
||||
};
|
||||
|
||||
export const setUnlimited = function (
|
||||
runtimeScene,
|
||||
inventoryName,
|
||||
name,
|
||||
enable
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string,
|
||||
enable: boolean
|
||||
) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).setUnlimited(
|
||||
name,
|
||||
enable
|
||||
return InventoryManager.get(
|
||||
instanceContainer,
|
||||
inventoryName
|
||||
).setUnlimited(name, enable);
|
||||
};
|
||||
|
||||
export const isFull = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string
|
||||
) {
|
||||
return InventoryManager.get(instanceContainer, inventoryName).isFull(
|
||||
name
|
||||
);
|
||||
};
|
||||
|
||||
export const isFull = function (runtimeScene, inventoryName, name) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).isFull(name);
|
||||
};
|
||||
|
||||
export const equip = function (runtimeScene, inventoryName, name, equip) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).equip(
|
||||
export const equip = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string,
|
||||
equip: boolean
|
||||
) {
|
||||
return InventoryManager.get(instanceContainer, inventoryName).equip(
|
||||
name,
|
||||
equip
|
||||
);
|
||||
};
|
||||
|
||||
export const isEquipped = function (runtimeScene, inventoryName, name) {
|
||||
return InventoryManager.get(runtimeScene, inventoryName).isEquipped(
|
||||
name
|
||||
);
|
||||
export const isEquipped = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
name: string
|
||||
) {
|
||||
return InventoryManager.get(
|
||||
instanceContainer,
|
||||
inventoryName
|
||||
).isEquipped(name);
|
||||
};
|
||||
|
||||
export const serializeToVariable = function (
|
||||
runtimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
variable: gdjs.Variable
|
||||
) {
|
||||
const allItems = gdjs.InventoryManager.get(
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
inventoryName
|
||||
).getAllItems();
|
||||
for (const name in allItems) {
|
||||
@@ -92,12 +134,12 @@ namespace gdjs {
|
||||
};
|
||||
|
||||
export const unserializeFromVariable = function (
|
||||
runtimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
inventoryName: string,
|
||||
variable: gdjs.Variable
|
||||
) {
|
||||
const inventory = gdjs.InventoryManager.get(
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
inventoryName
|
||||
);
|
||||
inventory.clear();
|
||||
|
@@ -1,5 +1,6 @@
|
||||
/// <reference path="sha256.d.ts" />
|
||||
|
||||
// TODO EBO Replace runtimeScene to instanceContainer.
|
||||
namespace gdjs {
|
||||
const logger = new gdjs.Logger('Leaderboards');
|
||||
export namespace evtTools {
|
||||
@@ -75,8 +76,8 @@ namespace gdjs {
|
||||
|
||||
isTooSoonToSaveAnotherScore(): boolean {
|
||||
return (
|
||||
!!this.lastScoreSavingSucceededAt &&
|
||||
Date.now() - this.lastScoreSavingSucceededAt < 500
|
||||
!!this.lastScoreSavingStartedAt &&
|
||||
Date.now() - this.lastScoreSavingStartedAt < 500
|
||||
);
|
||||
}
|
||||
|
||||
@@ -190,16 +191,14 @@ namespace gdjs {
|
||||
const saveScore = function ({
|
||||
leaderboardId,
|
||||
playerName,
|
||||
playerId,
|
||||
playerToken,
|
||||
authenticatedPlayerData,
|
||||
score,
|
||||
scoreSavingState,
|
||||
runtimeScene,
|
||||
}: {
|
||||
leaderboardId: string;
|
||||
playerName?: string;
|
||||
playerId?: string;
|
||||
playerToken?: string;
|
||||
playerName?: string | null;
|
||||
authenticatedPlayerData?: { playerId: string; playerToken: string };
|
||||
score: number;
|
||||
scoreSavingState: ScoreSavingState;
|
||||
runtimeScene: gdjs.RuntimeScene;
|
||||
@@ -220,19 +219,22 @@ namespace gdjs {
|
||||
? (window as any).location.href
|
||||
: '',
|
||||
};
|
||||
if (playerName)
|
||||
payloadObject['playerName'] = formatPlayerName(playerName);
|
||||
const payload = JSON.stringify(payloadObject);
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
Digest: computeDigest(payload),
|
||||
};
|
||||
if (playerToken)
|
||||
headers['Authorization'] = `player-game-token ${playerToken}`;
|
||||
let leaderboardEntryCreationUrl = `${baseUrl}/game/${gdjs.projectData.properties.projectUuid}/leaderboard/${leaderboardId}/entry`;
|
||||
if (playerId) {
|
||||
leaderboardEntryCreationUrl += `?playerId=${playerId}`;
|
||||
if (authenticatedPlayerData) {
|
||||
headers[
|
||||
'Authorization'
|
||||
] = `player-game-token ${authenticatedPlayerData.playerToken}`;
|
||||
leaderboardEntryCreationUrl += `?playerId=${authenticatedPlayerData.playerId}`;
|
||||
} else {
|
||||
// In case playerName is empty or undefined, the formatting will generate a random name.
|
||||
payloadObject['playerName'] = formatPlayerName(playerName);
|
||||
}
|
||||
const payload = JSON.stringify(payloadObject);
|
||||
headers['Digest'] = computeDigest(payload);
|
||||
|
||||
fetch(leaderboardEntryCreationUrl, {
|
||||
body: payload,
|
||||
method: 'POST',
|
||||
@@ -279,30 +281,42 @@ namespace gdjs {
|
||||
let scoreSavingState: ScoreSavingState;
|
||||
if (_scoreSavingStateByLeaderboard[leaderboardId]) {
|
||||
scoreSavingState = _scoreSavingStateByLeaderboard[leaderboardId];
|
||||
let shouldStartSaving = true;
|
||||
if (
|
||||
shouldStartSaving &&
|
||||
scoreSavingState.isAlreadySavingThisScore({ playerName, score })
|
||||
) {
|
||||
logger.warn(
|
||||
'There is already a request to save with this player name and this score. Ignoring this one.'
|
||||
);
|
||||
return;
|
||||
shouldStartSaving = false;
|
||||
}
|
||||
|
||||
if (scoreSavingState.isSameAsLastScore({ playerName, score })) {
|
||||
if (
|
||||
shouldStartSaving &&
|
||||
scoreSavingState.isSameAsLastScore({ playerName, score })
|
||||
) {
|
||||
logger.warn(
|
||||
'The player and score to be sent are the same as previous one. Ignoring this one.'
|
||||
);
|
||||
const errorCode = 'SAME_AS_PREVIOUS';
|
||||
scoreSavingState.setError(errorCode);
|
||||
return;
|
||||
scoreSavingState.setError('SAME_AS_PREVIOUS');
|
||||
shouldStartSaving = false;
|
||||
}
|
||||
|
||||
if (scoreSavingState.isTooSoonToSaveAnotherScore()) {
|
||||
if (
|
||||
shouldStartSaving &&
|
||||
scoreSavingState.isTooSoonToSaveAnotherScore()
|
||||
) {
|
||||
logger.warn(
|
||||
'Last entry was sent too little time ago. Ignoring this one.'
|
||||
);
|
||||
const errorCode = 'TOO_FAST';
|
||||
scoreSavingState.setError(errorCode);
|
||||
scoreSavingState.setError('TOO_FAST');
|
||||
shouldStartSaving = false;
|
||||
// Set the starting time to cancel all the following attempts that
|
||||
// are started too early after this one.
|
||||
scoreSavingState.lastScoreSavingStartedAt = Date.now();
|
||||
}
|
||||
if (!shouldStartSaving) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
@@ -337,28 +351,42 @@ namespace gdjs {
|
||||
}
|
||||
if (_scoreSavingStateByLeaderboard[leaderboardId]) {
|
||||
scoreSavingState = _scoreSavingStateByLeaderboard[leaderboardId];
|
||||
if (scoreSavingState.isAlreadySavingThisScore({ playerId, score })) {
|
||||
let shouldStartSaving = true;
|
||||
if (
|
||||
shouldStartSaving &&
|
||||
scoreSavingState.isAlreadySavingThisScore({ playerId, score })
|
||||
) {
|
||||
logger.warn(
|
||||
'There is already a request to save with this player ID and this score. Ignoring this one.'
|
||||
);
|
||||
return;
|
||||
shouldStartSaving = false;
|
||||
}
|
||||
|
||||
if (scoreSavingState.isSameAsLastScore({ playerId, score })) {
|
||||
if (
|
||||
shouldStartSaving &&
|
||||
scoreSavingState.isSameAsLastScore({ playerId, score })
|
||||
) {
|
||||
logger.warn(
|
||||
'The player and score to be sent are the same as previous one. Ignoring this one.'
|
||||
);
|
||||
const errorCode = 'SAME_AS_PREVIOUS';
|
||||
scoreSavingState.setError(errorCode);
|
||||
return;
|
||||
scoreSavingState.setError('SAME_AS_PREVIOUS');
|
||||
shouldStartSaving = false;
|
||||
}
|
||||
|
||||
if (scoreSavingState.isTooSoonToSaveAnotherScore()) {
|
||||
if (
|
||||
shouldStartSaving &&
|
||||
scoreSavingState.isTooSoonToSaveAnotherScore()
|
||||
) {
|
||||
logger.warn(
|
||||
'Last entry was sent too little time ago. Ignoring this one.'
|
||||
);
|
||||
const errorCode = 'TOO_FAST';
|
||||
scoreSavingState.setError(errorCode);
|
||||
scoreSavingState.setError('TOO_FAST');
|
||||
shouldStartSaving = false;
|
||||
// Set the starting time to cancel all the following attempts that
|
||||
// are started too early after this one.
|
||||
scoreSavingState.lastScoreSavingStartedAt = Date.now();
|
||||
}
|
||||
if (!shouldStartSaving) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
@@ -370,8 +398,7 @@ namespace gdjs {
|
||||
|
||||
saveScore({
|
||||
leaderboardId,
|
||||
playerId,
|
||||
playerToken,
|
||||
authenticatedPlayerData: { playerId, playerToken },
|
||||
score,
|
||||
scoreSavingState,
|
||||
runtimeScene,
|
||||
@@ -443,7 +470,9 @@ namespace gdjs {
|
||||
: 'NO_DATA_ERROR';
|
||||
};
|
||||
|
||||
export const formatPlayerName = function (rawName: string): string {
|
||||
export const formatPlayerName = function (
|
||||
rawName?: string | null
|
||||
): string {
|
||||
if (
|
||||
!rawName ||
|
||||
typeof rawName !== 'string' ||
|
||||
|
@@ -4,26 +4,26 @@ namespace gdjs {
|
||||
export class LightObstaclesManager {
|
||||
_obstacleRBush: any;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene) {
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
this._obstacleRBush = new rbush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the light obstacles manager of a scene.
|
||||
* Get the light obstacles manager of an instance container.
|
||||
*/
|
||||
static getManager(
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): gdjs.LightObstaclesManager {
|
||||
// @ts-ignore
|
||||
if (!runtimeScene._lightObstaclesManager) {
|
||||
if (!instanceContainer._lightObstaclesManager) {
|
||||
// Create the shared manager if necessary.
|
||||
// @ts-ignore
|
||||
runtimeScene._lightObstaclesManager = new gdjs.LightObstaclesManager(
|
||||
runtimeScene
|
||||
instanceContainer._lightObstaclesManager = new gdjs.LightObstaclesManager(
|
||||
instanceContainer
|
||||
);
|
||||
}
|
||||
// @ts-ignore
|
||||
return runtimeScene._lightObstaclesManager;
|
||||
return instanceContainer._lightObstaclesManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,15 +92,15 @@ namespace gdjs {
|
||||
_registeredInManager: boolean = false;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
this._manager = LightObstaclesManager.getManager(runtimeScene);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._manager = LightObstaclesManager.getManager(instanceContainer);
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// Make sure the obstacle is or is not in the obstacles manager.
|
||||
if (!this.activated() && this._registeredInManager) {
|
||||
this._manager.removeObstacle(this);
|
||||
|
@@ -7,7 +7,7 @@ namespace gdjs {
|
||||
*/
|
||||
export class LightRuntimeObjectPixiRenderer {
|
||||
_object: gdjs.LightRuntimeObject;
|
||||
_runtimeScene: gdjs.RuntimeScene;
|
||||
_instanceContainer: gdjs.RuntimeInstanceContainer;
|
||||
_manager: gdjs.LightObstaclesManager;
|
||||
_radius: number;
|
||||
_color: [number, number, number];
|
||||
@@ -30,10 +30,10 @@ namespace gdjs {
|
||||
|
||||
constructor(
|
||||
runtimeObject: gdjs.LightRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
this._runtimeScene = runtimeScene;
|
||||
this._instanceContainer = instanceContainer;
|
||||
this._manager = runtimeObject.getObstaclesManager();
|
||||
this._radius = runtimeObject.getRadius();
|
||||
const objectColor = runtimeObject._color;
|
||||
@@ -57,14 +57,14 @@ namespace gdjs {
|
||||
]);
|
||||
this._indexBuffer = new Uint16Array([0, 1, 2, 0, 2, 3]);
|
||||
this.updateMesh();
|
||||
this._isPreview = runtimeScene.getGame().isPreview();
|
||||
this._isPreview = instanceContainer.getGame().isPreview();
|
||||
this._lightBoundingPoly = gdjs.Polygon.createRectangle(0, 0);
|
||||
|
||||
this.updateDebugMode();
|
||||
|
||||
// Objects will be added in lighting layer, this is just to maintain consistency.
|
||||
if (this._light) {
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(
|
||||
@@ -198,7 +198,7 @@ namespace gdjs {
|
||||
const texture = this._object.getTexture();
|
||||
this._texture =
|
||||
texture !== ''
|
||||
? (this._runtimeScene
|
||||
? (this._instanceContainer
|
||||
.getGame()
|
||||
.getImageManager() as gdjs.PixiImageManager).getPIXITexture(
|
||||
texture
|
||||
|
@@ -27,7 +27,7 @@ namespace gdjs {
|
||||
_texture: string;
|
||||
_obstaclesManager: gdjs.LightObstaclesManager;
|
||||
_renderer: gdjs.LightRuntimeObjectRenderer;
|
||||
_runtimeScene: gdjs.RuntimeScene;
|
||||
_instanceContainer: gdjs.RuntimeScene;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
@@ -43,7 +43,7 @@ namespace gdjs {
|
||||
runtimeScene
|
||||
);
|
||||
this._renderer = new gdjs.LightRuntimeObjectRenderer(this, runtimeScene);
|
||||
this._runtimeScene = runtimeScene;
|
||||
this._instanceContainer = runtimeScene;
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
|
@@ -12,15 +12,17 @@ namespace gdjs {
|
||||
/**
|
||||
* Get the links manager of a scene.
|
||||
*/
|
||||
static getManager(runtimeScene: gdjs.RuntimeScene): gdjs.LinksManager {
|
||||
static getManager(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): gdjs.LinksManager {
|
||||
// @ts-ignore
|
||||
if (!runtimeScene.linkedObjectsManager) {
|
||||
if (!instanceContainer.linkedObjectsManager) {
|
||||
//Create the shared manager if necessary.
|
||||
// @ts-ignore
|
||||
runtimeScene.linkedObjectsManager = new gdjs.LinksManager();
|
||||
instanceContainer.linkedObjectsManager = new gdjs.LinksManager();
|
||||
}
|
||||
// @ts-ignore
|
||||
return runtimeScene.linkedObjectsManager;
|
||||
return instanceContainer.linkedObjectsManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -184,44 +186,50 @@ namespace gdjs {
|
||||
|
||||
export namespace evtTools {
|
||||
export namespace linkedObjects {
|
||||
gdjs.registerObjectDeletedFromSceneCallback(function (runtimeScene, obj) {
|
||||
LinksManager.getManager(runtimeScene).removeAllLinksOf(obj);
|
||||
gdjs.registerObjectDeletedFromSceneCallback(function (
|
||||
instanceContainer,
|
||||
obj
|
||||
) {
|
||||
LinksManager.getManager(instanceContainer).removeAllLinksOf(obj);
|
||||
});
|
||||
|
||||
export const linkObjects = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objA: gdjs.RuntimeObject,
|
||||
objB: gdjs.RuntimeObject
|
||||
) {
|
||||
if (objA === null || objB === null) {
|
||||
return;
|
||||
}
|
||||
LinksManager.getManager(runtimeScene).linkObjects(objA, objB);
|
||||
LinksManager.getManager(instanceContainer).linkObjects(objA, objB);
|
||||
};
|
||||
|
||||
export const removeLinkBetween = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objA: gdjs.RuntimeObject,
|
||||
objB: gdjs.RuntimeObject
|
||||
) {
|
||||
if (objA === null || objB === null) {
|
||||
return;
|
||||
}
|
||||
LinksManager.getManager(runtimeScene).removeLinkBetween(objA, objB);
|
||||
LinksManager.getManager(instanceContainer).removeLinkBetween(
|
||||
objA,
|
||||
objB
|
||||
);
|
||||
};
|
||||
|
||||
export const removeAllLinksOf = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objA: gdjs.RuntimeObject
|
||||
) {
|
||||
if (objA === null) {
|
||||
return;
|
||||
}
|
||||
LinksManager.getManager(runtimeScene).removeAllLinksOf(objA);
|
||||
LinksManager.getManager(instanceContainer).removeAllLinksOf(objA);
|
||||
};
|
||||
|
||||
export const pickObjectsLinkedTo = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objectsLists: Hashtable<gdjs.RuntimeObject[]>,
|
||||
obj: gdjs.RuntimeObject,
|
||||
eventsFunctionContext: EventsFunctionContext | undefined
|
||||
@@ -230,7 +238,7 @@ namespace gdjs {
|
||||
return false;
|
||||
}
|
||||
const linkedObjectMap = LinksManager.getManager(
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
)._getMapOfObjectsLinkedWith(obj);
|
||||
|
||||
let pickedSomething = false;
|
||||
@@ -273,7 +281,7 @@ namespace gdjs {
|
||||
// avoid running an intersection with the picked objects later.
|
||||
let objectCount = 0;
|
||||
for (const objectName of parentEventPickedObjectNames) {
|
||||
objectCount += runtimeScene.getObjects(objectName).length;
|
||||
objectCount += instanceContainer.getObjects(objectName)!.length;
|
||||
}
|
||||
|
||||
if (parentEventPickedObjects.length === objectCount) {
|
||||
|
@@ -20,12 +20,12 @@ namespace gdjs {
|
||||
|
||||
constructor(
|
||||
runtimeObject: gdjs.PanelSpriteRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
textureName: string,
|
||||
tiled: boolean
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
const texture = (runtimeScene
|
||||
const texture = (instanceContainer
|
||||
.getGame()
|
||||
.getImageManager() as gdjs.PixiImageManager).getPIXITexture(
|
||||
textureName
|
||||
@@ -58,14 +58,14 @@ namespace gdjs {
|
||||
];
|
||||
|
||||
//Bottom-Right
|
||||
this.setTexture(textureName, runtimeScene);
|
||||
this.setTexture(textureName, instanceContainer);
|
||||
this._spritesContainer.removeChildren();
|
||||
this._spritesContainer.addChild(this._centerSprite);
|
||||
for (let i = 0; i < this._borderSprites.length; ++i) {
|
||||
this._spritesContainer.addChild(this._borderSprites[i]);
|
||||
}
|
||||
this._wrapperContainer.addChild(this._spritesContainer);
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._wrapperContainer, runtimeObject.getZOrder());
|
||||
@@ -188,12 +188,19 @@ namespace gdjs {
|
||||
this._spritesContainer.cacheAsBitmap = false;
|
||||
}
|
||||
|
||||
setTexture(textureName, runtimeScene): void {
|
||||
setTexture(
|
||||
textureName: string,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): void {
|
||||
const obj = this._object;
|
||||
const texture = runtimeScene
|
||||
// @ts-ignore
|
||||
const texture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXITexture(textureName);
|
||||
.getPIXITexture(textureName) as PIXI.BaseTexture<
|
||||
PIXI.Resource,
|
||||
PIXI.IAutoDetectOptions
|
||||
>;
|
||||
this._textureWidth = texture.width;
|
||||
this._textureHeight = texture.height;
|
||||
|
||||
|
@@ -43,14 +43,14 @@ namespace gdjs {
|
||||
_renderer: gdjs.PanelSpriteRuntimeObjectRenderer;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param panelSpriteObjectData The initial properties of the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
panelSpriteObjectData: PanelSpriteObjectData
|
||||
) {
|
||||
super(runtimeScene, panelSpriteObjectData);
|
||||
super(instanceContainer, panelSpriteObjectData);
|
||||
this._rBorder = panelSpriteObjectData.rightMargin;
|
||||
this._lBorder = panelSpriteObjectData.leftMargin;
|
||||
this._tBorder = panelSpriteObjectData.topMargin;
|
||||
@@ -60,7 +60,7 @@ namespace gdjs {
|
||||
this._height = panelSpriteObjectData.height;
|
||||
this._renderer = new gdjs.PanelSpriteRuntimeObjectRenderer(
|
||||
this,
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
panelSpriteObjectData.texture,
|
||||
panelSpriteObjectData.tiled
|
||||
);
|
||||
@@ -100,7 +100,7 @@ namespace gdjs {
|
||||
updateTexture = true;
|
||||
}
|
||||
if (updateTexture) {
|
||||
this.setTexture(newObjectData.texture, this._runtimeScene);
|
||||
this.setTexture(newObjectData.texture, this.getRuntimeScene());
|
||||
}
|
||||
if (oldObjectData.tiled !== newObjectData.tiled) {
|
||||
return false;
|
||||
@@ -112,8 +112,8 @@ namespace gdjs {
|
||||
return this._renderer.getRendererObject();
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
// @ts-ignore
|
||||
if (this._renderer.onDestroy) {
|
||||
// @ts-ignore
|
||||
@@ -121,7 +121,7 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
update(runtimeScene: gdjs.RuntimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._renderer.ensureUpToDate();
|
||||
}
|
||||
|
||||
@@ -156,10 +156,13 @@ namespace gdjs {
|
||||
/**
|
||||
* Set the texture of the panel sprite.
|
||||
* @param textureName The name of the texture.
|
||||
* @param runtimeScene The scene the object lives in.
|
||||
* @param instanceContainer The container the object lives in.
|
||||
*/
|
||||
setTexture(textureName: string, runtimeScene: gdjs.RuntimeScene): void {
|
||||
this._renderer.setTexture(textureName, runtimeScene);
|
||||
setTexture(
|
||||
textureName: string,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): void {
|
||||
this._renderer.setTexture(textureName, instanceContainer);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -196,7 +199,7 @@ namespace gdjs {
|
||||
|
||||
this._width = width;
|
||||
this._renderer.updateWidth();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -208,7 +211,7 @@ namespace gdjs {
|
||||
|
||||
this._height = height;
|
||||
this._renderer.updateHeight();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -43,9 +43,7 @@ void ExtensionSubDeclaration1(gd::ObjectMetadata& obj) {
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardOperatorParameters("number")
|
||||
.SetFunctionName("SetAngle")
|
||||
.SetGetter("GetAngle");
|
||||
.UseStandardOperatorParameters("number");
|
||||
|
||||
obj.AddCondition("EmitterAngle",
|
||||
_("Emission angle"),
|
||||
@@ -65,7 +63,8 @@ void ExtensionSubDeclaration1(gd::ObjectMetadata& obj) {
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardOperatorParameters("number");
|
||||
.UseStandardOperatorParameters("number")
|
||||
.SetHidden(); // Angle A is not used.
|
||||
|
||||
obj.AddCondition("EmitterAngleA",
|
||||
_("Emission angle 1"),
|
||||
@@ -75,7 +74,8 @@ void ExtensionSubDeclaration1(gd::ObjectMetadata& obj) {
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardRelationalOperatorParameters("number");
|
||||
.UseStandardRelationalOperatorParameters("number")
|
||||
.SetHidden(); // Angle A is not used.
|
||||
|
||||
obj.AddAction("EmitterAngleB",
|
||||
_("Emission angle 2"),
|
||||
@@ -85,7 +85,8 @@ void ExtensionSubDeclaration1(gd::ObjectMetadata& obj) {
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardOperatorParameters("number");
|
||||
.UseStandardOperatorParameters("number")
|
||||
.SetHidden(); // Angle B is the same as cone spray angle
|
||||
|
||||
obj.AddCondition("EmitterAngleB",
|
||||
_("Emission angle 2"),
|
||||
@@ -95,7 +96,8 @@ void ExtensionSubDeclaration1(gd::ObjectMetadata& obj) {
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardRelationalOperatorParameters("number");
|
||||
.UseStandardRelationalOperatorParameters("number")
|
||||
.SetHidden(); // Angle B is the same as cone spray angle
|
||||
|
||||
obj.AddAction(
|
||||
"ConeSprayAngle",
|
||||
|
@@ -7,6 +7,7 @@ This project is released under the MIT License.
|
||||
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
#include "GDCore/Extensions/Metadata/MultipleInstructionMetadata.h"
|
||||
|
||||
#include "Extension.h"
|
||||
#include "ParticleEmitterObject.h"
|
||||
@@ -207,48 +208,6 @@ void ExtensionSubDeclaration2(gd::ObjectMetadata& obj) {
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardRelationalOperatorParameters("number");
|
||||
|
||||
obj.AddAction(
|
||||
"ParticleAngle1",
|
||||
_("Angle, parameter 1"),
|
||||
_("Modify parameter 1 of the angle of particles."),
|
||||
_("the parameter 1 of angle"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardOperatorParameters("number");
|
||||
|
||||
obj.AddCondition("ParticleAngle1",
|
||||
_("Angle, parameter 1"),
|
||||
_("Compare parameter 1 of the angle of particles."),
|
||||
_("the parameter 1 of angle"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardRelationalOperatorParameters("number");
|
||||
|
||||
obj.AddAction(
|
||||
"ParticleAngle2",
|
||||
_("Angle, parameter 2"),
|
||||
_("Modify parameter 2 of the angle of particles"),
|
||||
_("the parameter 2 of angle"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardOperatorParameters("number");
|
||||
|
||||
obj.AddCondition("ParticleAngle2",
|
||||
_("Angle, parameter 2"),
|
||||
_("Compare parameter 2 of the angle of particles."),
|
||||
_("the parameter 2 of angle"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png",
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardRelationalOperatorParameters("number");
|
||||
|
||||
obj.AddAction("ParticleAlpha1",
|
||||
_("Start opacity"),
|
||||
_("Modify the start opacity of particles."),
|
||||
@@ -301,4 +260,59 @@ void ExtensionSubDeclaration2(gd::ObjectMetadata& obj) {
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter");
|
||||
|
||||
obj.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
"ParticleRotationMinSpeed",
|
||||
_("Particle rotation min speed"),
|
||||
_("the minimum rotation speed of the particles"),
|
||||
_("the particles minimum rotation speed"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardParameters("number")
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("setParticleRotationMinSpeed")
|
||||
.SetGetter("getParticleRotationMinSpeed");
|
||||
|
||||
obj.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
"ParticleRotationMaxSpeed",
|
||||
_("Particle rotation max speed"),
|
||||
_("the maximum rotation speed of the particles"),
|
||||
_("the particles maximum rotation speed"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardParameters("number")
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("setParticleRotationMaxSpeed")
|
||||
.SetGetter("getParticleRotationMaxSpeed");
|
||||
|
||||
obj.AddExpressionAndConditionAndAction(
|
||||
"number",
|
||||
"MaxParticlesCount",
|
||||
_("Number of displayed particles"),
|
||||
_("the maximum number of displayed particles"),
|
||||
_("the maximum number of displayed particles"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardParameters("number")
|
||||
.SetFunctionName("setMaxParticlesCount")
|
||||
.SetGetter("getMaxParticlesCount");
|
||||
|
||||
obj.AddExpressionAndConditionAndAction(
|
||||
"boolean",
|
||||
"AdditiveRendering",
|
||||
_("Activate particles additive rendering"),
|
||||
_("the particles additive rendering is activated"),
|
||||
_("displaying particles with additive rendering activated"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon24.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter")
|
||||
.UseStandardParameters("boolean")
|
||||
.MarkAsAdvanced()
|
||||
.SetFunctionName("setAdditiveRendering")
|
||||
.SetGetter("getAdditiveRendering");
|
||||
|
||||
}
|
||||
|
@@ -5,10 +5,9 @@ Copyright (c) 2010-2016 Florian Rival (Florian.Rival@gmail.com)
|
||||
This project is released under the MIT License.
|
||||
*/
|
||||
|
||||
#include "Extension.h"
|
||||
#include "GDCore/Extensions/PlatformExtension.h"
|
||||
#include "GDCore/Tools/Localization.h"
|
||||
|
||||
#include "Extension.h"
|
||||
#include "ParticleEmitterObject.h"
|
||||
|
||||
/**
|
||||
@@ -241,12 +240,20 @@ void ExtensionSubDeclaration3(gd::ObjectMetadata& obj) {
|
||||
_("Emission angle A"),
|
||||
_("Advanced"),
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false);
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false)
|
||||
.SetHidden();
|
||||
obj.AddExpression("EmitterAngleB",
|
||||
_("Emission angle B"),
|
||||
_("Emission angle B"),
|
||||
_("Advanced"),
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false)
|
||||
.SetHidden();
|
||||
obj.AddExpression("ConeSprayAngle",
|
||||
_("Angle of the spray cone"),
|
||||
_("Angle of the spray cone"),
|
||||
_("Common"),
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false);
|
||||
obj.AddExpression("ZoneRadius",
|
||||
_("Radius of emission zone"),
|
||||
@@ -350,17 +357,4 @@ void ExtensionSubDeclaration3(gd::ObjectMetadata& obj) {
|
||||
_("Setup"),
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false);
|
||||
obj.AddExpression("ParticleAngle1",
|
||||
_("Parameter 1 of angle"),
|
||||
_("Parameter 1 of angle"),
|
||||
_("Setup"),
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false);
|
||||
obj.AddExpression("ParticleAngle2",
|
||||
_("Parameter 2 of angle"),
|
||||
_("Parameter 2 of angle"),
|
||||
_("Setup"),
|
||||
"CppPlatform/Extensions/particleSystemicon16.png")
|
||||
.AddParameter("object", _("Object"), "ParticleEmitter", false);
|
||||
|
||||
}
|
||||
|
@@ -191,6 +191,7 @@ class ParticleSystemJsExtension : public gd::PlatformExtension {
|
||||
expressions["EmitterAngle"].SetFunctionName("getAngle");
|
||||
expressions["EmitterAngleA"].SetFunctionName("getEmitterAngleA");
|
||||
expressions["EmitterAngleB"].SetFunctionName("getEmitterAngleB");
|
||||
expressions["ConeSprayAngle"].SetFunctionName("getConeSprayAngle");
|
||||
expressions["ZoneRadius"].SetFunctionName("getZoneRadius");
|
||||
expressions["ParticleGravityX"].SetFunctionName("getParticleGravityX");
|
||||
expressions["ParticleGravityY"].SetFunctionName("getParticleGravityY");
|
||||
|
@@ -12,7 +12,7 @@ namespace gdjs {
|
||||
started: boolean = false;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
runtimeObject: gdjs.RuntimeObject,
|
||||
objectData: any
|
||||
) {
|
||||
@@ -24,7 +24,7 @@ namespace gdjs {
|
||||
graphics.drawCircle(0, 0, objectData.rendererParam1);
|
||||
} else if (objectData.rendererType === 'Line') {
|
||||
graphics.drawRect(
|
||||
objectData.rendererParam1,
|
||||
0,
|
||||
0,
|
||||
objectData.rendererParam1,
|
||||
objectData.rendererParam2
|
||||
@@ -40,7 +40,7 @@ namespace gdjs {
|
||||
);
|
||||
} else if (objectData.textureParticleName) {
|
||||
const sprite = new PIXI.Sprite(
|
||||
(runtimeScene
|
||||
(instanceContainer
|
||||
.getGame()
|
||||
.getImageManager() as gdjs.PixiImageManager).getPIXITexture(
|
||||
objectData.textureParticleName
|
||||
@@ -62,7 +62,7 @@ namespace gdjs {
|
||||
// Render the texture from graphics using the PIXI Renderer.
|
||||
// TODO: could be optimized by generating the texture only once per object type,
|
||||
// instead of at each object creation.
|
||||
const pixiRenderer = runtimeScene
|
||||
const pixiRenderer = instanceContainer
|
||||
.getGame()
|
||||
.getRenderer()
|
||||
.getPIXIRenderer();
|
||||
@@ -149,25 +149,28 @@ namespace gdjs {
|
||||
minimumScaleMultiplier: m,
|
||||
isStepped: false,
|
||||
};
|
||||
// Angle of the spray cone
|
||||
// @ts-ignore
|
||||
config.startRotation = {
|
||||
min: -objectData.emitterAngleB / 2.0,
|
||||
max: objectData.emitterAngleB / 2.0,
|
||||
};
|
||||
const mediumLifetime =
|
||||
(objectData.particleLifeTimeMin + objectData.particleLifeTimeMax) / 2.0;
|
||||
// Rotation speed of the particles
|
||||
// @ts-ignore
|
||||
config.rotationSpeed = {
|
||||
min: objectData.particleAngle1 / mediumLifetime,
|
||||
max: objectData.particleAngle2 / mediumLifetime,
|
||||
min: objectData.particleAngle1,
|
||||
max: objectData.particleAngle2,
|
||||
};
|
||||
// @ts-ignore
|
||||
config.blendMode = objectData.additive ? 'ADD' : 'NORMAL';
|
||||
this.renderer = new PIXI.Container();
|
||||
// The embedded particle emitter is supposed to be the last minor version
|
||||
// of the version 4 of the particle emitter object
|
||||
// See source https://github.com/pixijs/particle-emitter/blob/v4.3.1/src/Emitter.ts
|
||||
// @ts-ignore
|
||||
this.emitter = new PIXI.particles.Emitter(this.renderer, texture, config);
|
||||
this.start();
|
||||
const layer = runtimeScene.getLayer(runtimeObject.getLayer());
|
||||
const layer = instanceContainer.getLayer(runtimeObject.getLayer());
|
||||
if (layer) {
|
||||
layer
|
||||
.getRenderer()
|
||||
@@ -197,8 +200,12 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
setForce(min: float, max: float): void {
|
||||
this.emitter.startSpeed.value = max;
|
||||
this.emitter.minimumSpeedMultiplier = max !== 0 ? min / max : 1;
|
||||
// If max force is zero, PIXI seems to not be able to compute correctly
|
||||
// the angle of the emitter, resulting in it staying at 0° or 180°.
|
||||
// See https://github.com/4ian/GDevelop/issues/4312.
|
||||
const _max = max || 0.000001;
|
||||
this.emitter.startSpeed.value = _max;
|
||||
this.emitter.minimumSpeedMultiplier = min / _max;
|
||||
}
|
||||
|
||||
setZoneRadius(radius: float): void {
|
||||
@@ -242,6 +249,21 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
setParticleRotationSpeed(min: float, max: float): void {
|
||||
this.emitter.minRotationSpeed = min;
|
||||
this.emitter.maxRotationSpeed = max;
|
||||
}
|
||||
|
||||
setMaxParticlesCount(count: float): void {
|
||||
this.emitter.maxParticles = count;
|
||||
}
|
||||
|
||||
setAdditiveRendering(enabled: boolean): void {
|
||||
this.emitter.particleBlendMode = enabled
|
||||
? PIXI.BLEND_MODES.ADD
|
||||
: PIXI.BLEND_MODES.NORMAL;
|
||||
}
|
||||
|
||||
setAlpha(alpha1: number, alpha2: number): void {
|
||||
this.emitter.startAlpha.value = alpha1 / 255.0;
|
||||
if (this.emitter.startAlpha.next) {
|
||||
@@ -267,25 +289,28 @@ namespace gdjs {
|
||||
|
||||
isTextureNameValid(
|
||||
texture: string,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): boolean {
|
||||
const invalidPixiTexture = runtimeScene
|
||||
const invalidPixiTexture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getInvalidPIXITexture();
|
||||
const pixiTexture = runtimeScene
|
||||
const pixiTexture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXITexture(texture);
|
||||
return pixiTexture.valid && pixiTexture !== invalidPixiTexture;
|
||||
}
|
||||
|
||||
setTextureName(texture: string, runtimeScene: gdjs.RuntimeScene): void {
|
||||
const invalidPixiTexture = runtimeScene
|
||||
setTextureName(
|
||||
texture: string,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): void {
|
||||
const invalidPixiTexture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getInvalidPIXITexture();
|
||||
const pixiTexture = runtimeScene
|
||||
const pixiTexture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXITexture(texture);
|
||||
|
@@ -6,8 +6,14 @@
|
||||
|
||||
namespace gdjs {
|
||||
export type ParticleEmitterObjectDataType = {
|
||||
/**
|
||||
* @deprecated Data not used
|
||||
*/
|
||||
emitterAngleA: number;
|
||||
emitterForceMin: number;
|
||||
/**
|
||||
* Cone spray angle (degrees)
|
||||
*/
|
||||
emitterAngleB: number;
|
||||
zoneRadius: number;
|
||||
emitterForceMax: number;
|
||||
@@ -23,7 +29,13 @@ namespace gdjs {
|
||||
particleBlue1: number;
|
||||
particleSize2: number;
|
||||
particleSize1: number;
|
||||
/**
|
||||
* Particle max rotation speed (degrees/second)
|
||||
*/
|
||||
particleAngle2: number;
|
||||
/**
|
||||
* Particle min rotation speed (degrees/second)
|
||||
*/
|
||||
particleAngle1: number;
|
||||
particleAlpha1: number;
|
||||
rendererType: string;
|
||||
@@ -49,6 +61,9 @@ namespace gdjs {
|
||||
* Displays particles.
|
||||
*/
|
||||
export class ParticleEmitterObject extends gdjs.RuntimeObject {
|
||||
/**
|
||||
* @deprecated Data not used
|
||||
*/
|
||||
angleA: number;
|
||||
angleB: number;
|
||||
forceMin: number;
|
||||
@@ -75,6 +90,10 @@ namespace gdjs {
|
||||
flow: number;
|
||||
tank: number;
|
||||
destroyWhenNoParticles: boolean;
|
||||
particleRotationMinSpeed: number;
|
||||
particleRotationMaxSpeed: number;
|
||||
maxParticlesCount: number;
|
||||
additiveRendering: boolean;
|
||||
_posDirty: boolean = true;
|
||||
_angleDirty: boolean = true;
|
||||
_forceDirty: boolean = true;
|
||||
@@ -86,6 +105,9 @@ namespace gdjs {
|
||||
_alphaDirty: boolean = true;
|
||||
_flowDirty: boolean = true;
|
||||
_tankDirty: boolean = true;
|
||||
_particleRotationSpeedDirty: boolean = true;
|
||||
_maxParticlesCountDirty: boolean = true;
|
||||
_additiveRenderingDirty: boolean = true;
|
||||
// Don't mark texture as dirty if not using one.
|
||||
_textureDirty: boolean;
|
||||
|
||||
@@ -93,16 +115,16 @@ namespace gdjs {
|
||||
_renderer: gdjs.ParticleEmitterObjectRenderer;
|
||||
|
||||
/**
|
||||
* @param the object belongs to
|
||||
* @param instanceContainer the container the object belongs to
|
||||
* @param particleObjectData The initial properties of the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
particleObjectData: ParticleEmitterObjectData
|
||||
) {
|
||||
super(runtimeScene, particleObjectData);
|
||||
super(instanceContainer, particleObjectData);
|
||||
this._renderer = new gdjs.ParticleEmitterObjectRenderer(
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
this,
|
||||
particleObjectData
|
||||
);
|
||||
@@ -132,6 +154,10 @@ namespace gdjs {
|
||||
this.flow = particleObjectData.flow;
|
||||
this.tank = particleObjectData.tank;
|
||||
this.destroyWhenNoParticles = particleObjectData.destroyWhenNoParticles;
|
||||
this.particleRotationMinSpeed = particleObjectData.particleAngle1;
|
||||
this.particleRotationMaxSpeed = particleObjectData.particleAngle2;
|
||||
this.maxParticlesCount = particleObjectData.maxParticleNb;
|
||||
this.additiveRendering = particleObjectData.additive;
|
||||
this._textureDirty = this.texture !== '';
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
@@ -176,6 +202,18 @@ namespace gdjs {
|
||||
if (oldObjectData.emitterForceMin !== newObjectData.emitterForceMin) {
|
||||
this.setEmitterForceMin(newObjectData.emitterForceMin);
|
||||
}
|
||||
if (oldObjectData.particleAngle1 !== newObjectData.particleAngle1) {
|
||||
this.setParticleRotationMinSpeed(newObjectData.particleAngle1);
|
||||
}
|
||||
if (oldObjectData.particleAngle2 !== newObjectData.particleAngle2) {
|
||||
this.setParticleRotationMaxSpeed(newObjectData.particleAngle2);
|
||||
}
|
||||
if (oldObjectData.maxParticleNb !== newObjectData.maxParticleNb) {
|
||||
this.setMaxParticlesCount(newObjectData.maxParticleNb);
|
||||
}
|
||||
if (oldObjectData.additive !== newObjectData.additive) {
|
||||
this.setAdditiveRendering(newObjectData.additive);
|
||||
}
|
||||
if (oldObjectData.emitterForceMax !== newObjectData.emitterForceMax) {
|
||||
this.setEmitterForceMax(newObjectData.emitterForceMax);
|
||||
}
|
||||
@@ -231,7 +269,10 @@ namespace gdjs {
|
||||
if (
|
||||
oldObjectData.textureParticleName !== newObjectData.textureParticleName
|
||||
) {
|
||||
this.setTexture(newObjectData.textureParticleName, this._runtimeScene);
|
||||
this.setTexture(
|
||||
newObjectData.textureParticleName,
|
||||
this.getRuntimeScene()
|
||||
);
|
||||
}
|
||||
if (oldObjectData.flow !== newObjectData.flow) {
|
||||
this.setFlow(newObjectData.flow);
|
||||
@@ -259,7 +300,7 @@ namespace gdjs {
|
||||
oldObjectData.rendererParam2 !== newObjectData.rendererParam2
|
||||
) {
|
||||
// Destroy the renderer, ensure it's removed from the layer.
|
||||
const layer = this._runtimeScene.getLayer(this.layer);
|
||||
const layer = this.getInstanceContainer().getLayer(this.layer);
|
||||
layer
|
||||
.getRenderer()
|
||||
.removeRendererObject(this._renderer.getRendererObject());
|
||||
@@ -267,7 +308,7 @@ namespace gdjs {
|
||||
|
||||
// and recreate the renderer, which will add itself to the layer.
|
||||
this._renderer = new gdjs.ParticleEmitterObjectRenderer(
|
||||
this._runtimeScene,
|
||||
this.getInstanceContainer(),
|
||||
this,
|
||||
newObjectData
|
||||
);
|
||||
@@ -281,15 +322,27 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
update(runtimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
if (this._posDirty) {
|
||||
this._renderer.setPosition(this.getX(), this.getY());
|
||||
}
|
||||
if (this._particleRotationSpeedDirty) {
|
||||
this._renderer.setParticleRotationSpeed(
|
||||
this.particleRotationMinSpeed,
|
||||
this.particleRotationMaxSpeed
|
||||
);
|
||||
}
|
||||
if (this._maxParticlesCountDirty) {
|
||||
this._renderer.setMaxParticlesCount(this.maxParticlesCount);
|
||||
}
|
||||
if (this._additiveRenderingDirty) {
|
||||
this._renderer.setAdditiveRendering(this.additiveRendering);
|
||||
}
|
||||
if (this._angleDirty) {
|
||||
const angle = this.getAngle();
|
||||
this._renderer.setAngle(
|
||||
this.angle - this.angleB / 2.0,
|
||||
this.angle + this.angleB / 2.0
|
||||
angle - this.angleB / 2.0,
|
||||
angle + this.angleB / 2.0
|
||||
);
|
||||
}
|
||||
if (this._forceDirty) {
|
||||
@@ -324,24 +377,25 @@ namespace gdjs {
|
||||
this._renderer.resetEmission(this.flow, this.tank);
|
||||
}
|
||||
if (this._textureDirty) {
|
||||
this._renderer.setTextureName(this.texture, runtimeScene);
|
||||
this._renderer.setTextureName(this.texture, instanceContainer);
|
||||
}
|
||||
this._posDirty = this._angleDirty = this._forceDirty = this._zoneRadiusDirty = false;
|
||||
this._lifeTimeDirty = this._gravityDirty = this._colorDirty = this._sizeDirty = false;
|
||||
this._alphaDirty = this._flowDirty = this._textureDirty = this._tankDirty = false;
|
||||
this._renderer.update(this.getElapsedTime(runtimeScene) / 1000.0);
|
||||
this._additiveRenderingDirty = this._maxParticlesCountDirty = this._particleRotationSpeedDirty = false;
|
||||
this._renderer.update(this.getElapsedTime() / 1000.0);
|
||||
if (
|
||||
this._renderer.hasStarted() &&
|
||||
this.getParticleCount() === 0 &&
|
||||
this.destroyWhenNoParticles
|
||||
) {
|
||||
this.deleteFromScene(runtimeScene);
|
||||
this.deleteFromScene(instanceContainer);
|
||||
}
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene: gdjs.RuntimeScene): void {
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._renderer.destroy();
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
}
|
||||
|
||||
getEmitterForceMin(): number {
|
||||
@@ -372,10 +426,60 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
setParticleRotationMinSpeed(speed: number): void {
|
||||
if (this.particleRotationMinSpeed !== speed) {
|
||||
this._particleRotationSpeedDirty = true;
|
||||
this.particleRotationMinSpeed = speed;
|
||||
}
|
||||
}
|
||||
|
||||
getParticleRotationMinSpeed(): number {
|
||||
return this.particleRotationMinSpeed;
|
||||
}
|
||||
|
||||
setParticleRotationMaxSpeed(speed: number): void {
|
||||
if (this.particleRotationMaxSpeed !== speed) {
|
||||
this._particleRotationSpeedDirty = true;
|
||||
this.particleRotationMaxSpeed = speed;
|
||||
}
|
||||
}
|
||||
|
||||
getParticleRotationMaxSpeed(): number {
|
||||
return this.particleRotationMaxSpeed;
|
||||
}
|
||||
|
||||
setMaxParticlesCount(count: number): void {
|
||||
if (this.maxParticlesCount !== count) {
|
||||
this._maxParticlesCountDirty = true;
|
||||
this.maxParticlesCount = count;
|
||||
}
|
||||
}
|
||||
|
||||
getMaxParticlesCount(): number {
|
||||
return this.maxParticlesCount;
|
||||
}
|
||||
|
||||
setAdditiveRendering(enabled: boolean) {
|
||||
if (this.additiveRendering !== enabled) {
|
||||
this._additiveRenderingDirty = true;
|
||||
this.additiveRendering = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
getAdditiveRendering(): boolean {
|
||||
return this.additiveRendering;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Prefer using getAngle
|
||||
*/
|
||||
getEmitterAngle(): float {
|
||||
return (this.angleA + this.angleB) / 2.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Prefer using setAngle
|
||||
*/
|
||||
setEmitterAngle(angle: float): void {
|
||||
const oldAngle = this.getEmitterAngle();
|
||||
if (angle !== oldAngle) {
|
||||
@@ -385,10 +489,16 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated This function returns data that is not used.
|
||||
*/
|
||||
getEmitterAngleA(): float {
|
||||
return this.angleA;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated This function sets data that is not used.
|
||||
*/
|
||||
setEmitterAngleA(angle: float): void {
|
||||
if (this.angleA !== angle) {
|
||||
this._angleDirty = true;
|
||||
@@ -408,17 +518,11 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
getConeSprayAngle(): float {
|
||||
return Math.abs(this.angleB - this.angleA);
|
||||
return this.getEmitterAngleB();
|
||||
}
|
||||
|
||||
setConeSprayAngle(angle: float): void {
|
||||
const oldCone = this.getConeSprayAngle();
|
||||
if (oldCone !== angle) {
|
||||
this._angleDirty = true;
|
||||
const midAngle = this.getEmitterAngle();
|
||||
this.angleA = midAngle - angle / 2.0;
|
||||
this.angleB = midAngle + angle / 2.0;
|
||||
}
|
||||
this.setEmitterAngleB(angle);
|
||||
}
|
||||
|
||||
getZoneRadius(): float {
|
||||
@@ -734,9 +838,12 @@ namespace gdjs {
|
||||
return this.texture;
|
||||
}
|
||||
|
||||
setTexture(texture: string, runtimeScene: gdjs.RuntimeScene): void {
|
||||
setTexture(
|
||||
texture: string,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): void {
|
||||
if (this.texture !== texture) {
|
||||
if (this._renderer.isTextureNameValid(texture, runtimeScene)) {
|
||||
if (this._renderer.isTextureNameValid(texture, instanceContainer)) {
|
||||
this.texture = texture;
|
||||
this._textureDirty = true;
|
||||
}
|
||||
|
@@ -4,35 +4,37 @@ Copyright (c) 2013-2016 Florian Rival (Florian.Rival@gmail.com)
|
||||
*/
|
||||
|
||||
namespace gdjs {
|
||||
export interface RuntimeInstanceContainer {
|
||||
pathfindingObstaclesManager: gdjs.PathfindingObstaclesManager;
|
||||
}
|
||||
declare var rbush: any;
|
||||
|
||||
/**
|
||||
* PathfindingObstaclesManager manages the common objects shared by objects having a
|
||||
* pathfinding behavior: In particular, the obstacles behaviors are required to declare
|
||||
* themselves (see `PathfindingObstaclesManager.addObstacle`) to the manager of their associated scene
|
||||
* (see `gdjs.PathfindingRuntimeBehavior.obstaclesManagers`).
|
||||
* PathfindingObstaclesManager manages the common objects shared by objects
|
||||
* having a pathfinding behavior: In particular, the obstacles behaviors are
|
||||
* required to declare themselves (see
|
||||
* `PathfindingObstaclesManager.addObstacle`) to the manager of their
|
||||
* associated container (see
|
||||
* `gdjs.PathfindingRuntimeBehavior.obstaclesManagers`).
|
||||
*/
|
||||
export class PathfindingObstaclesManager {
|
||||
_obstaclesRBush: any;
|
||||
|
||||
/**
|
||||
* @param object The object
|
||||
*/
|
||||
constructor(runtimeScene: gdjs.RuntimeScene) {
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
this._obstaclesRBush = new rbush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the obstacles manager of a scene.
|
||||
* Get the obstacles manager of an instance container.
|
||||
*/
|
||||
static getManager(runtimeScene) {
|
||||
if (!runtimeScene.pathfindingObstaclesManager) {
|
||||
static getManager(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
if (!instanceContainer.pathfindingObstaclesManager) {
|
||||
//Create the shared manager if necessary.
|
||||
runtimeScene.pathfindingObstaclesManager = new gdjs.PathfindingObstaclesManager(
|
||||
runtimeScene
|
||||
instanceContainer.pathfindingObstaclesManager = new gdjs.PathfindingObstaclesManager(
|
||||
instanceContainer
|
||||
);
|
||||
}
|
||||
return runtimeScene.pathfindingObstaclesManager;
|
||||
return instanceContainer.pathfindingObstaclesManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,14 +113,14 @@ namespace gdjs {
|
||||
> | null = null;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._impassable = behaviorData.impassable;
|
||||
this._cost = behaviorData.cost;
|
||||
this._manager = PathfindingObstaclesManager.getManager(runtimeScene);
|
||||
this._manager = PathfindingObstaclesManager.getManager(instanceContainer);
|
||||
|
||||
//Note that we can't use getX(), getWidth()... of owner here:
|
||||
//The owner is not yet fully constructed.
|
||||
@@ -140,7 +142,7 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
//Make sure the obstacle is or is not in the obstacles manager.
|
||||
if (!this.activated() && this._registeredInManager) {
|
||||
this._manager.removeObstacle(this);
|
||||
@@ -170,7 +172,7 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene: gdjs.RuntimeScene) {}
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
getAABB() {
|
||||
return this.owner.getAABB();
|
||||
|
@@ -38,11 +38,11 @@ namespace gdjs {
|
||||
_movementAngle: float = 0;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
|
||||
//The path computed and followed by the object (Array of arrays containing x and y position)
|
||||
if (this._path === undefined) {
|
||||
@@ -60,7 +60,9 @@ namespace gdjs {
|
||||
this._gridOffsetX = behaviorData.gridOffsetX || 0;
|
||||
this._gridOffsetY = behaviorData.gridOffsetY || 0;
|
||||
this._extraBorder = behaviorData.extraBorder;
|
||||
this._manager = gdjs.PathfindingObstaclesManager.getManager(runtimeScene);
|
||||
this._manager = gdjs.PathfindingObstaclesManager.getManager(
|
||||
instanceContainer
|
||||
);
|
||||
this._searchContext = new gdjs.PathfindingRuntimeBehavior.SearchContext(
|
||||
this._manager
|
||||
);
|
||||
@@ -313,7 +315,11 @@ namespace gdjs {
|
||||
/**
|
||||
* Compute and move on the path to the specified destination.
|
||||
*/
|
||||
moveTo(runtimeScene: gdjs.RuntimeScene, x: float, y: float) {
|
||||
moveTo(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
x: float,
|
||||
y: float
|
||||
) {
|
||||
const owner = this.owner;
|
||||
|
||||
//First be sure that there is a path to compute.
|
||||
@@ -403,13 +409,13 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
if (this._path.length === 0 || this._reachedEnd) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the speed of the object
|
||||
const timeDelta = this.owner.getElapsedTime(runtimeScene) / 1000;
|
||||
const timeDelta = this.owner.getElapsedTime() / 1000;
|
||||
const previousSpeed = this._speed;
|
||||
if (this._speed !== this._maxSpeed) {
|
||||
this._speed += this._acceleration * timeDelta;
|
||||
@@ -452,8 +458,7 @@ namespace gdjs {
|
||||
) {
|
||||
this.owner.rotateTowardAngle(
|
||||
this._movementAngle + this._angleOffset,
|
||||
this._angularSpeed,
|
||||
runtimeScene
|
||||
this._angularSpeed
|
||||
);
|
||||
}
|
||||
} else {
|
||||
@@ -463,7 +468,7 @@ namespace gdjs {
|
||||
this.owner.setY(newPos[1]);
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene: gdjs.RuntimeScene) {}
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
/**
|
||||
* Compute the euclidean distance between two positions.
|
||||
|
@@ -61,9 +61,14 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
sprites: [
|
||||
{
|
||||
originPoint: objectCenteredOnCells
|
||||
? { x: 80, y: 80 }
|
||||
: { x: 87, y: 87 },
|
||||
centerPoint: { x: 80, y: 80 },
|
||||
? { name: 'Origin', x: 80, y: 80 }
|
||||
: { name: 'Origin', x: 87, y: 87 },
|
||||
centerPoint: {
|
||||
name: 'Center',
|
||||
x: 80,
|
||||
y: 80,
|
||||
automatic: false,
|
||||
},
|
||||
points: [
|
||||
{ name: 'Center', x: 80, y: 80 },
|
||||
objectCenteredOnCells
|
||||
@@ -71,13 +76,17 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
: { name: 'Origin', x: 87, y: 87 },
|
||||
],
|
||||
hasCustomCollisionMask: false,
|
||||
customCollisionMask: [],
|
||||
image: '',
|
||||
},
|
||||
],
|
||||
timeBetweenFrames: 0,
|
||||
looping: false,
|
||||
},
|
||||
],
|
||||
useMultipleDirections: false,
|
||||
},
|
||||
],
|
||||
effects: [],
|
||||
behaviors: [
|
||||
{
|
||||
type: 'PathfindingBehavior::PathfindingBehavior',
|
||||
@@ -93,6 +102,9 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
extraBorder: 0,
|
||||
},
|
||||
],
|
||||
variables: [],
|
||||
effects: [],
|
||||
updateIfNotVisible: true,
|
||||
});
|
||||
player.getWidth = function () {
|
||||
return 160;
|
||||
@@ -116,9 +128,14 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
sprites: [
|
||||
{
|
||||
originPoint: objectCenteredOnCells
|
||||
? { x: 80, y: 80 }
|
||||
: { x: 87, y: 87 },
|
||||
centerPoint: { x: 80, y: 80 },
|
||||
? { name: 'Origin', x: 80, y: 80 }
|
||||
: { name: 'Origin', x: 87, y: 87 },
|
||||
centerPoint: {
|
||||
name: 'Center',
|
||||
x: 80,
|
||||
y: 80,
|
||||
automatic: false,
|
||||
},
|
||||
points: [
|
||||
{ name: 'Center', x: 80, y: 80 },
|
||||
objectCenteredOnCells
|
||||
@@ -126,13 +143,17 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
: { name: 'Origin', x: 87, y: 87 },
|
||||
],
|
||||
hasCustomCollisionMask: false,
|
||||
customCollisionMask: [],
|
||||
image: '',
|
||||
},
|
||||
],
|
||||
timeBetweenFrames: 0,
|
||||
looping: false,
|
||||
},
|
||||
],
|
||||
useMultipleDirections: false,
|
||||
},
|
||||
],
|
||||
effects: [],
|
||||
behaviors: [
|
||||
{
|
||||
type: 'PathfindingBehavior::PathfindingObstacleBehavior',
|
||||
@@ -140,6 +161,9 @@ describe('gdjs.PathfindingRuntimeBehavior', function () {
|
||||
cost: 2,
|
||||
},
|
||||
],
|
||||
variables: [],
|
||||
effects: [],
|
||||
updateIfNotVisible: true,
|
||||
});
|
||||
obstacle.getWidth = function () {
|
||||
return 160;
|
||||
|
@@ -35,7 +35,7 @@ namespace gdjs {
|
||||
*/
|
||||
_registeredBehaviors: Set<Physics2RuntimeBehavior>;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene, sharedData) {
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer, sharedData) {
|
||||
this._registeredBehaviors = new Set();
|
||||
this.gravityX = sharedData.gravityX;
|
||||
this.gravityY = sharedData.gravityY;
|
||||
@@ -349,11 +349,11 @@ namespace gdjs {
|
||||
_verticesBuffer: integer = 0;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this.bodyType = behaviorData.bodyType;
|
||||
this.bullet = behaviorData.bullet;
|
||||
this.fixedRotation = behaviorData.fixedRotation;
|
||||
@@ -382,7 +382,7 @@ namespace gdjs {
|
||||
this.currentContacts.length = 0;
|
||||
this.destroyedDuringFrameLogic = false;
|
||||
this._sharedData = Physics2SharedData.getSharedData(
|
||||
runtimeScene,
|
||||
instanceContainer.getScene(),
|
||||
behaviorData.name
|
||||
);
|
||||
this._tempb2Vec2 = new Box2D.b2Vec2();
|
||||
@@ -824,14 +824,15 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// Step the world if not done this frame yet
|
||||
if (!this._sharedData.stepped) {
|
||||
// Reset started and ended contacts array for all physics instances.
|
||||
this._sharedData.resetStartedAndEndedCollisions();
|
||||
this._sharedData.updateBodiesFromObjects();
|
||||
this._sharedData.step(
|
||||
runtimeScene.getTimeManager().getElapsedTime() / 1000.0
|
||||
instanceContainer.getScene().getTimeManager().getElapsedTime() /
|
||||
1000.0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -862,7 +863,7 @@ namespace gdjs {
|
||||
this._objectOldAngle = this.owner.getAngle();
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// Reset world step to update next frame
|
||||
this._sharedData.stepped = false;
|
||||
}
|
||||
|
@@ -99,7 +99,7 @@ PlatformerObjectBehavior::GetProperties(
|
||||
behaviorContent.GetDoubleAttribute("xGrabTolerance", 10)));
|
||||
properties["useLegacyTrajectory"]
|
||||
.SetLabel(_("Use frame rate dependent trajectories (deprecated, it's "
|
||||
"recommended to let this unchecked)"))
|
||||
"recommended to leave this unchecked)"))
|
||||
.SetGroup(_("Deprecated options (advanced)"))
|
||||
.SetValue(behaviorContent.GetBoolAttribute("useLegacyTrajectory", true)
|
||||
? "true"
|
||||
|
@@ -117,11 +117,11 @@ namespace gdjs {
|
||||
private _manager: gdjs.PlatformObjectsManager;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._gravity = behaviorData.gravity;
|
||||
this._maxFallingSpeed = behaviorData.maxFallingSpeed;
|
||||
this._ladderClimbingSpeed = behaviorData.ladderClimbingSpeed || 150;
|
||||
@@ -146,7 +146,7 @@ namespace gdjs {
|
||||
this._potentialCollidingObjects = [];
|
||||
this._overlappedJumpThru = [];
|
||||
|
||||
this._manager = gdjs.PlatformObjectsManager.getManager(runtimeScene);
|
||||
this._manager = gdjs.PlatformObjectsManager.getManager(instanceContainer);
|
||||
|
||||
this._falling = new Falling(this);
|
||||
this._onFloor = new OnFloor(this);
|
||||
@@ -210,7 +210,7 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
const LEFTKEY = 37;
|
||||
const UPKEY = 38;
|
||||
const RIGHTKEY = 39;
|
||||
@@ -219,13 +219,13 @@ namespace gdjs {
|
||||
const RSHIFTKEY = 2016;
|
||||
const SPACEKEY = 32;
|
||||
const object = this.owner;
|
||||
const timeDelta = this.owner.getElapsedTime(runtimeScene) / 1000;
|
||||
const timeDelta = this.owner.getElapsedTime() / 1000;
|
||||
|
||||
//0.1) Get the player input:
|
||||
this._requestedDeltaX = 0;
|
||||
this._requestedDeltaY = 0;
|
||||
|
||||
const inputManager = runtimeScene.getGame().getInputManager();
|
||||
const inputManager = instanceContainer.getGame().getInputManager();
|
||||
this._leftKey ||
|
||||
(this._leftKey =
|
||||
!this._ignoreDefaultControls && inputManager.isKeyPressed(LEFTKEY));
|
||||
@@ -329,7 +329,7 @@ namespace gdjs {
|
||||
this._lastDeltaY = object.getY() - oldY;
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene: gdjs.RuntimeScene) {}
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
private _updateSpeed(timeDelta: float): float {
|
||||
const previousSpeed = this._currentSpeed;
|
||||
|
@@ -8,34 +8,31 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Manages the common objects shared by objects having a
|
||||
* platform behavior: in particular, the platforms behaviors are required to declare
|
||||
* themselves (see PlatformObjectsManager.addPlatform) to the manager of their associated scene
|
||||
* (see PlatformRuntimeBehavior.getManager).
|
||||
* platform behavior: in particular, the platforms behaviors are required to
|
||||
* declare themselves (see PlatformObjectsManager.addPlatform) to the manager
|
||||
* of their associated container (see PlatformRuntimeBehavior.getManager).
|
||||
*/
|
||||
export class PlatformObjectsManager {
|
||||
private _platformRBush: any;
|
||||
|
||||
/**
|
||||
* @param object The object
|
||||
*/
|
||||
constructor(runtimeScene: gdjs.RuntimeScene) {
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
this._platformRBush = new rbush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the platforms manager of a scene.
|
||||
* Get the platforms manager of an instance container.
|
||||
*/
|
||||
static getManager(runtimeScene: gdjs.RuntimeScene) {
|
||||
static getManager(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
// @ts-ignore
|
||||
if (!runtimeScene.platformsObjectsManager) {
|
||||
if (!instanceContainer.platformsObjectsManager) {
|
||||
//Create the shared manager if necessary.
|
||||
// @ts-ignore
|
||||
runtimeScene.platformsObjectsManager = new gdjs.PlatformObjectsManager(
|
||||
runtimeScene
|
||||
instanceContainer.platformsObjectsManager = new gdjs.PlatformObjectsManager(
|
||||
instanceContainer
|
||||
);
|
||||
}
|
||||
// @ts-ignore
|
||||
return runtimeScene.platformsObjectsManager;
|
||||
return instanceContainer.platformsObjectsManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,11 +129,11 @@ namespace gdjs {
|
||||
_registeredInManager: boolean = false;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._platformType = behaviorData.platformType;
|
||||
if (behaviorData.platformType === 'Ladder') {
|
||||
this._platformType = PlatformRuntimeBehavior.LADDER;
|
||||
@@ -147,7 +144,7 @@ namespace gdjs {
|
||||
}
|
||||
this._canBeGrabbed = behaviorData.canBeGrabbed || false;
|
||||
this._yGrabOffset = behaviorData.yGrabOffset || 0;
|
||||
this._manager = PlatformObjectsManager.getManager(runtimeScene);
|
||||
this._manager = PlatformObjectsManager.getManager(instanceContainer);
|
||||
}
|
||||
|
||||
updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {
|
||||
@@ -169,7 +166,7 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
//Scene change is not supported
|
||||
/*if ( parentScene != &scene ) //Parent scene has changed
|
||||
{
|
||||
@@ -211,7 +208,7 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
doStepPostEvents(runtimeScene: gdjs.RuntimeScene) {}
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
onActivate() {
|
||||
if (this._registeredInManager) {
|
||||
|
@@ -3,6 +3,7 @@ namespace gdjs {
|
||||
|
||||
const logger = new gdjs.Logger('Player Authentication');
|
||||
const authComponents = gdjs.playerAuthenticationComponents;
|
||||
// TODO EBO Replace runtimeScene to instanceContainer.
|
||||
export namespace playerAuthentication {
|
||||
// Authentication information.
|
||||
let _username: string | null = null;
|
||||
|
@@ -27,11 +27,11 @@ namespace gdjs {
|
||||
|
||||
constructor(
|
||||
runtimeObject: gdjs.ShapePainterRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
this._graphics = new PIXI.Graphics();
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._graphics, runtimeObject.getZOrder());
|
||||
|
@@ -57,14 +57,14 @@ namespace gdjs {
|
||||
private static readonly _pointForTransformation: FloatPoint = [0, 0];
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param shapePainterObjectData The initial properties of the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
shapePainterObjectData: ShapePainterObjectData
|
||||
) {
|
||||
super(runtimeScene, shapePainterObjectData);
|
||||
super(instanceContainer, shapePainterObjectData);
|
||||
this._fillColor = parseInt(
|
||||
gdjs.rgbToHex(
|
||||
shapePainterObjectData.fillColor.r,
|
||||
@@ -88,7 +88,7 @@ namespace gdjs {
|
||||
this._clearBetweenFrames = shapePainterObjectData.clearBetweenFrames;
|
||||
this._renderer = new gdjs.ShapePainterRuntimeObjectRenderer(
|
||||
this,
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
@@ -158,12 +158,12 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
stepBehaviorsPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
stepBehaviorsPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
//We redefine stepBehaviorsPreEvents just to clear the graphics before running events.
|
||||
if (this._clearBetweenFrames) {
|
||||
this.clear();
|
||||
}
|
||||
super.stepBehaviorsPreEvents(runtimeScene);
|
||||
super.stepBehaviorsPreEvents(instanceContainer);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -468,7 +468,7 @@ namespace gdjs {
|
||||
}
|
||||
super.setAngle(angle);
|
||||
this._renderer.updateAngle();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -584,7 +584,7 @@ namespace gdjs {
|
||||
}
|
||||
this._scaleX = newScale * (this._flippedX ? -1 : 1);
|
||||
this._renderer.updateScaleX();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -601,7 +601,7 @@ namespace gdjs {
|
||||
}
|
||||
this._scaleY = newScale * (this._flippedY ? -1 : 1);
|
||||
this._renderer.updateScaleY();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
flipX(enable: boolean): void {
|
||||
@@ -609,7 +609,7 @@ namespace gdjs {
|
||||
this._scaleX *= -1;
|
||||
this._flippedX = enable;
|
||||
this._renderer.updateScaleX();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,7 +618,7 @@ namespace gdjs {
|
||||
this._scaleY *= -1;
|
||||
this._flippedY = enable;
|
||||
this._renderer.updateScaleY();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,7 +660,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
invalidateBounds() {
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getDrawableX(): float {
|
||||
@@ -679,7 +679,7 @@ namespace gdjs {
|
||||
return this._renderer.getHeight();
|
||||
}
|
||||
|
||||
updatePreRender(runtimeScene: gdjs.RuntimeScene): void {
|
||||
updatePreRender(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._renderer.updatePreRender();
|
||||
}
|
||||
|
||||
@@ -741,7 +741,7 @@ namespace gdjs {
|
||||
rectangle[3][0] = left;
|
||||
rectangle[3][1] = bottom;
|
||||
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
updateHitBoxes(): void {
|
||||
|
@@ -4,16 +4,16 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Save a screenshot of the game.
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer The container
|
||||
* @param savePath The path where to save the screenshot
|
||||
*/
|
||||
export const takeScreenshot = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
savePath: string
|
||||
) {
|
||||
const fs = typeof require !== 'undefined' ? require('fs') : null;
|
||||
if (fs) {
|
||||
const canvas = runtimeScene.getGame().getRenderer().getCanvas();
|
||||
const canvas = instanceContainer.getGame().getRenderer().getCanvas();
|
||||
if (canvas) {
|
||||
const content = canvas
|
||||
.toDataURL('image/png')
|
||||
|
@@ -1,17 +1,24 @@
|
||||
namespace gdjs {
|
||||
export interface RuntimeGame {
|
||||
shopifyClients: { [name: string]: any };
|
||||
}
|
||||
declare var ShopifyBuy: any;
|
||||
|
||||
export class ShopifyClientsManager {
|
||||
static set(runtimeScene, name, shopifyClient) {
|
||||
const game = runtimeScene.getGame();
|
||||
static set(
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
name: string,
|
||||
shopifyClient
|
||||
) {
|
||||
const game = instanceContainer.getGame();
|
||||
if (!game.shopifyClients) {
|
||||
game.shopifyClients = {};
|
||||
}
|
||||
game.shopifyClients[name] = shopifyClient;
|
||||
}
|
||||
|
||||
static get(runtimeScene, name) {
|
||||
const game = runtimeScene.getGame();
|
||||
static get(instanceContainer: gdjs.RuntimeInstanceContainer, name: string) {
|
||||
const game = instanceContainer.getGame();
|
||||
if (!game.shopifyClients) {
|
||||
game.shopifyClients = {};
|
||||
}
|
||||
@@ -22,11 +29,11 @@ namespace gdjs {
|
||||
export namespace evtTools {
|
||||
export namespace shopify {
|
||||
export const buildClient = function (
|
||||
runtimeScene,
|
||||
name,
|
||||
domain,
|
||||
appId,
|
||||
accessToken
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
name: string,
|
||||
domain: string,
|
||||
appId: string,
|
||||
accessToken: string
|
||||
) {
|
||||
if (typeof ShopifyBuy === 'undefined') {
|
||||
return;
|
||||
@@ -37,21 +44,24 @@ namespace gdjs {
|
||||
appId: appId,
|
||||
});
|
||||
const shopifyClient = ShopifyBuy.buildClient(config);
|
||||
ShopifyClientsManager.set(runtimeScene, name, shopifyClient);
|
||||
ShopifyClientsManager.set(instanceContainer, name, shopifyClient);
|
||||
};
|
||||
|
||||
export const getCheckoutUrlForProduct = function (
|
||||
runtimeScene,
|
||||
name,
|
||||
productId,
|
||||
quantity,
|
||||
variantIndex,
|
||||
successVariable,
|
||||
errorVariable
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
name: string,
|
||||
productId: string,
|
||||
quantity: number,
|
||||
variantIndex: number,
|
||||
successVariable: gdjs.Variable,
|
||||
errorVariable: gdjs.Variable
|
||||
) {
|
||||
errorVariable.setString('');
|
||||
successVariable.setString('');
|
||||
const shopifyClient = ShopifyClientsManager.get(runtimeScene, name);
|
||||
const shopifyClient = ShopifyClientsManager.get(
|
||||
instanceContainer,
|
||||
name
|
||||
);
|
||||
shopifyClient.fetchProduct(productId).then(
|
||||
function (product) {
|
||||
if (variantIndex < 0 || variantIndex >= product.variants.length) {
|
||||
|
@@ -3,13 +3,17 @@ namespace gdjs {
|
||||
export namespace spatialSound {
|
||||
const logger = new gdjs.Logger('Spatial Sound');
|
||||
export const setSoundPosition = (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
channel: integer,
|
||||
x: float,
|
||||
y: float,
|
||||
z: float
|
||||
) => {
|
||||
const sound = runtimeScene.getSoundManager().getSoundOnChannel(channel);
|
||||
// TODO EBO The position must be transform to the scene position when it comes from a custom object.
|
||||
const sound = instanceContainer
|
||||
.getScene()
|
||||
.getSoundManager()
|
||||
.getSoundOnChannel(channel);
|
||||
if (sound) sound.setSpatialPosition(x, y, z);
|
||||
else
|
||||
logger.error(
|
||||
|
@@ -83,18 +83,20 @@ namespace gdjs {
|
||||
* @returns true if WebGL is supported
|
||||
*/
|
||||
export const isWebGLSupported = (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): boolean => {
|
||||
return runtimeScene.getGame().getRenderer().isWebGLSupported();
|
||||
return instanceContainer.getGame().getRenderer().isWebGLSupported();
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if the game is running as a preview, launched from an editor.
|
||||
* @param runtimeScene The current scene.
|
||||
* @param instanceContainer The current container.
|
||||
* @returns true if the game is running as a preview.
|
||||
*/
|
||||
export const isPreview = (runtimeScene: gdjs.RuntimeScene): boolean => {
|
||||
return runtimeScene.getGame().isPreview();
|
||||
export const isPreview = (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): boolean => {
|
||||
return instanceContainer.getGame().isPreview();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@@ -1,11 +1,11 @@
|
||||
namespace gdjs {
|
||||
class TextEntryRuntimeObjectPixiRenderer {
|
||||
_object: any;
|
||||
_object: gdjs.TextEntryRuntimeObject;
|
||||
_pressHandler: any;
|
||||
_upHandler: any;
|
||||
_downHandler: any;
|
||||
|
||||
constructor(runtimeObject) {
|
||||
constructor(runtimeObject: gdjs.TextEntryRuntimeObject) {
|
||||
this._object = runtimeObject;
|
||||
this._pressHandler = function (evt) {
|
||||
if (!runtimeObject.isActivated()) {
|
||||
|
@@ -12,14 +12,14 @@ namespace gdjs {
|
||||
_renderer: gdjs.TextEntryRuntimeObjectRenderer;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param textEntryObjectData The initial properties of the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
textEntryObjectData: ObjectData
|
||||
) {
|
||||
super(runtimeScene, textEntryObjectData);
|
||||
super(instanceContainer, textEntryObjectData);
|
||||
this._renderer = new gdjs.TextEntryRuntimeObjectRenderer(this);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
@@ -31,14 +31,14 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
if (this._renderer.onDestroy) {
|
||||
this._renderer.onDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
update(runtimeScene: gdjs.RuntimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
if ((this._renderer as any).getString) {
|
||||
this._str = (this._renderer as any).getString();
|
||||
}
|
||||
|
@@ -29,13 +29,16 @@ namespace gdjs {
|
||||
class TextInputRuntimeObjectPixiRenderer {
|
||||
private _object: gdjs.TextInputRuntimeObject;
|
||||
private _input: HTMLInputElement | HTMLTextAreaElement | null = null;
|
||||
private _runtimeScene: gdjs.RuntimeScene;
|
||||
private _instanceContainer: gdjs.RuntimeInstanceContainer;
|
||||
private _runtimeGame: gdjs.RuntimeGame;
|
||||
|
||||
constructor(runtimeObject: gdjs.TextInputRuntimeObject) {
|
||||
constructor(
|
||||
runtimeObject: gdjs.TextInputRuntimeObject,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
this._runtimeScene = runtimeObject.getRuntimeScene();
|
||||
this._runtimeGame = this._runtimeScene.getGame();
|
||||
this._instanceContainer = instanceContainer;
|
||||
this._runtimeGame = this._instanceContainer.getGame();
|
||||
|
||||
this._createElement();
|
||||
}
|
||||
@@ -123,51 +126,69 @@ namespace gdjs {
|
||||
// Hide the input entirely if the layer is not visible.
|
||||
// Because this object is rendered as a DOM element (and not part of the PixiJS
|
||||
// scene graph), we have to do this manually.
|
||||
const layer = this._runtimeScene.getLayer(this._object.getLayer());
|
||||
const layer = this._instanceContainer.getLayer(this._object.getLayer());
|
||||
if (!layer.isVisible()) {
|
||||
this._input.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
const runtimeGame = this._runtimeScene.getGame();
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
TextInputRuntimeObjectPixiRenderer.prototype.updatePreRender
|
||||
) as FloatPoint;
|
||||
|
||||
const runtimeGame = this._instanceContainer.getGame();
|
||||
const runtimeGameRenderer = runtimeGame.getRenderer();
|
||||
const topLeftCanvasCoordinates = layer.convertInverseCoords(
|
||||
this._object.x,
|
||||
this._object.y,
|
||||
0
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
const canvasLeft = topLeftCanvasCoordinates[0];
|
||||
const canvasTop = topLeftCanvasCoordinates[1];
|
||||
|
||||
const bottomRightCanvasCoordinates = layer.convertInverseCoords(
|
||||
this._object.x + this._object.getWidth(),
|
||||
this._object.y + this._object.getHeight(),
|
||||
0
|
||||
0,
|
||||
workingPoint
|
||||
);
|
||||
const canvasRight = bottomRightCanvasCoordinates[0];
|
||||
const canvasBottom = bottomRightCanvasCoordinates[1];
|
||||
|
||||
// Hide the input entirely if not visible at all.
|
||||
const isOutsideCanvas =
|
||||
bottomRightCanvasCoordinates[0] < 0 ||
|
||||
bottomRightCanvasCoordinates[1] < 0 ||
|
||||
topLeftCanvasCoordinates[0] > runtimeGame.getGameResolutionWidth() ||
|
||||
topLeftCanvasCoordinates[1] > runtimeGame.getGameResolutionHeight();
|
||||
canvasRight < 0 ||
|
||||
canvasBottom < 0 ||
|
||||
canvasLeft > runtimeGame.getGameResolutionWidth() ||
|
||||
canvasTop > runtimeGame.getGameResolutionHeight();
|
||||
if (isOutsideCanvas) {
|
||||
this._input.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Position the input on the container on top of the canvas.
|
||||
workingPoint[0] = canvasLeft;
|
||||
workingPoint[1] = canvasTop;
|
||||
const topLeftPageCoordinates = runtimeGameRenderer.convertCanvasToDomElementContainerCoords(
|
||||
topLeftCanvasCoordinates
|
||||
workingPoint
|
||||
);
|
||||
const pageLeft = topLeftPageCoordinates[0];
|
||||
const pageTop = topLeftPageCoordinates[1];
|
||||
|
||||
workingPoint[0] = canvasRight;
|
||||
workingPoint[1] = canvasBottom;
|
||||
const bottomRightPageCoordinates = runtimeGameRenderer.convertCanvasToDomElementContainerCoords(
|
||||
bottomRightCanvasCoordinates
|
||||
workingPoint
|
||||
);
|
||||
const pageRight = bottomRightPageCoordinates[0];
|
||||
const pageBottom = bottomRightPageCoordinates[1];
|
||||
|
||||
const widthInContainer =
|
||||
bottomRightPageCoordinates[0] - topLeftPageCoordinates[0];
|
||||
const heightInContainer =
|
||||
bottomRightPageCoordinates[1] - topLeftPageCoordinates[1];
|
||||
const widthInContainer = pageRight - pageLeft;
|
||||
const heightInContainer = pageBottom - pageTop;
|
||||
|
||||
this._input.style.left = topLeftPageCoordinates[0] + 'px';
|
||||
this._input.style.top = topLeftPageCoordinates[1] + 'px';
|
||||
this._input.style.left = pageLeft + 'px';
|
||||
this._input.style.top = pageTop + 'px';
|
||||
this._input.style.width = widthInContainer + 'px';
|
||||
this._input.style.height = heightInContainer + 'px';
|
||||
this._input.style.transform =
|
||||
@@ -195,7 +216,7 @@ namespace gdjs {
|
||||
|
||||
updateFont() {
|
||||
if (!this._input) return;
|
||||
this._input.style.fontFamily = this._runtimeScene
|
||||
this._input.style.fontFamily = this._instanceContainer
|
||||
.getGame()
|
||||
.getFontManager()
|
||||
.getFontFamily(this._object.getFontResourceName());
|
||||
|
@@ -71,10 +71,10 @@ namespace gdjs {
|
||||
_renderer: TextInputRuntimeObjectRenderer;
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
objectData: TextInputObjectData
|
||||
) {
|
||||
super(runtimeScene, objectData);
|
||||
super(instanceContainer, objectData);
|
||||
|
||||
this._string = objectData.content.initialValue;
|
||||
this._placeholder = objectData.content.placeholder;
|
||||
@@ -92,7 +92,10 @@ namespace gdjs {
|
||||
this._disabled = objectData.content.disabled;
|
||||
this._readOnly = objectData.content.readOnly;
|
||||
|
||||
this._renderer = new gdjs.TextInputRuntimeObjectRenderer(this);
|
||||
this._renderer = new gdjs.TextInputRuntimeObjectRenderer(
|
||||
this,
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
@@ -167,7 +170,7 @@ namespace gdjs {
|
||||
return true;
|
||||
}
|
||||
|
||||
updatePreRender(runtimeScene: RuntimeScene): void {
|
||||
updatePreRender(instanceContainer: RuntimeInstanceContainer): void {
|
||||
this._renderer.updatePreRender();
|
||||
}
|
||||
|
||||
@@ -196,8 +199,8 @@ namespace gdjs {
|
||||
this._renderer.onSceneResumed();
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene: gdjs.RuntimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
this._renderer.onDestroy();
|
||||
}
|
||||
|
||||
|
@@ -152,8 +152,8 @@ void DeclareTextObjectExtension(gd::PlatformExtension& extension) {
|
||||
obj.AddAction("SetGradient",
|
||||
_("Gradient"),
|
||||
_("Change the gradient of the text."),
|
||||
_("Change gradient of _PARAM0_ to colors _PARAM1_ _PARAM2_ "
|
||||
"_PARAM3_ _PARAM4_ type _PARAM5_"),
|
||||
_("Change gradient of _PARAM0_ to colors _PARAM2_ "
|
||||
"_PARAM3_ _PARAM4_ _PARAM5_, type _PARAM1_"),
|
||||
_("Effects"),
|
||||
"res/actions/textGradient24.png",
|
||||
"res/actions/textGradient.png")
|
||||
|
@@ -9,14 +9,14 @@ namespace gdjs {
|
||||
|
||||
constructor(
|
||||
runtimeObject: gdjs.TextRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
this._fontManager = runtimeScene.getGame().getFontManager();
|
||||
this._fontManager = instanceContainer.getGame().getFontManager();
|
||||
this._text = new PIXI.Text(' ', { align: 'left' });
|
||||
this._text.anchor.x = 0.5;
|
||||
this._text.anchor.y = 0.5;
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._text, runtimeObject.getZOrder());
|
||||
|
@@ -63,14 +63,14 @@ namespace gdjs {
|
||||
_scaleY: number = 1;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param textObjectData The initial properties of the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
textObjectData: TextObjectData
|
||||
) {
|
||||
super(runtimeScene, textObjectData);
|
||||
super(instanceContainer, textObjectData);
|
||||
this._characterSize = Math.max(1, textObjectData.characterSize);
|
||||
this._fontName = textObjectData.font;
|
||||
this._bold = textObjectData.bold;
|
||||
@@ -82,7 +82,10 @@ namespace gdjs {
|
||||
textObjectData.color.b,
|
||||
];
|
||||
this._str = textObjectData.string;
|
||||
this._renderer = new gdjs.TextRuntimeObjectRenderer(this, runtimeScene);
|
||||
this._renderer = new gdjs.TextRuntimeObjectRenderer(
|
||||
this,
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
@@ -131,7 +134,7 @@ namespace gdjs {
|
||||
return this._renderer.getRendererObject();
|
||||
}
|
||||
|
||||
update(runtimeScene: gdjs.RuntimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._renderer.ensureUpToDate();
|
||||
}
|
||||
|
||||
@@ -151,7 +154,7 @@ namespace gdjs {
|
||||
* Update the rendered object position.
|
||||
*/
|
||||
private _updateTextPosition() {
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
this._renderer.updatePosition();
|
||||
}
|
||||
|
||||
@@ -326,7 +329,7 @@ namespace gdjs {
|
||||
this._scaleX = newScale;
|
||||
this._scaleY = newScale;
|
||||
this._renderer.setScale(newScale);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -338,7 +341,7 @@ namespace gdjs {
|
||||
|
||||
this._scaleX = newScale;
|
||||
this._renderer.setScaleX(newScale);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -350,7 +353,7 @@ namespace gdjs {
|
||||
|
||||
this._scaleY = newScale;
|
||||
this._renderer.setScaleY(newScale);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -410,7 +413,7 @@ namespace gdjs {
|
||||
|
||||
this._wrapping = enable;
|
||||
this._renderer.updateStyle();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -432,7 +435,7 @@ namespace gdjs {
|
||||
|
||||
this._wrappingWidth = width;
|
||||
this._renderer.updateStyle();
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -1,6 +1,6 @@
|
||||
/// <reference path="helper/TileMapHelper.d.ts" />
|
||||
namespace gdjs {
|
||||
export interface RuntimeScene {
|
||||
export interface RuntimeInstanceContainer {
|
||||
tileMapCollisionMaskManager: gdjs.TileMap.TileMapRuntimeManager;
|
||||
}
|
||||
export namespace TileMap {
|
||||
@@ -26,7 +26,7 @@ namespace gdjs {
|
||||
* @see {@link TileMapManager}
|
||||
*/
|
||||
export class TileMapRuntimeManager {
|
||||
private _runtimeScene: gdjs.RuntimeScene;
|
||||
private _instanceContainer: gdjs.RuntimeInstanceContainer;
|
||||
/**
|
||||
* Delegate that actually manage the caches without anything specific to
|
||||
* GDJS.
|
||||
@@ -34,27 +34,27 @@ namespace gdjs {
|
||||
*/
|
||||
private _manager: TileMapHelper.TileMapManager;
|
||||
/**
|
||||
* @param runtimeScene The scene.
|
||||
* @param instanceContainer The instance container.
|
||||
*/
|
||||
private constructor(runtimeScene: gdjs.RuntimeScene) {
|
||||
this._runtimeScene = runtimeScene;
|
||||
private constructor(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
this._instanceContainer = instanceContainer;
|
||||
this._manager = new TileMapHelper.TileMapManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param runtimeScene Where to set the manager instance.
|
||||
* @param instanceContainer Where to set the manager instance.
|
||||
* @returns The shared manager.
|
||||
*/
|
||||
static getManager(
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): TileMapRuntimeManager {
|
||||
if (!runtimeScene.tileMapCollisionMaskManager) {
|
||||
if (!instanceContainer.tileMapCollisionMaskManager) {
|
||||
// Create the shared manager if necessary.
|
||||
runtimeScene.tileMapCollisionMaskManager = new TileMapRuntimeManager(
|
||||
runtimeScene
|
||||
instanceContainer.tileMapCollisionMaskManager = new TileMapRuntimeManager(
|
||||
instanceContainer
|
||||
);
|
||||
}
|
||||
return runtimeScene.tileMapCollisionMaskManager;
|
||||
return instanceContainer.tileMapCollisionMaskManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +109,7 @@ namespace gdjs {
|
||||
tileSetJsonResourceName: string,
|
||||
callback: (tiledMap: TileMapHelper.TiledMap | null) => void
|
||||
): void {
|
||||
this._runtimeScene
|
||||
this._instanceContainer
|
||||
.getGame()
|
||||
.getJsonManager()
|
||||
.loadJson(tileMapJsonResourceName, (error, tileMapJsonData) => {
|
||||
@@ -123,7 +123,7 @@ namespace gdjs {
|
||||
}
|
||||
const tiledMap = tileMapJsonData as TileMapHelper.TiledMap;
|
||||
if (tileSetJsonResourceName) {
|
||||
this._runtimeScene
|
||||
this._instanceContainer
|
||||
.getGame()
|
||||
.getJsonManager()
|
||||
.loadJson(tileSetJsonResourceName, (error, tileSetJsonData) => {
|
||||
|
@@ -12,11 +12,11 @@ namespace gdjs {
|
||||
|
||||
constructor(
|
||||
runtimeObject: gdjs.TileMapCollisionMaskRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
this._graphics = new PIXI.Graphics();
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._graphics, runtimeObject.getZOrder());
|
||||
|
@@ -121,10 +121,10 @@ describe('gdjs.TileMapCollisionMaskRuntimeObject', function () {
|
||||
// TODO find a clean way to wait for the json to be read.
|
||||
for (
|
||||
let index = 0;
|
||||
index < 100 && tileMap._collisionTileMap.getDimensionX() === 0;
|
||||
index < 200 && tileMap._collisionTileMap.getDimensionX() === 0;
|
||||
index++
|
||||
) {
|
||||
await delay(20);
|
||||
await delay(25);
|
||||
}
|
||||
if (tileMap._collisionTileMap.getDimensionX() === 0) {
|
||||
throw new Error('Timeout reading the tile map JSON file.');
|
||||
|
@@ -42,8 +42,8 @@ namespace gdjs {
|
||||
*/
|
||||
private _transformationIsUpToDate: boolean = false;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene, objectData) {
|
||||
super(runtimeScene, objectData);
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer, objectData) {
|
||||
super(instanceContainer, objectData);
|
||||
this._tilemapJsonFile = objectData.content.tilemapJsonFile;
|
||||
this._tilesetJsonFile = objectData.content.tilesetJsonFile;
|
||||
this._collisionMaskTag = objectData.content.collisionMaskTag;
|
||||
@@ -58,7 +58,7 @@ namespace gdjs {
|
||||
this._outlineOpacity = objectData.content.outlineOpacity;
|
||||
this._outlineSize = objectData.content.outlineSize;
|
||||
this._tileMapManager = gdjs.TileMap.TileMapRuntimeManager.getManager(
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// The actual size is set when the tile map file is loaded.
|
||||
@@ -80,7 +80,7 @@ namespace gdjs {
|
||||
|
||||
this._renderer = new gdjs.TileMap.TileMapCollisionMaskRenderer(
|
||||
this,
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
this._updateTileMap();
|
||||
|
||||
@@ -88,8 +88,8 @@ namespace gdjs {
|
||||
this.onCreated();
|
||||
}
|
||||
|
||||
updatePreRender(runtimeScene: gdjs.RuntimeScene) {
|
||||
super.updatePreRender(runtimeScene);
|
||||
updatePreRender(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
super.updatePreRender(instanceContainer);
|
||||
|
||||
if (this._debugMode && this.hitBoxesDirty) {
|
||||
this.updateHitBoxes();
|
||||
@@ -472,8 +472,8 @@ namespace gdjs {
|
||||
}
|
||||
this._scaleX = width / this._collisionTileMap.getWidth();
|
||||
this._width = width;
|
||||
this.hitBoxesDirty = true;
|
||||
this._transformationIsUpToDate = false;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -487,8 +487,8 @@ namespace gdjs {
|
||||
}
|
||||
this._scaleY = height / this._collisionTileMap.getHeight();
|
||||
this._height = height;
|
||||
this.hitBoxesDirty = true;
|
||||
this._transformationIsUpToDate = false;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -515,8 +515,8 @@ namespace gdjs {
|
||||
}
|
||||
this._scaleX = scaleX;
|
||||
this._width = scaleX * this._collisionTileMap.getWidth();
|
||||
this.hitBoxesDirty = true;
|
||||
this._transformationIsUpToDate = false;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -533,8 +533,8 @@ namespace gdjs {
|
||||
}
|
||||
this._scaleY = scaleY;
|
||||
this._height = scaleY * this._collisionTileMap.getHeight();
|
||||
this.hitBoxesDirty = true;
|
||||
this._transformationIsUpToDate = false;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
getWidth(): float {
|
||||
|
@@ -16,11 +16,11 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* @param runtimeObject The object to render
|
||||
* @param runtimeScene The gdjs.RuntimeScene in which the object is
|
||||
* @param instanceContainer The gdjs.RuntimeScene in which the object is
|
||||
*/
|
||||
constructor(
|
||||
runtimeObject: gdjs.TileMapRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace gdjs {
|
||||
this._pixiObject = new PIXI.tilemap.CompositeTilemap();
|
||||
this._pixiObject.tileAnim = [0, 0];
|
||||
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._pixiObject, runtimeObject.getZOrder());
|
||||
@@ -44,7 +44,7 @@ namespace gdjs {
|
||||
return this._pixiObject;
|
||||
}
|
||||
|
||||
incrementAnimationFrameX(runtimeScene: gdjs.RuntimeScene) {
|
||||
incrementAnimationFrameX(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
this._pixiObject.tileAnim[0] += 1;
|
||||
}
|
||||
|
||||
|
@@ -19,8 +19,8 @@ namespace gdjs {
|
||||
_tileMapManager: gdjs.TileMap.TileMapRuntimeManager;
|
||||
_renderer: gdjs.TileMapRuntimeObjectPixiRenderer;
|
||||
|
||||
constructor(runtimeScene: gdjs.RuntimeScene, objectData) {
|
||||
super(runtimeScene, objectData);
|
||||
constructor(instanceContainer: gdjs.RuntimeInstanceContainer, objectData) {
|
||||
super(instanceContainer, objectData);
|
||||
this._opacity = objectData.content.opacity;
|
||||
this._tilemapJsonFile = objectData.content.tilemapJsonFile;
|
||||
this._tilesetJsonFile = objectData.content.tilesetJsonFile;
|
||||
@@ -30,11 +30,11 @@ namespace gdjs {
|
||||
this._animationSpeedScale = objectData.content.animationSpeedScale;
|
||||
this._animationFps = objectData.content.animationFps;
|
||||
this._tileMapManager = gdjs.TileMap.TileMapRuntimeManager.getManager(
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
this._renderer = new gdjs.TileMapRuntimeObjectRenderer(
|
||||
this,
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
this._updateTileMap();
|
||||
|
||||
@@ -46,14 +46,14 @@ namespace gdjs {
|
||||
return this._renderer.getRendererObject();
|
||||
}
|
||||
|
||||
update(runtimeScene: gdjs.RuntimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
if (this._animationSpeedScale <= 0 || this._animationFps === 0) {
|
||||
return;
|
||||
}
|
||||
const elapsedTime = this.getElapsedTime(runtimeScene) / 1000;
|
||||
const elapsedTime = this.getElapsedTime() / 1000;
|
||||
this._frameElapsedTime += elapsedTime * this._animationSpeedScale;
|
||||
while (this._frameElapsedTime > 1 / this._animationFps) {
|
||||
this._renderer.incrementAnimationFrameX(runtimeScene);
|
||||
this._renderer.incrementAnimationFrameX(instanceContainer);
|
||||
this._frameElapsedTime -= 1 / this._animationFps;
|
||||
}
|
||||
}
|
||||
@@ -124,7 +124,7 @@ namespace gdjs {
|
||||
}
|
||||
this._tileMapManager.getOrLoadTextureCache(
|
||||
(textureName) =>
|
||||
(this._runtimeScene
|
||||
(this.getInstanceContainer()
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXITexture(textureName) as unknown) as PIXI.BaseTexture<
|
||||
@@ -221,7 +221,7 @@ namespace gdjs {
|
||||
if (this.getWidth() === width) return;
|
||||
|
||||
this._renderer.setWidth(width);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -233,7 +233,7 @@ namespace gdjs {
|
||||
if (this.getHeight() === height) return;
|
||||
|
||||
this._renderer.setHeight(height);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -258,7 +258,7 @@ namespace gdjs {
|
||||
if (this.getScaleX() === scaleX) return;
|
||||
|
||||
this._renderer.setScaleX(scaleX);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,7 +273,7 @@ namespace gdjs {
|
||||
if (this.getScaleY() === scaleY) return;
|
||||
|
||||
this._renderer.setScaleY(scaleY);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
setX(x: float): void {
|
||||
|
@@ -7,17 +7,17 @@ namespace gdjs {
|
||||
|
||||
constructor(
|
||||
runtimeObject: gdjs.TiledSpriteRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
textureName: string
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
const texture = runtimeScene
|
||||
const texture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXITexture(textureName);
|
||||
this._tiledSprite = new PIXI.TilingSprite(texture, 1024, 1024);
|
||||
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._tiledSprite, runtimeObject.getZOrder());
|
||||
@@ -42,8 +42,11 @@ namespace gdjs {
|
||||
this._object.y + this._tiledSprite.height / 2;
|
||||
}
|
||||
|
||||
setTexture(textureName, runtimeScene): void {
|
||||
const texture = runtimeScene
|
||||
setTexture(
|
||||
textureName: string,
|
||||
instanceContainer: RuntimeInstanceContainer
|
||||
): void {
|
||||
const texture = instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXITexture(textureName);
|
||||
|
@@ -30,17 +30,17 @@ namespace gdjs {
|
||||
_renderer: gdjs.TiledSpriteRuntimeObjectRenderer;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The container the object belongs to.
|
||||
* @param tiledSpriteObjectData The initial properties of the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
tiledSpriteObjectData: TiledSpriteObjectData
|
||||
) {
|
||||
super(runtimeScene, tiledSpriteObjectData);
|
||||
super(instanceContainer, tiledSpriteObjectData);
|
||||
this._renderer = new gdjs.TiledSpriteRuntimeObjectRenderer(
|
||||
this,
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
tiledSpriteObjectData.texture
|
||||
);
|
||||
this._width = 0;
|
||||
@@ -54,7 +54,7 @@ namespace gdjs {
|
||||
|
||||
updateFromObjectData(oldObjectData, newObjectData): boolean {
|
||||
if (oldObjectData.texture !== newObjectData.texture) {
|
||||
this.setTexture(newObjectData.texture, this._runtimeScene);
|
||||
this.setTexture(newObjectData.texture, this.getRuntimeScene());
|
||||
}
|
||||
if (oldObjectData.width !== newObjectData.width) {
|
||||
this.setWidth(newObjectData.width);
|
||||
@@ -69,8 +69,8 @@ namespace gdjs {
|
||||
return this._renderer.getRendererObject();
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
if ((this._renderer as any).onDestroy) {
|
||||
(this._renderer as any).onDestroy();
|
||||
}
|
||||
@@ -106,11 +106,14 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Assign a new texture to the Tiled Sprite object.
|
||||
* @param textureName The name of the image texture ressource.
|
||||
* @param runtimeScene The scene in which the texture is used.
|
||||
* @param textureName The name of the image texture resource.
|
||||
* @param instanceContainer The container in which the texture is used.
|
||||
*/
|
||||
setTexture(textureName: string, runtimeScene: gdjs.RuntimeScene): void {
|
||||
this._renderer.setTexture(textureName, runtimeScene);
|
||||
setTexture(
|
||||
textureName: string,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): void {
|
||||
this._renderer.setTexture(textureName, instanceContainer);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,7 +150,7 @@ namespace gdjs {
|
||||
|
||||
this._width = width;
|
||||
this._renderer.setWidth(width);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -159,7 +162,7 @@ namespace gdjs {
|
||||
|
||||
this._height = height;
|
||||
this._renderer.setHeight(height);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -48,11 +48,11 @@ namespace gdjs {
|
||||
private _temporaryPointForTransformations: FloatPoint = [0, 0];
|
||||
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._allowDiagonals = behaviorData.allowDiagonals;
|
||||
this._acceleration = behaviorData.acceleration;
|
||||
this._deceleration = behaviorData.deceleration;
|
||||
@@ -227,7 +227,7 @@ namespace gdjs {
|
||||
return this._movementAngleOffset;
|
||||
}
|
||||
|
||||
doStepPreEvents(runtimeScene: gdjs.RuntimeScene) {
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {
|
||||
const LEFTKEY = 37;
|
||||
const UPKEY = 38;
|
||||
const RIGHTKEY = 39;
|
||||
@@ -237,21 +237,21 @@ namespace gdjs {
|
||||
// @ts-ignore
|
||||
this._leftKey |=
|
||||
!this._ignoreDefaultControls &&
|
||||
runtimeScene.getGame().getInputManager().isKeyPressed(LEFTKEY);
|
||||
instanceContainer.getGame().getInputManager().isKeyPressed(LEFTKEY);
|
||||
// @ts-ignore
|
||||
this._rightKey |=
|
||||
!this._ignoreDefaultControls &&
|
||||
runtimeScene.getGame().getInputManager().isKeyPressed(RIGHTKEY);
|
||||
instanceContainer.getGame().getInputManager().isKeyPressed(RIGHTKEY);
|
||||
// @ts-ignore
|
||||
this._downKey |=
|
||||
!this._ignoreDefaultControls &&
|
||||
runtimeScene.getGame().getInputManager().isKeyPressed(DOWNKEY);
|
||||
instanceContainer.getGame().getInputManager().isKeyPressed(DOWNKEY);
|
||||
// @ts-ignore
|
||||
this._upKey |=
|
||||
!this._ignoreDefaultControls &&
|
||||
runtimeScene.getGame().getInputManager().isKeyPressed(UPKEY);
|
||||
instanceContainer.getGame().getInputManager().isKeyPressed(UPKEY);
|
||||
|
||||
const elapsedTime = this.owner.getElapsedTime(runtimeScene);
|
||||
const elapsedTime = this.owner.getElapsedTime();
|
||||
|
||||
if (!this._leftKey) {
|
||||
this._leftKeyPressedDuration = 0;
|
||||
@@ -330,7 +330,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
const object = this.owner;
|
||||
const timeDelta = this.owner.getElapsedTime(runtimeScene) / 1000;
|
||||
const timeDelta = this.owner.getElapsedTime() / 1000;
|
||||
const previousVelocityX = this._xVelocity;
|
||||
const previousVelocityY = this._yVelocity;
|
||||
this._wasStickUsed = false;
|
||||
@@ -443,8 +443,7 @@ namespace gdjs {
|
||||
if (this._rotateObject) {
|
||||
object.rotateTowardAngle(
|
||||
directionInDeg + this._angleOffset,
|
||||
this._angularSpeed,
|
||||
runtimeScene
|
||||
this._angularSpeed
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@@ -75,8 +75,9 @@ module.exports = {
|
||||
)
|
||||
.setCategory('Visual effect')
|
||||
.setExtensionHelpPath('/behaviors/tween');
|
||||
extension.addInstructionOrExpressionGroupMetadata(_("Tweening"))
|
||||
.setIcon("JsPlatform/Extensions/tween_behavior32.png");
|
||||
extension
|
||||
.addInstructionOrExpressionGroupMetadata(_('Tweening'))
|
||||
.setIcon('JsPlatform/Extensions/tween_behavior32.png');
|
||||
|
||||
extension
|
||||
.addExpression(
|
||||
@@ -105,19 +106,20 @@ module.exports = {
|
||||
"Tweens a scene variable's numeric value from one number to another."
|
||||
),
|
||||
_(
|
||||
'Tween variable _PARAM2_ from _PARAM3_ to _PARAM4_ for _PARAM5_ms with easing _PARAM6_ as _PARAM1_'
|
||||
'Tween variable _PARAM2_ from _PARAM3_ to _PARAM4_ over _PARAM5_ms with easing _PARAM6_ as _PARAM1_'
|
||||
),
|
||||
_('Scene Tweens'),
|
||||
'JsPlatform/Extensions/tween_behavior24.png',
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.addParameter('scenevar', _('The variable to tween'), '', false)
|
||||
.addParameter('expression', _('Initial value'), '', false)
|
||||
.addParameter('expression', _('Final value'), '', false)
|
||||
.addParameter('expression', _('Duration'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setHidden()
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -126,18 +128,44 @@ module.exports = {
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'TweenCameraPosition',
|
||||
_('Tween the camera position'),
|
||||
_('Tweens the camera position from the current one to a new one.'),
|
||||
'TweenSceneVariableNumber2',
|
||||
_('Tween a number in a scene variable'),
|
||||
_(
|
||||
'Tween camera on layer _PARAM4_ to _PARAM2_;_PARAM3_ for _PARAM5_ms with easing _PARAM6_ as _PARAM1_'
|
||||
"Tweens a scene variable's numeric value from its current value to a new one."
|
||||
),
|
||||
_(
|
||||
'Tween variable _PARAM2_ to _PARAM3_ over _PARAM4_ms with easing _PARAM5_ as _PARAM1_'
|
||||
),
|
||||
_('Scene Tweens'),
|
||||
'JsPlatform/Extensions/tween_behavior24.png',
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.addParameter('scenevar', _('The variable to tween'), '', false)
|
||||
.addParameter('expression', _('Final value'), '', false)
|
||||
.addParameter('expression', _('Duration'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/tweentools.js')
|
||||
.setFunctionName('gdjs.evtTools.tween.tweenVariableNumber2');
|
||||
|
||||
extension
|
||||
.addAction(
|
||||
'TweenCameraPosition',
|
||||
_('Tween the camera position'),
|
||||
_('Tweens the camera position from the current one to a new one.'),
|
||||
_(
|
||||
'Tween camera on layer _PARAM4_ to _PARAM2_;_PARAM3_ over _PARAM5_ms with easing _PARAM6_ as _PARAM1_'
|
||||
),
|
||||
_('Scene Tweens'),
|
||||
'JsPlatform/Extensions/tween_behavior24.png',
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.addParameter('expression', _('Target X position'), '', false)
|
||||
.addParameter('expression', _('Target Y position'), '', false)
|
||||
.addParameter('layer', _('Layer'), '', true)
|
||||
@@ -155,14 +183,14 @@ module.exports = {
|
||||
_('Tween the camera zoom'),
|
||||
_('Tweens the camera zoom from the current zoom factor to a new one.'),
|
||||
_(
|
||||
'Tween the zoom of camera on layer _PARAM3_ to _PARAM2_ for _PARAM4_ms with easing _PARAM5_ as _PARAM1_'
|
||||
'Tween the zoom of camera on layer _PARAM3_ to _PARAM2_ over _PARAM4_ms with easing _PARAM5_ as _PARAM1_'
|
||||
),
|
||||
_('Scene Tweens'),
|
||||
'JsPlatform/Extensions/tween_behavior24.png',
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.addParameter('expression', _('Target zoom'), '', false)
|
||||
.addParameter('layer', _('Layer'), '', true)
|
||||
.addParameter('expression', _('Duration'), '', false)
|
||||
@@ -179,14 +207,14 @@ module.exports = {
|
||||
_('Tween the camera rotation'),
|
||||
_('Tweens the camera rotation from the current angle to a new one.'),
|
||||
_(
|
||||
'Tween the rotation of camera on layer _PARAM3_ to _PARAM2_ for _PARAM4_ms with easing _PARAM5_ as _PARAM1_'
|
||||
'Tween the rotation of camera on layer _PARAM3_ to _PARAM2_ over _PARAM4_ms with easing _PARAM5_ as _PARAM1_'
|
||||
),
|
||||
_('Scene Tweens'),
|
||||
'JsPlatform/Extensions/tween_behavior24.png',
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.addParameter('expression', _('Target rotation'), '', false)
|
||||
.addParameter('layer', _('Layer'), '', true)
|
||||
.addParameter('expression', _('Duration'), '', false)
|
||||
@@ -208,7 +236,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -226,7 +254,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -244,7 +272,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -262,7 +290,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -280,7 +308,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.addParameter('yesorno', _('Jump to the end'), '', false)
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
@@ -299,7 +327,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -319,7 +347,7 @@ module.exports = {
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addCodeOnlyParameter('currentScene', '')
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'sceneTween')
|
||||
.getCodeExtraInformation()
|
||||
.setIncludeFile('Extensions/TweenBehavior/shifty.js')
|
||||
.addIncludeFile('Extensions/TweenBehavior/shifty_setup.js')
|
||||
@@ -379,7 +407,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('objectvar', _('Object variable'), '', false)
|
||||
.addParameter('expression', _('From value'), '', false)
|
||||
.addParameter('expression', _('To value'), '', false)
|
||||
@@ -393,14 +421,47 @@ module.exports = {
|
||||
false
|
||||
)
|
||||
.setDefaultValue('no')
|
||||
.setHidden()
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('addVariableTween');
|
||||
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectVariableTween2',
|
||||
_('Tween a number in an object variable'),
|
||||
_(
|
||||
"Tweens an object variable's numeric value from its current value to a new one."
|
||||
),
|
||||
_(
|
||||
'Tween the variable _PARAM3_ of _PARAM0_ to _PARAM4_ with easing _PARAM5_ over _PARAM6_ms as _PARAM2_'
|
||||
),
|
||||
_('Variables'),
|
||||
'JsPlatform/Extensions/tween_behavior24.png',
|
||||
'JsPlatform/Extensions/tween_behavior32.png'
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('objectvar', _('Object variable'), '', false)
|
||||
.addParameter('expression', _('To value'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
.addParameter('expression', _('Duration, in milliseconds'), '', false)
|
||||
.addParameter(
|
||||
'yesorno',
|
||||
_('Destroy this object when tween finishes'),
|
||||
'',
|
||||
false
|
||||
)
|
||||
.setDefaultValue('no')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('addVariableTween2');
|
||||
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectPositionTween',
|
||||
_('Add object position tween'),
|
||||
_('Add a tween animation for the object position.'),
|
||||
_('Tween object position'),
|
||||
_('Tweens an object position from its current position to a new one.'),
|
||||
_(
|
||||
'Tween the position of _PARAM0_ to x: _PARAM3_, y: _PARAM4_ with easing _PARAM5_ over _PARAM6_ms as _PARAM2_'
|
||||
),
|
||||
@@ -410,7 +471,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To X'), '', false)
|
||||
.addParameter('expression', _('To Y'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
@@ -429,8 +490,8 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectPositionXTween',
|
||||
_('Add object position X tween'),
|
||||
_('Add a tween animation for the object X position.'),
|
||||
_('Tween object X position'),
|
||||
_('Tweens an object X position from its current X position to a new one.'),
|
||||
_(
|
||||
'Tween the X position of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
),
|
||||
@@ -440,7 +501,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To X'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -458,8 +519,8 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectWidthTween',
|
||||
_('Add object width tween'),
|
||||
_('Add a tween animation for the object width.'),
|
||||
_('Tween object width'),
|
||||
_('Tweens an object width from its current width to a new one.'),
|
||||
_(
|
||||
'Tween the width of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
),
|
||||
@@ -469,7 +530,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To width'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -487,8 +548,8 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectHeightTween',
|
||||
_('Add object height tween'),
|
||||
_('Add a tween animation for the object height.'),
|
||||
_('Tween object height'),
|
||||
_('Tweens an object height from its current height to a new one.'),
|
||||
_(
|
||||
'Tween the height of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
),
|
||||
@@ -498,7 +559,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To height'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -516,8 +577,8 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectPositionYTween',
|
||||
_('Add object position Y tween'),
|
||||
_('Add a tween animation for the object Y position.'),
|
||||
_('Tween object Y position'),
|
||||
_('Tweens an object Y position from its current Y position to a new one.'),
|
||||
_(
|
||||
'Tween the Y position of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
),
|
||||
@@ -527,7 +588,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To Y'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -545,8 +606,8 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectAngleTween',
|
||||
_('Add object angle tween'),
|
||||
_('Add a tween animation for the object angle.'),
|
||||
_('Tween object angle'),
|
||||
_('Tweens an object angle from its current angle to a new one.'),
|
||||
_(
|
||||
'Tween the angle of _PARAM0_ to _PARAM3_° with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
),
|
||||
@@ -556,7 +617,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To angle (in degrees)'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -574,9 +635,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectScaleTween',
|
||||
_('Add object scale tween'),
|
||||
_('Tween object scale'),
|
||||
_(
|
||||
'Add a tween animation for the object scale (Note: the scale can never be less than 0).'
|
||||
'Tweens an object scale from its current scale to a new one (note: the scale can never be less than 0).'
|
||||
),
|
||||
_(
|
||||
'Tween the scale of _PARAM0_ to X-scale: _PARAM3_, Y-scale: _PARAM4_ (from center: _PARAM8_) with easing _PARAM5_ over _PARAM6_ms as _PARAM2_'
|
||||
@@ -587,7 +648,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To scale X'), '', false)
|
||||
.addParameter('expression', _('To scale Y'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
@@ -608,9 +669,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectScaleXTween',
|
||||
_('Add object X-scale tween'),
|
||||
_('Tween object X-scale'),
|
||||
_(
|
||||
'Add a tween animation for the object X-scale (Note: the scale can never be less than 0).'
|
||||
'Tweens an object X-scale from its current value to a new one (note: the scale can never be less than 0).'
|
||||
),
|
||||
_(
|
||||
'Tween the X-scale of _PARAM0_ to _PARAM3_ (from center: _PARAM7_) with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
@@ -621,7 +682,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To scale X'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -641,9 +702,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectScaleYTween',
|
||||
_('Add object Y-scale tween'),
|
||||
_('Tween object Y-scale'),
|
||||
_(
|
||||
'Add a tween animation for the object Y-scale (Note: the scale can never be less than 0).'
|
||||
'Tweens an object Y-scale from its current value to a new one (note: the scale can never be less than 0).'
|
||||
),
|
||||
_(
|
||||
'Tween the Y-scale of _PARAM0_ to _PARAM3_ (from center: _PARAM7_) with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
@@ -654,7 +715,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To scale Y'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -674,9 +735,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddTextObjectCharacterSizeTween',
|
||||
_('Add text size tween'),
|
||||
_('Tween text size'),
|
||||
_(
|
||||
'Add a tween animation for the text object character size (Note: the size can never be less than 1).'
|
||||
'Tweens the text object character size from its current value to a new one (note: the size can never be less than 1).'
|
||||
),
|
||||
_(
|
||||
'Tween the character size of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
@@ -687,7 +748,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Text object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To character size'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -705,9 +766,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectOpacityTween',
|
||||
_('Add object opacity tween'),
|
||||
_('Tween object opacity'),
|
||||
_(
|
||||
'Add a tween animation for the object opacity (Value between 0 and 255).'
|
||||
'Tweens the object opacity from its current value to a new one (note: the value shall stay between 0 and 255).'
|
||||
),
|
||||
_(
|
||||
'Tween the opacity of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
@@ -718,7 +779,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To opacity'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -736,9 +797,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectColorTween',
|
||||
_('Add object color tween'),
|
||||
_('Tween object color'),
|
||||
_(
|
||||
'Add a tween animation for the object color. Format: "128;200;255" with values between 0 and 255 for red, green and blue'
|
||||
'Tweens the object color from its current value to a new one. Format: "128;200;255" with values between 0 and 255 for red, green and blue'
|
||||
),
|
||||
_(
|
||||
'Tween the color of _PARAM0_ to _PARAM3_ with easing _PARAM4_ over _PARAM5_ms as _PARAM2_'
|
||||
@@ -749,7 +810,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('color', _('To color'), '', false)
|
||||
.addParameter('stringWithSelector', _('Easing'), easingChoices, false)
|
||||
.setDefaultValue('linear')
|
||||
@@ -777,9 +838,9 @@ module.exports = {
|
||||
behavior
|
||||
.addAction(
|
||||
'AddObjectColorHSLTween',
|
||||
_('Add object HSL color tween'),
|
||||
_('Tween object HSL color'),
|
||||
_(
|
||||
'Add a tween animation for the object color using Hue/Saturation/Lightness. Hue can be any number, Saturation and Lightness are between 0 and 100. Use -1 for Saturation and Lightness to let them unchanged.'
|
||||
'Tweens the object color using Hue/Saturation/Lightness. Hue can be any number, Saturation and Lightness are between 0 and 100. Use -1 for Saturation and Lightness to let them unchanged.'
|
||||
),
|
||||
_(
|
||||
'Tween the color of _PARAM0_ using HSL to H: _PARAM3_ (_PARAM4_), S: _PARAM5_, L: _PARAM6_ with easing _PARAM7_ over _PARAM8_ms as _PARAM2_'
|
||||
@@ -790,7 +851,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('expression', _('To Hue'), '', false)
|
||||
.addParameter('yesorno', _('Animate Hue'), '', false)
|
||||
.setDefaultValue('yes')
|
||||
@@ -823,7 +884,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('exists');
|
||||
|
||||
@@ -839,7 +900,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('isPlaying');
|
||||
|
||||
@@ -855,7 +916,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('hasFinished');
|
||||
|
||||
@@ -871,7 +932,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('pauseTween');
|
||||
|
||||
@@ -887,7 +948,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.addParameter('yesorno', _('Jump to end'), '', false)
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('stopTween');
|
||||
@@ -904,7 +965,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('resumeTween');
|
||||
|
||||
@@ -920,7 +981,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('removeTween');
|
||||
|
||||
@@ -934,7 +995,7 @@ module.exports = {
|
||||
)
|
||||
.addParameter('object', _('Object'), '', false)
|
||||
.addParameter('behavior', _('Behavior'), 'TweenBehavior', false)
|
||||
.addParameter('string', _('Tween Identifier'), '', false)
|
||||
.addParameter('identifier', _('Tween Identifier'), 'objectTween')
|
||||
.getCodeExtraInformation()
|
||||
.setFunctionName('getProgress');
|
||||
|
||||
|
@@ -76,23 +76,25 @@ namespace gdjs {
|
||||
];
|
||||
}
|
||||
|
||||
// TODO EBO Rewrite this behavior to use standard method to step.
|
||||
// This could also fix layer time scale that seems to be ignored.
|
||||
export class TweenRuntimeBehavior extends gdjs.RuntimeBehavior {
|
||||
private _tweens: Record<string, TweenRuntimeBehavior.TweenInstance> = {};
|
||||
private _runtimeScene: gdjs.RuntimeScene;
|
||||
private _isActive: boolean = true;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The runtime scene the behavior belongs to.
|
||||
* @param instanceContainer The instance container the behavior belongs to.
|
||||
* @param behaviorData The data to initialize the behavior
|
||||
* @param owner The runtime object the behavior belongs to.
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
behaviorData: BehaviorData,
|
||||
owner: gdjs.RuntimeObject
|
||||
) {
|
||||
super(runtimeScene, behaviorData, owner);
|
||||
this._runtimeScene = runtimeScene;
|
||||
super(instanceContainer, behaviorData, owner);
|
||||
this._runtimeScene = instanceContainer.getScene();
|
||||
}
|
||||
|
||||
updateFromBehaviorData(
|
||||
@@ -204,6 +206,13 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Add an object variable tween.
|
||||
* @deprecated Use addVariableTween2 instead.
|
||||
* This function is misleading since one could think that the tween starts
|
||||
* right at the moment this function is called whereas the value of the variable
|
||||
* will change at the next frame only. Moreover, the variable will not start from
|
||||
* the start value exactly since time will have passed at the moment the next
|
||||
* frame is rendered.
|
||||
* See https://github.com/4ian/GDevelop/issues/4270
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param variable The object variable to store the tweened value
|
||||
* @param fromValue Start value
|
||||
@@ -238,7 +247,40 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object position tween.
|
||||
* Tween an object variable.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param variable The object variable to store the tweened value
|
||||
* @param toValue End value
|
||||
* @param easingValue Type of easing
|
||||
* @param durationValue Duration in milliseconds
|
||||
* @param destroyObjectWhenFinished Destroy this object when the tween ends
|
||||
*/
|
||||
addVariableTween2(
|
||||
identifier: string,
|
||||
variable: gdjs.Variable,
|
||||
toValue: float,
|
||||
easingValue: string,
|
||||
durationValue: float,
|
||||
destroyObjectWhenFinished: boolean
|
||||
) {
|
||||
this._addTween(
|
||||
identifier,
|
||||
easingValue,
|
||||
{
|
||||
from: { value: variable.getValue() },
|
||||
to: { value: toValue },
|
||||
duration: durationValue,
|
||||
easing: easingValue,
|
||||
render: (state) => variable.setNumber(state.value),
|
||||
},
|
||||
this._runtimeScene.getTimeManager().getTimeFromStart(),
|
||||
durationValue,
|
||||
destroyObjectWhenFinished
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tween an object position.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toX The target X position
|
||||
* @param toY The target Y position
|
||||
@@ -274,7 +316,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object X position tween.
|
||||
* Tween an object X position.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toX The target X position
|
||||
* @param easingValue Type of easing
|
||||
@@ -305,7 +347,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object Y position tween.
|
||||
* Tween an object Y position.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toY The target Y position
|
||||
* @param easingValue Type of easing
|
||||
@@ -336,7 +378,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object angle tween.
|
||||
* Tween an object angle.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toAngle The target angle
|
||||
* @param easingValue Type of easing
|
||||
@@ -369,7 +411,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object scale tween.
|
||||
* Tween an object scale.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toScaleX The target X-scale
|
||||
* @param toScaleY The target Y-scale
|
||||
@@ -427,7 +469,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object X-scale tween.
|
||||
* Tween an object X-scale.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toScaleX The target X-scale
|
||||
* @param easingValue Type of easing
|
||||
@@ -472,7 +514,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object scale y tween.
|
||||
* Tween an object Y-scale.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toScaleY The target Y-scale
|
||||
* @param easingValue Type of easing
|
||||
@@ -517,7 +559,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object opacity tween.
|
||||
* Tween an object opacity.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toOpacity The target opacity
|
||||
* @param easingValue Type of easing
|
||||
@@ -553,9 +595,9 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object color tween.
|
||||
* Tween an object color.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toColorStr The target color
|
||||
* @param toColorStr The target RGB color (format "128;200;255" with values between 0 and 255 for red, green and blue)
|
||||
* @param easingValue Type of easing
|
||||
* @param durationValue Duration in milliseconds
|
||||
* @param destroyObjectWhenFinished Destroy this object when the tween ends
|
||||
@@ -656,7 +698,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object color HSL tween, with the "to" color given using HSL (H: any number, S and L: 0-100).
|
||||
* Tween an object HSL color, with the "to" color given using HSL (H: any number, S and L: 0-100).
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toHue The target hue, or the same as the from color's hue if blank
|
||||
* @param animateHue, include hue in calculations, as can't set this to -1 as default to ignore
|
||||
@@ -736,7 +778,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a text object character size tween.
|
||||
* Tween a text object character size.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toSize The target character size
|
||||
* @param easingValue Type of easing
|
||||
@@ -772,7 +814,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object width tween.
|
||||
* Tween an object width.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toWidth The target width
|
||||
* @param easingValue Type of easing
|
||||
@@ -805,7 +847,7 @@ namespace gdjs {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object height tween.
|
||||
* Tween an object height.
|
||||
* @param identifier Unique id to identify the tween
|
||||
* @param toHeight The target height
|
||||
* @param easingValue Type of easing
|
||||
|
@@ -137,6 +137,15 @@ namespace gdjs {
|
||||
tween.stop().dispose();
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated Use tweenVariableNumber2 instead.
|
||||
* This function is misleading since one could think that the tween starts
|
||||
* right at the moment this function is called whereas the value of the variable
|
||||
* will change at the next frame only. Moreover, the variable will not start from
|
||||
* the start value exactly since time will have passed at the moment the next
|
||||
* frame is rendered.
|
||||
* See https://github.com/4ian/GDevelop/issues/4270
|
||||
*/
|
||||
export const tweenVariableNumber = (
|
||||
runtimeScene: RuntimeScene,
|
||||
identifier: string,
|
||||
@@ -158,6 +167,26 @@ namespace gdjs {
|
||||
getShiftyScene(runtimeScene).add(tween);
|
||||
};
|
||||
|
||||
export const tweenVariableNumber2 = (
|
||||
runtimeScene: RuntimeScene,
|
||||
identifier: string,
|
||||
variable: Variable,
|
||||
to: number,
|
||||
duration: number,
|
||||
easing: shifty.easingFunction
|
||||
) => {
|
||||
const tween = shifty.tween({
|
||||
from: { value: variable.getValue() },
|
||||
to: { value: to },
|
||||
easing,
|
||||
duration,
|
||||
render: ({ value }) => variable.setNumber(value),
|
||||
});
|
||||
|
||||
getTweensMap(runtimeScene).set(identifier, tween);
|
||||
getShiftyScene(runtimeScene).add(tween);
|
||||
};
|
||||
|
||||
export const tweenCamera = (
|
||||
runtimeScene: RuntimeScene,
|
||||
identifier: string,
|
||||
|
@@ -7,7 +7,7 @@ namespace gdjs {
|
||||
* The PIXI.js renderer for the VideoRuntimeObject.
|
||||
*/
|
||||
export class VideoRuntimeObjectPixiRenderer {
|
||||
_object: any;
|
||||
_object: gdjs.VideoRuntimeObject;
|
||||
|
||||
// Load (or reset) the video
|
||||
_pixiObject: any;
|
||||
@@ -15,15 +15,15 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* @param runtimeObject The object to render
|
||||
* @param runtimeScene The gdjs.RuntimeScene in which the object is
|
||||
* @param instanceContainer The gdjs.RuntimeScene in which the object is
|
||||
*/
|
||||
constructor(
|
||||
runtimeObject: gdjs.VideoRuntimeObject,
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
this._object = runtimeObject;
|
||||
this._pixiObject = new PIXI.Sprite(
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getGame()
|
||||
.getImageManager()
|
||||
.getPIXIVideoTexture(this._object._videoResource)
|
||||
@@ -36,7 +36,7 @@ namespace gdjs {
|
||||
this._pixiObject._texture.baseTexture.resource.source.autoload = true;
|
||||
|
||||
// Will be set to true when video texture is loaded.
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
.getLayer('')
|
||||
.getRenderer()
|
||||
.addRendererObject(this._pixiObject, runtimeObject.getZOrder());
|
||||
|
@@ -37,19 +37,22 @@ namespace gdjs {
|
||||
_playbackSpeed: any;
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene the object belongs to.
|
||||
* @param instanceContainer The scene the object belongs to.
|
||||
* @param videoObjectData The data defining the object
|
||||
*/
|
||||
constructor(
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
videoObjectData: VideoObjectData
|
||||
) {
|
||||
super(runtimeScene, videoObjectData);
|
||||
super(instanceContainer, videoObjectData);
|
||||
this._opacity = videoObjectData.content.opacity;
|
||||
this._loop = videoObjectData.content.loop;
|
||||
this._volume = videoObjectData.content.volume;
|
||||
this._videoResource = videoObjectData.content.videoResource;
|
||||
this._renderer = new gdjs.VideoRuntimeObjectRenderer(this, runtimeScene);
|
||||
this._renderer = new gdjs.VideoRuntimeObjectRenderer(
|
||||
this,
|
||||
instanceContainer
|
||||
);
|
||||
|
||||
// *ALWAYS* call `this.onCreated()` at the very end of your object constructor.
|
||||
this.onCreated();
|
||||
@@ -92,12 +95,12 @@ namespace gdjs {
|
||||
}
|
||||
}
|
||||
|
||||
onDestroyFromScene(runtimeScene): void {
|
||||
super.onDestroyFromScene(runtimeScene);
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
this._renderer.onDestroy();
|
||||
}
|
||||
|
||||
update(runtimeScene): void {
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._renderer.ensureUpToDate();
|
||||
}
|
||||
|
||||
@@ -153,7 +156,7 @@ namespace gdjs {
|
||||
if (this._renderer.getWidth() === width) return;
|
||||
|
||||
this._renderer.setWidth(width);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -164,7 +167,7 @@ namespace gdjs {
|
||||
if (this._renderer.getHeight() === height) return;
|
||||
|
||||
this._renderer.setHeight(height);
|
||||
this.hitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -19,6 +19,7 @@
|
||||
#include "GDCore/IDE/SceneNameMangler.h"
|
||||
#include "GDCore/Project/Behavior.h"
|
||||
#include "GDCore/Project/EventsBasedBehavior.h"
|
||||
#include "GDCore/Project/EventsBasedObject.h"
|
||||
#include "GDCore/Project/EventsFunction.h"
|
||||
#include "GDCore/Project/ExternalEvents.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
@@ -38,6 +39,7 @@ gd::String EventsCodeGenerator::GenerateEventsListCompleteFunctionCode(
|
||||
gd::String functionArgumentsCode,
|
||||
gd::String functionPreEventsCode,
|
||||
const gd::EventsList& events,
|
||||
gd::String functionPostEventsCode,
|
||||
gd::String functionReturnCode) {
|
||||
// Prepare the global context
|
||||
unsigned int maxDepthLevelReached = 0;
|
||||
@@ -80,6 +82,7 @@ gd::String EventsCodeGenerator::GenerateEventsListCompleteFunctionCode(
|
||||
functionPreEventsCode + "\n" +
|
||||
globalObjectListsReset + "\n" +
|
||||
wholeEventsCode + "\n" +
|
||||
functionPostEventsCode + "\n" +
|
||||
functionReturnCode + "\n" +
|
||||
"}\n";
|
||||
// clang-format on
|
||||
@@ -103,6 +106,7 @@ gd::String EventsCodeGenerator::GenerateLayoutCode(
|
||||
"runtimeScene",
|
||||
"runtimeScene.getOnceTriggers().startNewFrame();\n",
|
||||
scene.GetEvents(),
|
||||
"",
|
||||
"return;\n");
|
||||
|
||||
includeFiles.insert(codeGenerator.GetIncludeFiles().begin(),
|
||||
@@ -129,10 +133,11 @@ gd::String EventsCodeGenerator::GenerateEventsFunctionCode(
|
||||
codeGenerator,
|
||||
codeGenerator.GetCodeNamespaceAccessor() + "func",
|
||||
codeGenerator.GenerateEventsFunctionParameterDeclarationsList(
|
||||
eventsFunction.GetParameters(), false),
|
||||
eventsFunction.GetParameters(), 0, true),
|
||||
codeGenerator.GenerateFreeEventsFunctionContext(
|
||||
eventsFunction.GetParameters(), "runtimeScene.getOnceTriggers()"),
|
||||
eventsFunction.GetEvents(),
|
||||
"",
|
||||
codeGenerator.GenerateEventsFunctionReturn(eventsFunction));
|
||||
|
||||
includeFiles.insert(codeGenerator.GetIncludeFiles().begin(),
|
||||
@@ -191,9 +196,83 @@ gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionCode(
|
||||
codeGenerator,
|
||||
fullyQualifiedFunctionName,
|
||||
codeGenerator.GenerateEventsFunctionParameterDeclarationsList(
|
||||
eventsFunction.GetParameters(), true),
|
||||
eventsFunction.GetParameters(), 2, false),
|
||||
fullPreludeCode,
|
||||
eventsFunction.GetEvents(),
|
||||
"",
|
||||
codeGenerator.GenerateEventsFunctionReturn(eventsFunction));
|
||||
|
||||
includeFiles.insert(codeGenerator.GetIncludeFiles().begin(),
|
||||
codeGenerator.GetIncludeFiles().end());
|
||||
return output;
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateObjectEventsFunctionCode(
|
||||
gd::Project& project,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& codeNamespace,
|
||||
const gd::String& fullyQualifiedFunctionName,
|
||||
const gd::String& onceTriggersVariable,
|
||||
const gd::String& preludeCode,
|
||||
const gd::String& endingCode,
|
||||
std::set<gd::String>& includeFiles,
|
||||
bool compilationForRuntime) {
|
||||
gd::ObjectsContainer globalObjectsAndGroups;
|
||||
gd::ObjectsContainer objectsAndGroups;
|
||||
gd::EventsFunctionTools::ObjectEventsFunctionToObjectsContainer(
|
||||
project,
|
||||
eventsBasedObject,
|
||||
eventsFunction,
|
||||
globalObjectsAndGroups,
|
||||
objectsAndGroups);
|
||||
|
||||
EventsCodeGenerator codeGenerator(globalObjectsAndGroups, objectsAndGroups);
|
||||
codeGenerator.SetCodeNamespace(codeNamespace);
|
||||
codeGenerator.SetGenerateCodeForRuntime(compilationForRuntime);
|
||||
|
||||
// Generate the code setting up the context of the function.
|
||||
gd::String fullPreludeCode =
|
||||
preludeCode + "\n" + "var that = this;\n" +
|
||||
// runtimeScene is supposed to be always accessible, read
|
||||
// it from the object
|
||||
"var runtimeScene = this._instanceContainer;\n" +
|
||||
// By convention of Object Events Function, the object is accessible
|
||||
// as a parameter called "Object", and thisObjectList is an array
|
||||
// containing it (for faster access, without having to go through the
|
||||
// hashmap).
|
||||
"var thisObjectList = [this];\n" +
|
||||
"var Object = Hashtable.newFrom({Object: thisObjectList});\n";
|
||||
|
||||
// Add child-objects
|
||||
for (auto &childObject : eventsBasedObject.GetObjects()) {
|
||||
// child-object are never picked because they are not parameters.
|
||||
const auto &childName = ManObjListName(childObject->GetName());
|
||||
fullPreludeCode +=
|
||||
"var this" + childName + "List = [...runtimeScene.getObjects(" +
|
||||
ConvertToStringExplicit(childObject->GetName()) + ")];\n" +
|
||||
"var " + childName + " = Hashtable.newFrom({" +
|
||||
ConvertToStringExplicit(childObject->GetName()) +
|
||||
": this" + childName + "List});\n";
|
||||
}
|
||||
|
||||
fullPreludeCode += codeGenerator.GenerateObjectEventsFunctionContext(
|
||||
eventsBasedObject,
|
||||
eventsFunction.GetParameters(),
|
||||
onceTriggersVariable,
|
||||
// Pass the names of the parameters considered as the current
|
||||
// object and behavior parameters:
|
||||
"Object");
|
||||
|
||||
gd::String output = GenerateEventsListCompleteFunctionCode(
|
||||
codeGenerator,
|
||||
fullyQualifiedFunctionName,
|
||||
codeGenerator.GenerateEventsFunctionParameterDeclarationsList(
|
||||
// TODO EBO use constants for firstParameterIndex
|
||||
eventsFunction.GetParameters(), 1, false),
|
||||
fullPreludeCode,
|
||||
eventsFunction.GetEvents(),
|
||||
endingCode,
|
||||
codeGenerator.GenerateEventsFunctionReturn(eventsFunction));
|
||||
|
||||
includeFiles.insert(codeGenerator.GetIncludeFiles().begin(),
|
||||
@@ -203,11 +282,12 @@ gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionCode(
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateEventsFunctionParameterDeclarationsList(
|
||||
const vector<gd::ParameterMetadata>& parameters,
|
||||
bool isBehaviorEventsFunction) {
|
||||
gd::String declaration = isBehaviorEventsFunction ? "" : "runtimeScene";
|
||||
int firstParameterIndex,
|
||||
bool addsSceneParameter) {
|
||||
gd::String declaration = addsSceneParameter ? "runtimeScene" : "";
|
||||
for (size_t i = 0; i < parameters.size(); ++i) {
|
||||
const auto& parameter = parameters[i];
|
||||
if (isBehaviorEventsFunction && (i == 0 || i == 1)) {
|
||||
if (i < firstParameterIndex) {
|
||||
// By convention, the first two arguments of a behavior events function
|
||||
// are the object and the behavior, which are not passed to the called
|
||||
// function in the generated JS code.
|
||||
@@ -294,6 +374,44 @@ gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionContext(
|
||||
thisBehaviorName);
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateObjectEventsFunctionContext(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const vector<gd::ParameterMetadata>& parameters,
|
||||
const gd::String& onceTriggersVariable,
|
||||
const gd::String& thisObjectName) {
|
||||
// See the comment at the start of the GenerateEventsFunctionContext function
|
||||
|
||||
gd::String objectsGettersMap;
|
||||
gd::String objectArraysMap;
|
||||
gd::String behaviorNamesMap;
|
||||
|
||||
// If we have an object considered as the current object ("this") (usually
|
||||
// called Object in behavior events function), generate a slightly more
|
||||
// optimized getter for it (bypassing "Object" hashmap, and directly return
|
||||
// the array containing it).
|
||||
if (!thisObjectName.empty()) {
|
||||
objectsGettersMap +=
|
||||
ConvertToStringExplicit(thisObjectName) + ": " + thisObjectName + "\n";
|
||||
objectArraysMap +=
|
||||
ConvertToStringExplicit(thisObjectName) + ": thisObjectList\n";
|
||||
|
||||
// Add child-objects
|
||||
for (auto &childObject : eventsBasedObject.GetObjects()) {
|
||||
const auto &childName = ManObjListName(childObject->GetName());
|
||||
// child-object are never picked because they are not parameters.
|
||||
objectsGettersMap += ", " + ConvertToStringExplicit(childObject->GetName()) + ": " + childName + "\n";
|
||||
objectArraysMap += ", " + ConvertToStringExplicit(childObject->GetName()) + ": this" + childName + "List\n";
|
||||
}
|
||||
}
|
||||
|
||||
return GenerateEventsFunctionContext(parameters,
|
||||
onceTriggersVariable,
|
||||
objectsGettersMap,
|
||||
objectArraysMap,
|
||||
behaviorNamesMap,
|
||||
thisObjectName);
|
||||
}
|
||||
|
||||
gd::String EventsCodeGenerator::GenerateEventsFunctionContext(
|
||||
const vector<gd::ParameterMetadata>& parameters,
|
||||
const gd::String& onceTriggersVariable,
|
||||
@@ -379,7 +497,8 @@ gd::String EventsCodeGenerator::GenerateEventsFunctionContext(
|
||||
// can be different between the parameter name vs the actual behavior
|
||||
// name passed as argument).
|
||||
" getBehaviorName: function(behaviorName) {\n" +
|
||||
" return eventsFunctionContext._behaviorNamesMap[behaviorName];\n"
|
||||
// TODO EBO Handle behavior name collision between parameters and children
|
||||
" return eventsFunctionContext._behaviorNamesMap[behaviorName] || behaviorName;\n"
|
||||
" },\n" +
|
||||
// Creator function that will be used to create new objects. We
|
||||
// need to check if the function was given the context of the calling
|
||||
|
@@ -16,6 +16,7 @@ namespace gd {
|
||||
class ObjectsContainer;
|
||||
class EventsFunction;
|
||||
class EventsBasedBehavior;
|
||||
class EventsBasedObject;
|
||||
class ObjectMetadata;
|
||||
class BehaviorMetadata;
|
||||
class InstructionMetadata;
|
||||
@@ -76,10 +77,13 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
* \param project Project used.
|
||||
* \param eventsFunction The events function to be compiled.
|
||||
* \param codeNamespace Where to store the context used by the function.
|
||||
* \param includeFiles Will be filled with the necessary include files.
|
||||
* \param fullyQualifiedFunctionName The function name with its namespace.
|
||||
* \param onceTriggersVariable The code to access the variable holding
|
||||
* OnceTriggers. \param preludeCode The code to run just before the events
|
||||
* generated code. \param compilationForRuntime Set this to true if the code
|
||||
* OnceTriggers.
|
||||
* \param preludeCode The code to run just before the events
|
||||
* generated code.
|
||||
* \param includeFiles Will be filled with the necessary include files.
|
||||
* \param compilationForRuntime Set this to true if the code
|
||||
* is generated for runtime.
|
||||
*
|
||||
* \return JavaScript code
|
||||
@@ -95,6 +99,39 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
std::set<gd::String>& includeFiles,
|
||||
bool compilationForRuntime = false);
|
||||
|
||||
/**
|
||||
* Generate JavaScript for executing events of a events based object
|
||||
* function.
|
||||
*
|
||||
* \param project Project used.
|
||||
* \param eventsBasedObject The object that contains the function to be compiled.
|
||||
* \param eventsFunction The events function to be compiled.
|
||||
* \param codeNamespace Where to store the context used by the function.
|
||||
* \param fullyQualifiedFunctionName The function name with its namespace.
|
||||
* \param onceTriggersVariable The code to access the variable holding
|
||||
* OnceTriggers.
|
||||
* \param preludeCode The code to run right before the events
|
||||
* generated code.
|
||||
* \param endingCode The code to run right after the events
|
||||
* generated code.
|
||||
* \param includeFiles Will be filled with the necessary include files.
|
||||
* \param compilationForRuntime Set this to true if the code
|
||||
* is generated for runtime.
|
||||
*
|
||||
* \return JavaScript code
|
||||
*/
|
||||
static gd::String GenerateObjectEventsFunctionCode(
|
||||
gd::Project& project,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::EventsFunction& eventsFunction,
|
||||
const gd::String& codeNamespace,
|
||||
const gd::String& fullyQualifiedFunctionName,
|
||||
const gd::String& onceTriggersVariable,
|
||||
const gd::String& preludeCode,
|
||||
const gd::String& endingCode,
|
||||
std::set<gd::String>& includeFiles,
|
||||
bool compilationForRuntime = false);
|
||||
|
||||
/**
|
||||
* \brief Generate code for executing an event list
|
||||
* \note To reduce the stress on JS engines, the code is generated inside
|
||||
@@ -296,6 +333,7 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
gd::String functionArgumentsCode,
|
||||
gd::String functionPreEventsCode,
|
||||
const gd::EventsList& events,
|
||||
gd::String functionPostEventsCode,
|
||||
gd::String functionReturnCode);
|
||||
|
||||
/**
|
||||
@@ -324,7 +362,8 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
*/
|
||||
gd::String GenerateEventsFunctionParameterDeclarationsList(
|
||||
const std::vector<gd::ParameterMetadata>& parameters,
|
||||
bool isBehaviorEventsFunction);
|
||||
int firstParameterIndex,
|
||||
bool addsSceneParameter);
|
||||
|
||||
/**
|
||||
* \brief Generate the "eventsFunctionContext" object that allow a free
|
||||
@@ -347,6 +386,17 @@ class EventsCodeGenerator : public gd::EventsCodeGenerator {
|
||||
const gd::String& thisObjectName,
|
||||
const gd::String& thisBehaviorName);
|
||||
|
||||
/**
|
||||
* \brief Generate the "eventsFunctionContext" object that allow an object
|
||||
* function to provides access objects, object creation and access to
|
||||
* arguments from the rest of the events.
|
||||
*/
|
||||
gd::String GenerateObjectEventsFunctionContext(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const std::vector<gd::ParameterMetadata>& parameters,
|
||||
const gd::String& onceTriggersVariable,
|
||||
const gd::String& thisObjectName);
|
||||
|
||||
gd::String GenerateEventsFunctionReturn(
|
||||
const gd::EventsFunction& eventFunction);
|
||||
|
||||
|
250
GDJS/GDJS/Events/CodeGeneration/ObjectCodeGenerator.cpp
Normal file
250
GDJS/GDJS/Events/CodeGeneration/ObjectCodeGenerator.cpp
Normal file
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* GDevelop JS Platform
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
#include "ObjectCodeGenerator.h"
|
||||
|
||||
#include "EventsCodeGenerator.h"
|
||||
|
||||
namespace gdjs {
|
||||
|
||||
gd::String ObjectCodeGenerator::onCreatedFunctionName =
|
||||
"onCreated";
|
||||
|
||||
gd::String ObjectCodeGenerator::doStepPreEventsFunctionName =
|
||||
"doStepPreEvents";
|
||||
|
||||
gd::String ObjectCodeGenerator::GenerateRuntimeObjectCompleteCode(
|
||||
const gd::String& extensionName,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace,
|
||||
const std::map<gd::String, gd::String>& objectMethodMangledNames,
|
||||
std::set<gd::String>& includeFiles,
|
||||
bool compilationForRuntime) {
|
||||
auto& eventsFunctionsVector =
|
||||
eventsBasedObject.GetEventsFunctions().GetInternalVector();
|
||||
|
||||
return GenerateRuntimeObjectTemplateCode(
|
||||
extensionName,
|
||||
eventsBasedObject,
|
||||
codeNamespace,
|
||||
[&]() {
|
||||
gd::String runtimeObjectDataInitializationCode;
|
||||
for (auto& property :
|
||||
eventsBasedObject.GetPropertyDescriptors().GetInternalVector()) {
|
||||
runtimeObjectDataInitializationCode +=
|
||||
property->IsHidden()
|
||||
? GenerateInitializePropertyFromDefaultValueCode(*property)
|
||||
: GenerateInitializePropertyFromDataCode(*property);
|
||||
}
|
||||
|
||||
return runtimeObjectDataInitializationCode;
|
||||
},
|
||||
[&]() {
|
||||
gd::String runtimeObjectPropertyMethodsCode;
|
||||
for (auto& property :
|
||||
eventsBasedObject.GetPropertyDescriptors().GetInternalVector()) {
|
||||
runtimeObjectPropertyMethodsCode +=
|
||||
GenerateRuntimeObjectPropertyTemplateCode(
|
||||
eventsBasedObject, *property);
|
||||
}
|
||||
|
||||
return runtimeObjectPropertyMethodsCode;
|
||||
},
|
||||
// TODO: Update code generation to be able to generate methods (which would allow
|
||||
// for a cleaner output, not having to add methods to the prototype).
|
||||
[&]() {
|
||||
gd::String runtimeObjectMethodsCode;
|
||||
for (auto& eventsFunction : eventsFunctionsVector) {
|
||||
const gd::String& functionName =
|
||||
objectMethodMangledNames.find(eventsFunction->GetName()) !=
|
||||
objectMethodMangledNames.end()
|
||||
? objectMethodMangledNames.find(eventsFunction->GetName())
|
||||
->second
|
||||
: "UNKNOWN_FUNCTION_fix_objectMethodMangledNames_please";
|
||||
gd::String methodCodeNamespace =
|
||||
codeNamespace + "." + eventsBasedObject.GetName() +
|
||||
".prototype." + functionName + "Context";
|
||||
gd::String methodFullyQualifiedName = codeNamespace + "." +
|
||||
eventsBasedObject.GetName() +
|
||||
".prototype." + functionName;
|
||||
runtimeObjectMethodsCode +=
|
||||
EventsCodeGenerator::GenerateObjectEventsFunctionCode(
|
||||
project,
|
||||
eventsBasedObject,
|
||||
*eventsFunction,
|
||||
methodCodeNamespace,
|
||||
methodFullyQualifiedName,
|
||||
"that._onceTriggers",
|
||||
functionName == doStepPreEventsFunctionName
|
||||
? GenerateDoStepPreEventsPreludeCode()
|
||||
: "",
|
||||
functionName == onCreatedFunctionName
|
||||
? "gdjs.CustomRuntimeObject.prototype.onCreated.call(this);\n"
|
||||
: "",
|
||||
includeFiles,
|
||||
compilationForRuntime);
|
||||
}
|
||||
|
||||
bool hasDoStepPreEventsFunction =
|
||||
eventsBasedObject.GetEventsFunctions().HasEventsFunctionNamed(
|
||||
doStepPreEventsFunctionName);
|
||||
if (!hasDoStepPreEventsFunction) {
|
||||
runtimeObjectMethodsCode +=
|
||||
GenerateDefaultDoStepPreEventsFunctionCode(eventsBasedObject,
|
||||
codeNamespace);
|
||||
}
|
||||
|
||||
return runtimeObjectMethodsCode;
|
||||
},
|
||||
[&]() {
|
||||
gd::String updateFromObjectCode;
|
||||
updateFromObjectCode += "super.updateFromObjectData(oldObjectData, newObjectData);";
|
||||
for (auto& property :
|
||||
eventsBasedObject.GetPropertyDescriptors().GetInternalVector()) {
|
||||
updateFromObjectCode +=
|
||||
GenerateUpdatePropertyFromObjectDataCode(
|
||||
eventsBasedObject, *property);
|
||||
}
|
||||
|
||||
return updateFromObjectCode;
|
||||
});
|
||||
}
|
||||
|
||||
gd::String ObjectCodeGenerator::GenerateRuntimeObjectTemplateCode(
|
||||
const gd::String& extensionName,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace,
|
||||
std::function<gd::String()> generateInitializePropertiesCode,
|
||||
std::function<gd::String()> generatePropertiesCode,
|
||||
std::function<gd::String()> generateMethodsCode,
|
||||
std::function<gd::String()> generateUpdateFromObjectDataCode) {
|
||||
return gd::String(R"jscode_template(
|
||||
CODE_NAMESPACE = CODE_NAMESPACE || {};
|
||||
|
||||
/**
|
||||
* Object generated from OBJECT_FULL_NAME
|
||||
*/
|
||||
CODE_NAMESPACE.RUNTIME_OBJECT_CLASSNAME = class RUNTIME_OBJECT_CLASSNAME extends gdjs.CustomRuntimeObject {
|
||||
constructor(runtimeScene, objectData) {
|
||||
super(runtimeScene, objectData);
|
||||
this._runtimeScene = runtimeScene;
|
||||
|
||||
this._onceTriggers = new gdjs.OnceTriggers();
|
||||
this._behaviorData = {};
|
||||
INITIALIZE_PROPERTIES_CODE
|
||||
}
|
||||
|
||||
// Hot-reload:
|
||||
updateFromObjectData(oldObjectData, newObjectData) {
|
||||
UPDATE_FROM_OBJECT_DATA_CODE
|
||||
|
||||
this.onHotReloading(this.getInstanceContainer());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Properties:
|
||||
PROPERTIES_CODE
|
||||
}
|
||||
|
||||
// Methods:
|
||||
METHODS_CODE
|
||||
|
||||
gdjs.registerObject("EXTENSION_NAME::OBJECT_NAME", CODE_NAMESPACE.RUNTIME_OBJECT_CLASSNAME);
|
||||
)jscode_template")
|
||||
.FindAndReplace("EXTENSION_NAME", extensionName)
|
||||
.FindAndReplace("OBJECT_NAME", eventsBasedObject.GetName())
|
||||
.FindAndReplace("OBJECT_FULL_NAME", eventsBasedObject.GetFullName())
|
||||
.FindAndReplace("RUNTIME_OBJECT_CLASSNAME",
|
||||
eventsBasedObject.GetName())
|
||||
.FindAndReplace("CODE_NAMESPACE", codeNamespace)
|
||||
.FindAndReplace("INITIALIZE_PROPERTIES_CODE",
|
||||
generateInitializePropertiesCode())
|
||||
.FindAndReplace("UPDATE_FROM_OBJECT_DATA_CODE", generateUpdateFromObjectDataCode())
|
||||
.FindAndReplace("PROPERTIES_CODE", generatePropertiesCode())
|
||||
.FindAndReplace("METHODS_CODE", generateMethodsCode());
|
||||
;
|
||||
}
|
||||
// TODO these 2 methods are probably not needed if the properties are merged by GDJS.
|
||||
gd::String ObjectCodeGenerator::GenerateInitializePropertyFromDataCode(
|
||||
const gd::NamedPropertyDescriptor& property) {
|
||||
return gd::String(R"jscode_template(
|
||||
this._objectData.content.PROPERTY_NAME = objectData.content.PROPERTY_NAME !== undefined ? objectData.content.PROPERTY_NAME : DEFAULT_VALUE;)jscode_template")
|
||||
.FindAndReplace("PROPERTY_NAME", property.GetName())
|
||||
.FindAndReplace("DEFAULT_VALUE", GeneratePropertyValueCode(property));
|
||||
}
|
||||
gd::String
|
||||
ObjectCodeGenerator::GenerateInitializePropertyFromDefaultValueCode(
|
||||
const gd::NamedPropertyDescriptor& property) {
|
||||
return gd::String(R"jscode_template(
|
||||
this._objectData.content.PROPERTY_NAME = DEFAULT_VALUE;)jscode_template")
|
||||
.FindAndReplace("PROPERTY_NAME", property.GetName())
|
||||
.FindAndReplace("DEFAULT_VALUE", GeneratePropertyValueCode(property));
|
||||
}
|
||||
|
||||
gd::String ObjectCodeGenerator::GenerateRuntimeObjectPropertyTemplateCode(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::NamedPropertyDescriptor& property) {
|
||||
return gd::String(R"jscode_template(
|
||||
GETTER_NAME() {
|
||||
return this._objectData.content.PROPERTY_NAME !== undefined ? this._objectData.content.PROPERTY_NAME : DEFAULT_VALUE;
|
||||
}
|
||||
SETTER_NAME(newValue) {
|
||||
this._objectData.content.PROPERTY_NAME = newValue;
|
||||
})jscode_template")
|
||||
.FindAndReplace("PROPERTY_NAME", property.GetName())
|
||||
.FindAndReplace("GETTER_NAME",
|
||||
GetObjectPropertyGetterName(property.GetName()))
|
||||
.FindAndReplace("SETTER_NAME",
|
||||
GetObjectPropertySetterName(property.GetName()))
|
||||
.FindAndReplace("DEFAULT_VALUE", GeneratePropertyValueCode(property))
|
||||
.FindAndReplace("RUNTIME_OBJECT_CLASSNAME",
|
||||
eventsBasedObject.GetName());
|
||||
}
|
||||
|
||||
gd::String ObjectCodeGenerator::GenerateUpdatePropertyFromObjectDataCode(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::NamedPropertyDescriptor& property) {
|
||||
return gd::String(R"jscode_template(
|
||||
if (oldObjectData.content.PROPERTY_NAME !== newObjectData.content.PROPERTY_NAME)
|
||||
this._objectData.content.PROPERTY_NAME = newObjectData.content.PROPERTY_NAME;)jscode_template")
|
||||
.FindAndReplace("PROPERTY_NAME", property.GetName());
|
||||
}
|
||||
|
||||
gd::String ObjectCodeGenerator::GeneratePropertyValueCode(
|
||||
const gd::PropertyDescriptor& property) {
|
||||
if (property.GetType() == "String" ||
|
||||
property.GetType() == "Choice" ||
|
||||
property.GetType() == "Color") {
|
||||
return EventsCodeGenerator::ConvertToStringExplicit(property.GetValue());
|
||||
} else if (property.GetType() == "Number") {
|
||||
return "Number(" +
|
||||
EventsCodeGenerator::ConvertToStringExplicit(property.GetValue()) +
|
||||
") || 0";
|
||||
} else if (property.GetType() == "Boolean") { // TODO: Check if working
|
||||
return property.GetValue() == "true" ? "true" : "false";
|
||||
}
|
||||
|
||||
return "0 /* Error: property was of an unrecognized type */";
|
||||
}
|
||||
|
||||
gd::String ObjectCodeGenerator::GenerateDefaultDoStepPreEventsFunctionCode(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace) {
|
||||
return gd::String(R"jscode_template(
|
||||
CODE_NAMESPACE.RUNTIME_OBJECT_CLASSNAME.prototype.doStepPreEvents = function() {
|
||||
PRELUDE_CODE
|
||||
};
|
||||
)jscode_template")
|
||||
.FindAndReplace("RUNTIME_OBJECT_CLASSNAME",
|
||||
eventsBasedObject.GetName())
|
||||
.FindAndReplace("CODE_NAMESPACE", codeNamespace)
|
||||
.FindAndReplace("PRELUDE_CODE", GenerateDoStepPreEventsPreludeCode());
|
||||
}
|
||||
|
||||
gd::String ObjectCodeGenerator::GenerateDoStepPreEventsPreludeCode() {
|
||||
return "this._onceTriggers.startNewFrame();";
|
||||
}
|
||||
|
||||
} // namespace gdjs
|
95
GDJS/GDJS/Events/CodeGeneration/ObjectCodeGenerator.h
Normal file
95
GDJS/GDJS/Events/CodeGeneration/ObjectCodeGenerator.h
Normal file
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* GDevelop JS Platform
|
||||
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
|
||||
* reserved. This project is released under the MIT License.
|
||||
*/
|
||||
#ifndef GDJS_OBJECTCODEGENERATOR_H
|
||||
#define GDJS_OBJECTCODEGENERATOR_H
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "GDCore/Project/EventsBasedObject.h"
|
||||
namespace gd {
|
||||
class NamedPropertyDescriptor;
|
||||
}
|
||||
|
||||
namespace gdjs {
|
||||
|
||||
/**
|
||||
* \brief The class being responsible for generating JavaScript code for
|
||||
* EventsBasedObject.
|
||||
*
|
||||
* See also gd::EventsCodeGenerator.
|
||||
*/
|
||||
class ObjectCodeGenerator {
|
||||
public:
|
||||
ObjectCodeGenerator(gd::Project& project_) : project(project_){};
|
||||
|
||||
/**
|
||||
* \brief Generate the complete JS class (`gdjs.CustomRuntimeObject`) for the
|
||||
* object.
|
||||
*/
|
||||
gd::String GenerateRuntimeObjectCompleteCode(
|
||||
const gd::String& extensionName,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace,
|
||||
const std::map<gd::String, gd::String>& objectMethodMangledNames,
|
||||
std::set<gd::String>& includeFiles,
|
||||
bool compilationForRuntime = false);
|
||||
|
||||
/**
|
||||
* \brief Generate the name of the method to get the value of the property
|
||||
* of a object.
|
||||
*/
|
||||
static gd::String GetObjectPropertyGetterName(
|
||||
const gd::String& propertyName) {
|
||||
return "_get" + propertyName;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief Generate the name of the method to set the value of the property
|
||||
* of a object.
|
||||
*/
|
||||
static gd::String GetObjectPropertySetterName(
|
||||
const gd::String& propertyName) {
|
||||
return "_set" + propertyName;
|
||||
}
|
||||
|
||||
private:
|
||||
gd::String GenerateRuntimeObjectTemplateCode(
|
||||
const gd::String& extensionName,
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace,
|
||||
std::function<gd::String()> generateInitializePropertiesCode,
|
||||
std::function<gd::String()> generateMethodsCode,
|
||||
std::function<gd::String()> generatePropertiesCode,
|
||||
std::function<gd::String()> generateUpdateFromObjectDataCode);
|
||||
gd::String GenerateRuntimeObjectPropertyTemplateCode(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::NamedPropertyDescriptor& property);
|
||||
gd::String GenerateInitializePropertyFromDataCode(
|
||||
const gd::NamedPropertyDescriptor& property);
|
||||
gd::String GenerateInitializePropertyFromDefaultValueCode(
|
||||
const gd::NamedPropertyDescriptor& property);
|
||||
gd::String GeneratePropertyValueCode(const gd::PropertyDescriptor& property);
|
||||
gd::String GenerateUpdatePropertyFromObjectDataCode(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::NamedPropertyDescriptor& property);
|
||||
gd::String GenerateObjectOnDestroyToDeprecatedOnOwnerRemovedFromScene(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace);
|
||||
gd::String GenerateDefaultDoStepPreEventsFunctionCode(
|
||||
const gd::EventsBasedObject& eventsBasedObject,
|
||||
const gd::String& codeNamespace);
|
||||
gd::String GenerateDoStepPreEventsPreludeCode();
|
||||
|
||||
gd::Project& project;
|
||||
|
||||
static gd::String onCreatedFunctionName;
|
||||
static gd::String doStepPreEventsFunctionName;
|
||||
};
|
||||
|
||||
} // namespace gdjs
|
||||
#endif // GDJS_OBJECTCODEGENERATOR_H
|
@@ -128,10 +128,6 @@ CameraExtension::CameraExtension() {
|
||||
GetAllExpressions()["LayerTimeScale"].SetFunctionName(
|
||||
"gdjs.evtTools.camera.getLayerTimeScale");
|
||||
|
||||
GetAllConditions()["LayerHighestZOrder"].SetFunctionName(
|
||||
"gdjs.evtTools.layer.getLayerHighestZOrder");
|
||||
GetAllExpressions()["LayerHighestZOrder"].SetFunctionName(
|
||||
"gdjs.evtTools.layer.getLayerHighestZOrder");
|
||||
GetAllConditions()["LayerDefaultZOrder"].SetFunctionName(
|
||||
"gdjs.evtTools.camera.getLayerDefaultZOrder");
|
||||
GetAllActions()["SetLayerDefaultZOrder"].SetFunctionName(
|
||||
|
@@ -31,6 +31,8 @@
|
||||
#include "GDCore/Project/ExternalLayout.h"
|
||||
#include "GDCore/Project/Layout.h"
|
||||
#include "GDCore/Project/Project.h"
|
||||
#include "GDCore/Project/EventsBasedObject.h"
|
||||
#include "GDCore/Project/EventsFunctionsExtension.h"
|
||||
#include "GDCore/Project/PropertyDescriptor.h"
|
||||
#include "GDCore/Project/SourceFile.h"
|
||||
#include "GDCore/Serialization/Serializer.h"
|
||||
@@ -560,10 +562,12 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
InsertUnique(includesFiles, "polygon.js");
|
||||
InsertUnique(includesFiles, "runtimeobject.js");
|
||||
InsertUnique(includesFiles, "profiler.js");
|
||||
InsertUnique(includesFiles, "RuntimeInstanceContainer.js");
|
||||
InsertUnique(includesFiles, "runtimescene.js");
|
||||
InsertUnique(includesFiles, "scenestack.js");
|
||||
InsertUnique(includesFiles, "force.js");
|
||||
InsertUnique(includesFiles, "layer.js");
|
||||
InsertUnique(includesFiles, "RuntimeSceneLayer.js");
|
||||
InsertUnique(includesFiles, "timer.js");
|
||||
InsertUnique(includesFiles, "runtimegame.js");
|
||||
InsertUnique(includesFiles, "variable.js");
|
||||
@@ -572,6 +576,8 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
InsertUnique(includesFiles, "runtimebehavior.js");
|
||||
InsertUnique(includesFiles, "spriteruntimeobject.js");
|
||||
InsertUnique(includesFiles, "affinetransformation.js");
|
||||
InsertUnique(includesFiles, "CustomRuntimeObjectInstanceContainer.js");
|
||||
InsertUnique(includesFiles, "CustomRuntimeObject.js");
|
||||
|
||||
// Common includes for events only.
|
||||
InsertUnique(includesFiles, "events-tools/commontools.js");
|
||||
@@ -618,6 +624,10 @@ void ExporterHelper::AddLibsInclude(bool pixiRenderers,
|
||||
InsertUnique(includesFiles, "pixi-renderers/pixi-bitmapfont-manager.js");
|
||||
InsertUnique(includesFiles,
|
||||
"pixi-renderers/spriteruntimeobject-pixi-renderer.js");
|
||||
InsertUnique(includesFiles,
|
||||
"pixi-renderers/CustomObjectPixiRenderer.js");
|
||||
InsertUnique(includesFiles,
|
||||
"pixi-renderers/DebuggerPixiRenderer.js");
|
||||
InsertUnique(includesFiles,
|
||||
"pixi-renderers/loadingscreen-pixi-renderer.js");
|
||||
InsertUnique(includesFiles, "pixi-renderers/pixi-effects-manager.js");
|
||||
@@ -819,11 +829,25 @@ void ExporterHelper::ExportObjectAndBehaviorsIncludes(
|
||||
}
|
||||
};
|
||||
|
||||
// TODO UsedExtensionsFinder should be used instead to find the file to include.
|
||||
// The Exporter class already use it.
|
||||
addObjectsIncludeFiles(project);
|
||||
for (std::size_t i = 0; i < project.GetLayoutsCount(); ++i) {
|
||||
const gd::Layout &layout = project.GetLayout(i);
|
||||
addObjectsIncludeFiles(layout);
|
||||
}
|
||||
|
||||
// Event based objects children
|
||||
for (std::size_t e = 0; e < project.GetEventsFunctionsExtensionsCount(); e++) {
|
||||
auto& eventsFunctionsExtension = project.GetEventsFunctionsExtension(e);
|
||||
for (auto&& eventsBasedObjectUniquePtr :
|
||||
eventsFunctionsExtension.GetEventsBasedObjects()
|
||||
.GetInternalVector()) {
|
||||
auto eventsBasedObject = eventsBasedObjectUniquePtr.get();
|
||||
|
||||
addObjectsIncludeFiles(*eventsBasedObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ExporterHelper::ExportObjectAndBehaviorsRequiredFiles(
|
||||
|
591
GDJS/Runtime/CustomRuntimeObject.ts
Normal file
591
GDJS/Runtime/CustomRuntimeObject.ts
Normal file
@@ -0,0 +1,591 @@
|
||||
/*
|
||||
* GDevelop JS Platform
|
||||
* Copyright 2013-2022 Florian Rival (Florian.Rival@gmail.com). All rights reserved.
|
||||
* This project is released under the MIT License.
|
||||
*/
|
||||
namespace gdjs {
|
||||
export type ObjectConfiguration = {
|
||||
content: any;
|
||||
};
|
||||
|
||||
export type CustomObjectConfiguration = ObjectConfiguration & {
|
||||
childrenContent: { [objectName: string]: ObjectConfiguration & any };
|
||||
};
|
||||
|
||||
/**
|
||||
* An object that contains other object.
|
||||
*
|
||||
* This is the base class for objects generated from EventsBasedObject.
|
||||
*
|
||||
* @see gdjs.CustomRuntimeObjectInstanceContainer
|
||||
*/
|
||||
export class CustomRuntimeObject extends gdjs.RuntimeObject {
|
||||
/** It contains the children of this object. */
|
||||
_instanceContainer: gdjs.CustomRuntimeObjectInstanceContainer;
|
||||
_isUntransformedHitBoxesDirty: boolean = true;
|
||||
/** It contains shallow copies of the children hitboxes */
|
||||
_untransformedHitBoxes: gdjs.Polygon[] = [];
|
||||
/** The dimension of this object is calculated from its children AABBs. */
|
||||
_unrotatedAABB: AABB = { min: [0, 0], max: [0, 0] };
|
||||
_scaleX: number = 1;
|
||||
_scaleY: number = 1;
|
||||
_flippedX: boolean = false;
|
||||
_flippedY: boolean = false;
|
||||
opacity: float = 255;
|
||||
_objectData: ObjectData & CustomObjectConfiguration;
|
||||
|
||||
/**
|
||||
* @param parent The container the object belongs to
|
||||
* @param objectData The object data used to initialize the object
|
||||
*/
|
||||
constructor(
|
||||
parent: gdjs.RuntimeInstanceContainer,
|
||||
objectData: ObjectData & CustomObjectConfiguration
|
||||
) {
|
||||
super(parent, objectData);
|
||||
this._instanceContainer = new gdjs.CustomRuntimeObjectInstanceContainer(
|
||||
parent,
|
||||
this
|
||||
);
|
||||
this._objectData = objectData;
|
||||
|
||||
this._instanceContainer.loadFrom(objectData);
|
||||
this.getRenderer().reinitialize(this, parent);
|
||||
|
||||
// The generated code calls the onCreated super implementation at the end.
|
||||
this.onCreated();
|
||||
}
|
||||
|
||||
reinitialize(objectData: ObjectData & CustomObjectConfiguration) {
|
||||
super.reinitialize(objectData);
|
||||
|
||||
this._instanceContainer.loadFrom(objectData);
|
||||
this.getRenderer().reinitialize(this, this.getParent());
|
||||
|
||||
// The generated code calls the onCreated super implementation at the end.
|
||||
this.onCreated();
|
||||
}
|
||||
|
||||
updateFromObjectData(
|
||||
oldObjectData: ObjectData & CustomObjectConfiguration,
|
||||
newObjectData: ObjectData & CustomObjectConfiguration
|
||||
): boolean {
|
||||
return this._instanceContainer.updateFrom(oldObjectData, newObjectData);
|
||||
}
|
||||
|
||||
extraInitializationFromInitialInstance(initialInstanceData: InstanceData) {
|
||||
if (initialInstanceData.customSize) {
|
||||
this.setWidth(initialInstanceData.width);
|
||||
this.setHeight(initialInstanceData.height);
|
||||
}
|
||||
}
|
||||
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
// Let subclasses do something before the object is destroyed.
|
||||
this.onDestroy(instanceContainer);
|
||||
// Let behaviors do something before the object is destroyed.
|
||||
super.onDestroyFromScene(instanceContainer);
|
||||
// Destroy the children.
|
||||
this._instanceContainer.onDestroyFromScene(instanceContainer);
|
||||
}
|
||||
|
||||
update(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._instanceContainer._updateObjectsPreEvents();
|
||||
|
||||
this.doStepPreEvents(instanceContainer);
|
||||
|
||||
const profiler = this.getRuntimeScene().getProfiler();
|
||||
if (profiler) {
|
||||
profiler.begin(this._objectData.type);
|
||||
}
|
||||
// This is a bit like the "scene" events for custom objects.
|
||||
this.doStepPostEvents(instanceContainer);
|
||||
if (profiler) {
|
||||
profiler.end(this._objectData.type);
|
||||
}
|
||||
|
||||
this._instanceContainer._updateObjectsPostEvents();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called when the preview is being hot-reloaded.
|
||||
*/
|
||||
onHotReloading(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
// This is only to handle trigger once.
|
||||
doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
/**
|
||||
* This method is called each tick after events are done.
|
||||
* @param instanceContainer The instanceContainer owning the object
|
||||
*/
|
||||
doStepPostEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
/**
|
||||
* This method is called when the object is being removed from its parent
|
||||
* container and is about to be destroyed/reused later.
|
||||
*/
|
||||
onDestroy(instanceContainer: gdjs.RuntimeInstanceContainer) {}
|
||||
|
||||
updatePreRender(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
this._instanceContainer._updateObjectsPreRender();
|
||||
this.getRenderer().ensureUpToDate();
|
||||
}
|
||||
|
||||
getRendererObject() {
|
||||
return this.getRenderer().getRendererObject();
|
||||
}
|
||||
|
||||
getRenderer() {
|
||||
return this._instanceContainer.getRenderer();
|
||||
}
|
||||
|
||||
onChildrenLocationChanged() {
|
||||
this._isUntransformedHitBoxesDirty = true;
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().update();
|
||||
}
|
||||
|
||||
updateHitBoxes(): void {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
|
||||
//Update the current hitboxes with the frame custom hit boxes
|
||||
//and apply transformations.
|
||||
for (let i = 0; i < this._untransformedHitBoxes.length; ++i) {
|
||||
if (i >= this.hitBoxes.length) {
|
||||
this.hitBoxes.push(new gdjs.Polygon());
|
||||
}
|
||||
for (
|
||||
let j = 0;
|
||||
j < this._untransformedHitBoxes[i].vertices.length;
|
||||
++j
|
||||
) {
|
||||
if (j >= this.hitBoxes[i].vertices.length) {
|
||||
this.hitBoxes[i].vertices.push([0, 0]);
|
||||
}
|
||||
this.applyObjectTransformation(
|
||||
this._untransformedHitBoxes[i].vertices[j][0],
|
||||
this._untransformedHitBoxes[i].vertices[j][1],
|
||||
this.hitBoxes[i].vertices[j]
|
||||
);
|
||||
}
|
||||
this.hitBoxes[i].vertices.length = this._untransformedHitBoxes[
|
||||
i
|
||||
].vertices.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the hitboxes of the children.
|
||||
*/
|
||||
_updateUntransformedHitBoxes() {
|
||||
this._isUntransformedHitBoxesDirty = false;
|
||||
|
||||
const oldUnscaledCenterX =
|
||||
(this._unrotatedAABB.max[0] + this._unrotatedAABB.min[0]) / 2;
|
||||
const oldUnscaledCenterY =
|
||||
(this._unrotatedAABB.max[1] + this._unrotatedAABB.min[1]) / 2;
|
||||
|
||||
this._untransformedHitBoxes.length = 0;
|
||||
if (this._instanceContainer.getAdhocListOfAllInstances().length === 0) {
|
||||
this._unrotatedAABB.min[0] = 0;
|
||||
this._unrotatedAABB.min[1] = 0;
|
||||
this._unrotatedAABB.max[0] = 0;
|
||||
this._unrotatedAABB.max[1] = 0;
|
||||
} else {
|
||||
let minX = Number.MAX_VALUE;
|
||||
let minY = Number.MAX_VALUE;
|
||||
let maxX = -Number.MAX_VALUE;
|
||||
let maxY = -Number.MAX_VALUE;
|
||||
for (const childInstance of this._instanceContainer.getAdhocListOfAllInstances()) {
|
||||
Array.prototype.push.apply(
|
||||
this._untransformedHitBoxes,
|
||||
childInstance.getHitBoxes()
|
||||
);
|
||||
const childAABB = childInstance.getAABB();
|
||||
minX = Math.min(minX, childAABB.min[0]);
|
||||
minY = Math.min(minY, childAABB.min[1]);
|
||||
maxX = Math.max(maxX, childAABB.max[0]);
|
||||
maxY = Math.max(maxY, childAABB.max[1]);
|
||||
}
|
||||
this._unrotatedAABB.min[0] = minX;
|
||||
this._unrotatedAABB.min[1] = minY;
|
||||
this._unrotatedAABB.max[0] = maxX;
|
||||
this._unrotatedAABB.max[1] = maxY;
|
||||
|
||||
while (this.hitBoxes.length < this._untransformedHitBoxes.length) {
|
||||
this.hitBoxes.push(new gdjs.Polygon());
|
||||
}
|
||||
this.hitBoxes.length = this._untransformedHitBoxes.length;
|
||||
}
|
||||
|
||||
if (
|
||||
this.getUnscaledCenterX() !== oldUnscaledCenterX ||
|
||||
this.getUnscaledCenterY() !== oldUnscaledCenterY
|
||||
) {
|
||||
this._instanceContainer.onObjectUnscaledCenterChanged(
|
||||
oldUnscaledCenterX,
|
||||
oldUnscaledCenterY
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Position:
|
||||
/**
|
||||
* Return an array containing the coordinates of the point passed as parameter
|
||||
* in parent coordinate coordinates (as opposed to the object local coordinates).
|
||||
*
|
||||
* All transformations (flipping, scale, rotation) are supported.
|
||||
*
|
||||
* @param x The X position of the point, in object coordinates.
|
||||
* @param y The Y position of the point, in object coordinates.
|
||||
* @param result Array that will be updated with the result
|
||||
* (x and y position of the point in parent coordinates).
|
||||
*/
|
||||
applyObjectTransformation(x: float, y: float, result: number[]) {
|
||||
let cx = this.getCenterX();
|
||||
let cy = this.getCenterY();
|
||||
|
||||
// Flipping
|
||||
if (this._flippedX) {
|
||||
x = x + (cx - x) * 2;
|
||||
}
|
||||
if (this._flippedY) {
|
||||
y = y + (cy - y) * 2;
|
||||
}
|
||||
|
||||
// Scale
|
||||
const absScaleX = Math.abs(this._scaleX);
|
||||
const absScaleY = Math.abs(this._scaleY);
|
||||
x *= absScaleX;
|
||||
y *= absScaleY;
|
||||
cx *= absScaleX;
|
||||
cy *= absScaleY;
|
||||
|
||||
// Rotation
|
||||
const oldX = x;
|
||||
const angleInRadians = (this.angle / 180) * Math.PI;
|
||||
const cosValue = Math.cos(angleInRadians);
|
||||
const sinValue = Math.sin(angleInRadians);
|
||||
const xToCenterXDelta = x - cx;
|
||||
const yToCenterYDelta = y - cy;
|
||||
x = cx + cosValue * xToCenterXDelta - sinValue * yToCenterYDelta;
|
||||
y = cy + sinValue * xToCenterXDelta + cosValue * yToCenterYDelta;
|
||||
result.length = 2;
|
||||
result[0] = x + this.x;
|
||||
result[1] = y + this.y;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an array containing the coordinates of the point passed as parameter
|
||||
* in object local coordinates (as opposed to the parent coordinate coordinates).
|
||||
*
|
||||
* All transformations (flipping, scale, rotation) are supported.
|
||||
*
|
||||
* @param x The X position of the point, in parent coordinates.
|
||||
* @param y The Y position of the point, in parent coordinates.
|
||||
* @param result Array that will be updated with the result
|
||||
* (x and y position of the point in object coordinates).
|
||||
*/
|
||||
applyObjectInverseTransformation(x: float, y: float, result: number[]) {
|
||||
x -= this.getCenterXInScene();
|
||||
y -= this.getCenterYInScene();
|
||||
|
||||
const absScaleX = Math.abs(this._scaleX);
|
||||
const absScaleY = Math.abs(this._scaleY);
|
||||
|
||||
// Rotation
|
||||
const angleInRadians = (this.angle / 180) * Math.PI;
|
||||
const cosValue = Math.cos(-angleInRadians);
|
||||
const sinValue = Math.sin(-angleInRadians);
|
||||
const oldX = x;
|
||||
x = cosValue * x - sinValue * y;
|
||||
y = sinValue * oldX + cosValue * y;
|
||||
|
||||
// Scale
|
||||
x /= absScaleX;
|
||||
y /= absScaleY;
|
||||
|
||||
// Flipping
|
||||
if (this._flippedX) {
|
||||
x = -x;
|
||||
}
|
||||
if (this._flippedY) {
|
||||
y = -y;
|
||||
}
|
||||
|
||||
const positionToCenterX =
|
||||
this.getUnscaledWidth() / 2 + this._unrotatedAABB.min[0];
|
||||
const positionToCenterY =
|
||||
this.getUnscaledHeight() / 2 + this._unrotatedAABB.min[1];
|
||||
result[0] = x + positionToCenterX;
|
||||
result[1] = y + positionToCenterY;
|
||||
}
|
||||
|
||||
getDrawableX(): float {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
return this.x + this._unrotatedAABB.min[0] * this._scaleX;
|
||||
}
|
||||
|
||||
getDrawableY(): float {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
return this.y + this._unrotatedAABB.min[1] * this._scaleY;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the internal width of the object according to its children.
|
||||
*/
|
||||
getUnscaledWidth(): float {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
return this._unrotatedAABB.max[0] - this._unrotatedAABB.min[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the internal height of the object according to its children.
|
||||
*/
|
||||
getUnscaledHeight(): float {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
return this._unrotatedAABB.max[1] - this._unrotatedAABB.min[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns the center X from the local origin (0;0).
|
||||
*/
|
||||
getUnscaledCenterX(): float {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
return (this._unrotatedAABB.min[0] + this._unrotatedAABB.max[0]) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns the center Y from the local origin (0;0).
|
||||
*/
|
||||
getUnscaledCenterY(): float {
|
||||
if (this._isUntransformedHitBoxesDirty) {
|
||||
this._updateUntransformedHitBoxes();
|
||||
}
|
||||
return (this._unrotatedAABB.min[1] + this._unrotatedAABB.max[1]) / 2;
|
||||
}
|
||||
|
||||
getWidth(): float {
|
||||
return this.getUnscaledWidth() * this.getScaleX();
|
||||
}
|
||||
|
||||
getHeight(): float {
|
||||
return this.getUnscaledHeight() * this.getScaleY();
|
||||
}
|
||||
|
||||
setWidth(newWidth: float): void {
|
||||
const unscaledWidth = this.getUnscaledWidth();
|
||||
if (unscaledWidth !== 0) {
|
||||
this.setScaleX(newWidth / unscaledWidth);
|
||||
}
|
||||
}
|
||||
|
||||
setHeight(newHeight: float): void {
|
||||
const unscaledHeight = this.getUnscaledHeight();
|
||||
if (unscaledHeight !== 0) {
|
||||
this.setScaleY(newHeight / unscaledHeight);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the size of the object.
|
||||
*
|
||||
* @param newWidth The new width of the object, in pixels.
|
||||
* @param newHeight The new height of the object, in pixels.
|
||||
*/
|
||||
setSize(newWidth: float, newHeight: float): void {
|
||||
this.setWidth(newWidth);
|
||||
this.setHeight(newHeight);
|
||||
}
|
||||
|
||||
setX(x: float): void {
|
||||
if (x === this.x) {
|
||||
return;
|
||||
}
|
||||
this.x = x;
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().updateX();
|
||||
}
|
||||
|
||||
setY(y: float): void {
|
||||
if (y === this.y) {
|
||||
return;
|
||||
}
|
||||
this.y = y;
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().updateY();
|
||||
}
|
||||
|
||||
setAngle(angle: float): void {
|
||||
if (this.angle === angle) {
|
||||
return;
|
||||
}
|
||||
this.angle = angle;
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().updateAngle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the scale on X and Y axis of the object.
|
||||
*
|
||||
* @param newScale The new scale (must be greater than 0).
|
||||
*/
|
||||
setScale(newScale: number): void {
|
||||
if (newScale < 0) {
|
||||
newScale = 0;
|
||||
}
|
||||
if (
|
||||
newScale === Math.abs(this._scaleX) &&
|
||||
newScale === Math.abs(this._scaleY)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this._scaleX = newScale * (this._flippedX ? -1 : 1);
|
||||
this._scaleY = newScale * (this._flippedY ? -1 : 1);
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().update();
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the scale on X axis of the object (changing its width).
|
||||
*
|
||||
* @param newScale The new scale (must be greater than 0).
|
||||
*/
|
||||
setScaleX(newScale: number): void {
|
||||
if (newScale < 0) {
|
||||
newScale = 0;
|
||||
}
|
||||
if (newScale === Math.abs(this._scaleX)) {
|
||||
return;
|
||||
}
|
||||
this._scaleX = newScale * (this._flippedX ? -1 : 1);
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().update();
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the scale on Y axis of the object (changing its height).
|
||||
*
|
||||
* @param newScale The new scale (must be greater than 0).
|
||||
*/
|
||||
setScaleY(newScale: number): void {
|
||||
if (newScale < 0) {
|
||||
newScale = 0;
|
||||
}
|
||||
if (newScale === Math.abs(this._scaleY)) {
|
||||
return;
|
||||
}
|
||||
this._scaleY = newScale * (this._flippedY ? -1 : 1);
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().update();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scale of the object (or the average of the X and Y scale in case
|
||||
* they are different).
|
||||
*
|
||||
* @return the scale of the object (or the average of the X and Y scale in
|
||||
* case they are different).
|
||||
*/
|
||||
getScale(): number {
|
||||
return (Math.abs(this._scaleX) + Math.abs(this._scaleY)) / 2.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scale of the object on Y axis.
|
||||
*
|
||||
* @return the scale of the object on Y axis
|
||||
*/
|
||||
getScaleY(): float {
|
||||
return Math.abs(this._scaleY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scale of the object on X axis.
|
||||
*
|
||||
* @return the scale of the object on X axis
|
||||
*/
|
||||
getScaleX(): float {
|
||||
return Math.abs(this._scaleX);
|
||||
}
|
||||
|
||||
// Visibility and display :
|
||||
/**
|
||||
* Change the transparency of the object.
|
||||
* @param opacity The new opacity, between 0 (transparent) and 255 (opaque).
|
||||
*/
|
||||
setOpacity(opacity: float): void {
|
||||
if (opacity < 0) {
|
||||
opacity = 0;
|
||||
}
|
||||
if (opacity > 255) {
|
||||
opacity = 255;
|
||||
}
|
||||
this.opacity = opacity;
|
||||
this.getRenderer().updateOpacity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the transparency of the object.
|
||||
* @return The opacity, between 0 (transparent) and 255 (opaque).
|
||||
*/
|
||||
getOpacity(): number {
|
||||
return this.opacity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide (or show) the object
|
||||
* @param enable true to hide the object, false to show it again.
|
||||
*/
|
||||
hide(enable: boolean): void {
|
||||
if (enable === undefined) {
|
||||
enable = true;
|
||||
}
|
||||
this.hidden = enable;
|
||||
this.getRenderer().updateVisibility();
|
||||
}
|
||||
|
||||
flipX(enable: boolean) {
|
||||
if (enable !== this._flippedX) {
|
||||
this._scaleX *= -1;
|
||||
this._flippedX = enable;
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().update();
|
||||
}
|
||||
}
|
||||
|
||||
flipY(enable: boolean) {
|
||||
if (enable !== this._flippedY) {
|
||||
this._scaleY *= -1;
|
||||
this._flippedY = enable;
|
||||
this.invalidateHitboxes();
|
||||
this.getRenderer().update();
|
||||
}
|
||||
}
|
||||
|
||||
isFlippedX(): boolean {
|
||||
return this._flippedX;
|
||||
}
|
||||
|
||||
isFlippedY(): boolean {
|
||||
return this._flippedY;
|
||||
}
|
||||
}
|
||||
|
||||
// Others initialization and internal state management :
|
||||
// TODO EBO Activate and test instance recycling.
|
||||
CustomRuntimeObject.supportsReinitialization = false;
|
||||
}
|
354
GDJS/Runtime/CustomRuntimeObjectInstanceContainer.ts
Normal file
354
GDJS/Runtime/CustomRuntimeObjectInstanceContainer.ts
Normal file
@@ -0,0 +1,354 @@
|
||||
/*
|
||||
* GDevelop JS Platform
|
||||
* Copyright 2013-2022 Florian Rival (Florian.Rival@gmail.com). All rights reserved.
|
||||
* This project is released under the MIT License.
|
||||
*/
|
||||
namespace gdjs {
|
||||
const logger = new gdjs.Logger('CustomRuntimeObject');
|
||||
const setupWarningLogger = new gdjs.Logger(
|
||||
'CustomRuntimeObject (setup warnings)'
|
||||
);
|
||||
|
||||
/**
|
||||
* The instance container of a custom object, containing instances of objects rendered on screen.
|
||||
*
|
||||
* @see gdjs.CustomRuntimeObject
|
||||
*/
|
||||
export class CustomRuntimeObjectInstanceContainer extends gdjs.RuntimeInstanceContainer {
|
||||
_renderer: gdjs.CustomObjectRenderer;
|
||||
_debuggerRenderer: gdjs.DebuggerRenderer;
|
||||
_runtimeScene: gdjs.RuntimeScene;
|
||||
/** The parent container that contains the object associated with this container. */
|
||||
_parent: gdjs.RuntimeInstanceContainer;
|
||||
/** The object that is built with the instances of this container. */
|
||||
_customObject: gdjs.CustomRuntimeObject;
|
||||
_isLoaded: boolean = false;
|
||||
|
||||
/**
|
||||
* @param parent the parent container that contains the object associated
|
||||
* with this container.
|
||||
* @param customObject the object that is built with the instances of this
|
||||
* container.
|
||||
*/
|
||||
constructor(
|
||||
parent: gdjs.RuntimeInstanceContainer,
|
||||
customObject: gdjs.CustomRuntimeObject
|
||||
) {
|
||||
super();
|
||||
this._parent = parent;
|
||||
this._customObject = customObject;
|
||||
this._runtimeScene = parent.getScene();
|
||||
this._renderer = new gdjs.CustomObjectRenderer(
|
||||
customObject,
|
||||
this,
|
||||
parent
|
||||
);
|
||||
this._debuggerRenderer = new gdjs.DebuggerRenderer(this);
|
||||
}
|
||||
|
||||
createObject(objectName: string): gdjs.RuntimeObject | null {
|
||||
const result = super.createObject(objectName);
|
||||
this._customObject.onChildrenLocationChanged();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the container from the given initial configuration.
|
||||
* @param customObjectData An object containing the container data.
|
||||
* @see gdjs.RuntimeGame#getSceneData
|
||||
*/
|
||||
loadFrom(customObjectData: ObjectData & CustomObjectConfiguration) {
|
||||
if (this._isLoaded) {
|
||||
this.onDestroyFromScene(this._parent);
|
||||
}
|
||||
|
||||
const eventsBasedObjectData = this._runtimeScene
|
||||
.getGame()
|
||||
.getEventsBasedObjectData(customObjectData.type);
|
||||
if (!eventsBasedObjectData) {
|
||||
logger.error('loadFrom was called without an events-based object');
|
||||
return;
|
||||
}
|
||||
|
||||
// Registering objects
|
||||
for (
|
||||
let i = 0, len = eventsBasedObjectData.objects.length;
|
||||
i < len;
|
||||
++i
|
||||
) {
|
||||
const childObjectData = eventsBasedObjectData.objects[i];
|
||||
this.registerObject({
|
||||
...childObjectData,
|
||||
...customObjectData.childrenContent[childObjectData.name],
|
||||
});
|
||||
}
|
||||
|
||||
// TODO EBO Remove it when the instance editor is done.
|
||||
// Add a default layer
|
||||
this.addLayer({
|
||||
name: '',
|
||||
visibility: true,
|
||||
cameras: [
|
||||
{
|
||||
defaultSize: true,
|
||||
defaultViewport: true,
|
||||
height: 0,
|
||||
viewportBottom: 0,
|
||||
viewportLeft: 0,
|
||||
viewportRight: 0,
|
||||
viewportTop: 0,
|
||||
width: 0,
|
||||
},
|
||||
],
|
||||
effects: [],
|
||||
ambientLightColorR: 0,
|
||||
ambientLightColorG: 0,
|
||||
ambientLightColorB: 0,
|
||||
isLightingLayer: false,
|
||||
followBaseLayerCamera: false,
|
||||
});
|
||||
|
||||
// Set up the default z order (for objects created from events)
|
||||
this._setLayerDefaultZOrders();
|
||||
|
||||
this._isLoaded = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the container must be updated using the specified
|
||||
* objectData. This is the case during hot-reload, and is only called if
|
||||
* the object was modified.
|
||||
*
|
||||
* @param oldCustomObjectData The previous data for the object.
|
||||
* @param newCustomObjectData The new data for the object.
|
||||
* @returns true if the object was updated, false if it could not
|
||||
* (i.e: hot-reload is not supported).
|
||||
*/
|
||||
updateFrom(
|
||||
oldCustomObjectData: ObjectData & CustomObjectConfiguration,
|
||||
newCustomObjectData: ObjectData & CustomObjectConfiguration
|
||||
): boolean {
|
||||
const eventsBasedObjectData = this._runtimeScene
|
||||
.getGame()
|
||||
.getEventsBasedObjectData(newCustomObjectData.type);
|
||||
if (!eventsBasedObjectData) {
|
||||
logger.error('updateFrom was called without an events-based object');
|
||||
return false;
|
||||
}
|
||||
|
||||
for (
|
||||
let i = 0, len = eventsBasedObjectData.objects.length;
|
||||
i < len;
|
||||
++i
|
||||
) {
|
||||
const childName = eventsBasedObjectData.objects[i].name;
|
||||
const oldChildData = {
|
||||
...eventsBasedObjectData.objects[i],
|
||||
...oldCustomObjectData.childrenContent[childName],
|
||||
};
|
||||
const newChildData = {
|
||||
...eventsBasedObjectData.objects[i],
|
||||
...newCustomObjectData.childrenContent[childName],
|
||||
};
|
||||
this.updateObject(newChildData);
|
||||
|
||||
for (const child of this.getInstancesOf(childName)) {
|
||||
child.updateFromObjectData(oldChildData, newChildData);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the associated object is destroyed (because it is removed
|
||||
* from its parent container or the scene is being unloaded).
|
||||
*
|
||||
* @param instanceContainer The container owning the object.
|
||||
*/
|
||||
onDestroyFromScene(instanceContainer: gdjs.RuntimeInstanceContainer): void {
|
||||
if (!this._isLoaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Notify the objects they are being destroyed
|
||||
const allInstancesList = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
|
||||
const object = allInstancesList[i];
|
||||
object.onDestroyFromScene(this);
|
||||
}
|
||||
|
||||
this._destroy();
|
||||
|
||||
this._isLoaded = false;
|
||||
}
|
||||
|
||||
_destroy() {
|
||||
// It should not be necessary to reset these variables, but this help
|
||||
// ensuring that all memory related to the container is released immediately.
|
||||
super._destroy();
|
||||
// @ts-ignore We are deleting the object
|
||||
this._onceTriggers = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to update visibility of the renderers of objects
|
||||
* rendered on the scene ("culling"), update effects (of visible objects)
|
||||
* and give a last chance for objects to update before rendering.
|
||||
*
|
||||
* Visibility is set to false if object is hidden, or if
|
||||
* object is too far from the camera of its layer ("culling").
|
||||
*/
|
||||
_updateObjectsPreRender() {
|
||||
const allInstancesList = this.getAdhocListOfAllInstances();
|
||||
for (
|
||||
let i = 0, len = this.getAdhocListOfAllInstances().length;
|
||||
i < len;
|
||||
++i
|
||||
) {
|
||||
const object = this.getAdhocListOfAllInstances()[i];
|
||||
const rendererObject = object.getRendererObject();
|
||||
if (rendererObject) {
|
||||
rendererObject.visible = !object.isHidden();
|
||||
|
||||
// Update effects, only for visible objects.
|
||||
if (rendererObject.visible) {
|
||||
this.getGame()
|
||||
.getEffectsManager()
|
||||
.updatePreRender(object.getRendererEffects(), object);
|
||||
}
|
||||
}
|
||||
|
||||
// Set to true to enable debug rendering (look for the implementation in the renderer
|
||||
// to see what is rendered).
|
||||
if (this._debugDrawEnabled) {
|
||||
this._debuggerRenderer.renderDebugDraw(
|
||||
this.getAdhocListOfAllInstances(),
|
||||
this._debugDrawShowHiddenInstances,
|
||||
this._debugDrawShowPointsNames,
|
||||
this._debugDrawShowCustomPoints
|
||||
);
|
||||
}
|
||||
|
||||
// Perform pre-render update.
|
||||
object.updatePreRender(this);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the objects before launching the events.
|
||||
*/
|
||||
_updateObjectsPreEvents() {
|
||||
const allInstancesList = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
|
||||
const obj = allInstancesList[i];
|
||||
const elapsedTime = obj.getElapsedTime();
|
||||
if (!obj.hasNoForces()) {
|
||||
const averageForce = obj.getAverageForce();
|
||||
const elapsedTimeInSeconds = elapsedTime / 1000;
|
||||
obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);
|
||||
obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);
|
||||
obj.update(this);
|
||||
obj.updateForces(elapsedTimeInSeconds);
|
||||
} else {
|
||||
obj.update(this);
|
||||
}
|
||||
obj.updateTimers(elapsedTime);
|
||||
obj.stepBehaviorsPreEvents(this);
|
||||
}
|
||||
|
||||
// Some behaviors may have request objects to be deleted.
|
||||
this._cacheOrClearRemovedInstances();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the renderer associated to the RuntimeScene.
|
||||
*/
|
||||
getRenderer(): gdjs.CustomObjectRenderer {
|
||||
return this._renderer;
|
||||
}
|
||||
|
||||
getDebuggerRenderer() {
|
||||
return this._debuggerRenderer;
|
||||
}
|
||||
|
||||
getGame() {
|
||||
return this._runtimeScene.getGame();
|
||||
}
|
||||
|
||||
getScene() {
|
||||
return this._runtimeScene;
|
||||
}
|
||||
|
||||
getViewportWidth(): float {
|
||||
return this._customObject.getUnscaledWidth();
|
||||
}
|
||||
|
||||
getViewportHeight(): float {
|
||||
return this._customObject.getUnscaledHeight();
|
||||
}
|
||||
|
||||
getViewportOriginX(): float {
|
||||
return this._customObject.getUnscaledCenterX();
|
||||
}
|
||||
|
||||
getViewportOriginY(): float {
|
||||
return this._customObject.getUnscaledCenterY();
|
||||
}
|
||||
|
||||
onChildrenLocationChanged(): void {
|
||||
this._customObject.onChildrenLocationChanged();
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggered when the object dimensions are changed.
|
||||
*
|
||||
* It adapts the layers camera positions.
|
||||
*/
|
||||
onObjectUnscaledCenterChanged(oldOriginX: float, oldOriginY: float): void {
|
||||
for (const name in this._layers.items) {
|
||||
if (this._layers.items.hasOwnProperty(name)) {
|
||||
/** @type gdjs.Layer */
|
||||
const theLayer: gdjs.Layer = this._layers.items[name];
|
||||
theLayer.onGameResolutionResized(oldOriginX, oldOriginY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
convertCoords(x: float, y: float, result: FloatPoint): FloatPoint {
|
||||
// The result parameter used to be optional.
|
||||
let position = result || [0, 0];
|
||||
position = this._parent
|
||||
.getLayer(this._customObject.getLayer())
|
||||
.convertCoords(x, y, 0, position);
|
||||
this._customObject.applyObjectInverseTransformation(
|
||||
position[0],
|
||||
position[1],
|
||||
position
|
||||
);
|
||||
return position;
|
||||
}
|
||||
|
||||
convertInverseCoords(
|
||||
sceneX: float,
|
||||
sceneY: float,
|
||||
result: FloatPoint
|
||||
): FloatPoint {
|
||||
const position = result || [0, 0];
|
||||
this._customObject.applyObjectTransformation(sceneX, sceneY, position);
|
||||
return this._parent.convertInverseCoords(
|
||||
position[0],
|
||||
position[1],
|
||||
position
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time elapsed since the last frame,
|
||||
* in milliseconds, for objects on the layer.
|
||||
*/
|
||||
getElapsedTime(): float {
|
||||
return this._parent.getElapsedTime();
|
||||
}
|
||||
}
|
||||
}
|
694
GDJS/Runtime/RuntimeInstanceContainer.ts
Normal file
694
GDJS/Runtime/RuntimeInstanceContainer.ts
Normal file
@@ -0,0 +1,694 @@
|
||||
/*
|
||||
* GDevelop JS Platform
|
||||
* Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.
|
||||
* This project is released under the MIT License.
|
||||
*/
|
||||
namespace gdjs {
|
||||
const logger = new gdjs.Logger('RuntimeInstanceContainer');
|
||||
const setupWarningLogger = new gdjs.Logger(
|
||||
'RuntimeInstanceContainer (setup warnings)'
|
||||
);
|
||||
|
||||
/**
|
||||
* A container of object instances rendered on screen.
|
||||
*/
|
||||
export abstract class RuntimeInstanceContainer {
|
||||
/** Contains the instances living on the container */
|
||||
_instances: Hashtable<RuntimeObject[]>;
|
||||
|
||||
/**
|
||||
* An array used to create a list of all instance when necessary.
|
||||
* @see gdjs.RuntimeInstanceContainer#_constructListOfAllInstances}
|
||||
*/
|
||||
private _allInstancesList: gdjs.RuntimeObject[] = [];
|
||||
_allInstancesListIsUpToDate = true;
|
||||
|
||||
/** Used to recycle destroyed instance instead of creating new ones. */
|
||||
_instancesCache: Hashtable<RuntimeObject[]>;
|
||||
|
||||
/** The instances removed from the container and waiting to be sent to the cache. */
|
||||
_instancesRemoved: gdjs.RuntimeObject[] = [];
|
||||
|
||||
/** Contains the objects data stored in the project */
|
||||
_objects: Hashtable<ObjectData>;
|
||||
_objectsCtor: Hashtable<typeof RuntimeObject>;
|
||||
|
||||
_layers: Hashtable<Layer>;
|
||||
_layersCameraCoordinates: Record<string, [float, float, float, float]> = {};
|
||||
|
||||
// Options for the debug draw:
|
||||
_debugDrawEnabled: boolean = false;
|
||||
_debugDrawShowHiddenInstances: boolean = false;
|
||||
_debugDrawShowPointsNames: boolean = false;
|
||||
_debugDrawShowCustomPoints: boolean = false;
|
||||
|
||||
constructor() {
|
||||
this._instances = new Hashtable();
|
||||
this._instancesCache = new Hashtable();
|
||||
this._objects = new Hashtable();
|
||||
this._objectsCtor = new Hashtable();
|
||||
this._layers = new Hashtable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the time elapsed since the last frame,
|
||||
* in milliseconds, for objects on the layer.
|
||||
*/
|
||||
abstract getElapsedTime(): float;
|
||||
|
||||
/**
|
||||
* Get the renderer associated to the container.
|
||||
*/
|
||||
abstract getRenderer(): gdjs.RuntimeInstanceContainerRenderer;
|
||||
|
||||
/**
|
||||
* Get the renderer for visual debugging associated to the container.
|
||||
*/
|
||||
abstract getDebuggerRenderer(): gdjs.DebuggerRenderer;
|
||||
|
||||
/**
|
||||
* Get the {@link gdjs.RuntimeGame} associated to this.
|
||||
*/
|
||||
abstract getGame(): gdjs.RuntimeGame;
|
||||
|
||||
/**
|
||||
* Get the {@link gdjs.RuntimeScene} associated to this.
|
||||
*/
|
||||
abstract getScene(): gdjs.RuntimeScene;
|
||||
|
||||
/**
|
||||
* Convert a point from the canvas coordinates (for example,
|
||||
* the mouse position) to the container coordinates.
|
||||
*
|
||||
* @param x The x position, in container coordinates.
|
||||
* @param y The y position, in container coordinates.
|
||||
* @param result The point instance that is used to return the result.
|
||||
*/
|
||||
abstract convertCoords(x: float, y: float, result?: FloatPoint): FloatPoint;
|
||||
|
||||
/**
|
||||
* Convert a point from the container coordinates (for example,
|
||||
* an object position) to the canvas coordinates.
|
||||
*
|
||||
* @param sceneX The x position, in container coordinates.
|
||||
* @param sceneY The y position, in container coordinates.
|
||||
* @param result The point instance that is used to return the result.
|
||||
*/
|
||||
abstract convertInverseCoords(
|
||||
sceneX: float,
|
||||
sceneY: float,
|
||||
result: FloatPoint
|
||||
): FloatPoint;
|
||||
|
||||
/**
|
||||
* @return the width of:
|
||||
* - the game resolution for a {@link gdjs.RuntimeScene}
|
||||
* - the default dimensions (the AABB of all its children) for a
|
||||
* {@link gdjs.CustomRuntimeObject}.
|
||||
*/
|
||||
abstract getViewportWidth(): float;
|
||||
|
||||
/**
|
||||
* @return the height of:
|
||||
* - the game resolution for a {@link gdjs.RuntimeScene}
|
||||
* - the default dimensions (the AABB of all its children) for a
|
||||
* {@link gdjs.CustomRuntimeObject}.
|
||||
*/
|
||||
abstract getViewportHeight(): float;
|
||||
|
||||
/**
|
||||
* @return the center X of:
|
||||
* - the game resolution for a {@link gdjs.RuntimeScene}
|
||||
* - the default dimensions (the AABB of all its children) for a
|
||||
* {@link gdjs.CustomRuntimeObject}.
|
||||
*/
|
||||
abstract getViewportOriginX(): float;
|
||||
|
||||
/**
|
||||
* @return the center Y of:
|
||||
* - the game resolution for a {@link gdjs.RuntimeScene}
|
||||
* - the default dimensions (the AABB of all its children) for a
|
||||
* {@link gdjs.CustomRuntimeObject}.
|
||||
*/
|
||||
abstract getViewportOriginY(): float;
|
||||
|
||||
/**
|
||||
* Triggered when the AABB of a child of the container could have changed.
|
||||
*/
|
||||
abstract onChildrenLocationChanged(): void;
|
||||
|
||||
/**
|
||||
* Activate or deactivate the debug visualization for collisions and points.
|
||||
*/
|
||||
enableDebugDraw(
|
||||
enableDebugDraw: boolean,
|
||||
showHiddenInstances: boolean,
|
||||
showPointsNames: boolean,
|
||||
showCustomPoints: boolean
|
||||
): void {
|
||||
if (this._debugDrawEnabled && !enableDebugDraw) {
|
||||
this.getDebuggerRenderer().clearDebugDraw();
|
||||
}
|
||||
|
||||
this._debugDrawEnabled = enableDebugDraw;
|
||||
this._debugDrawShowHiddenInstances = showHiddenInstances;
|
||||
this._debugDrawShowPointsNames = showPointsNames;
|
||||
this._debugDrawShowCustomPoints = showCustomPoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an object is registered, meaning that instances of it can be
|
||||
* created and lives in the container.
|
||||
* @see gdjs.RuntimeInstanceContainer#registerObject
|
||||
*/
|
||||
isObjectRegistered(objectName: string): boolean {
|
||||
return (
|
||||
this._objects.containsKey(objectName) &&
|
||||
this._instances.containsKey(objectName) &&
|
||||
this._objectsCtor.containsKey(objectName)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a {@link gdjs.RuntimeObject} so that instances of it can be
|
||||
* used in the container.
|
||||
* @param objectData The data for the object to register.
|
||||
*/
|
||||
registerObject(objectData: ObjectData) {
|
||||
this._objects.put(objectData.name, objectData);
|
||||
this._instances.put(objectData.name, []);
|
||||
|
||||
// Cache the constructor
|
||||
const Ctor = gdjs.getObjectConstructor(objectData.type);
|
||||
this._objectsCtor.put(objectData.name, Ctor);
|
||||
|
||||
// Also prepare a cache for recycled instances, if the object supports it.
|
||||
if (Ctor.supportsReinitialization) {
|
||||
this._instancesCache.put(objectData.name, []);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the data of a {@link gdjs.RuntimeObject} so that instances use
|
||||
* this when constructed.
|
||||
* @param objectData The data for the object to register.
|
||||
*/
|
||||
updateObject(objectData: ObjectData): void {
|
||||
if (!this.isObjectRegistered(objectData.name)) {
|
||||
logger.warn(
|
||||
'Tried to call updateObject for an object that was not registered (' +
|
||||
objectData.name +
|
||||
'). Call registerObject first.'
|
||||
);
|
||||
}
|
||||
this._objects.put(objectData.name, objectData);
|
||||
}
|
||||
|
||||
// Don't erase instances, nor instances cache, or objectsCtor cache.
|
||||
/**
|
||||
* Unregister a {@link gdjs.RuntimeObject}. Instances will be destroyed.
|
||||
* @param objectName The name of the object to unregister.
|
||||
*/
|
||||
unregisterObject(objectName: string) {
|
||||
const instances = this._instances.get(objectName);
|
||||
if (instances) {
|
||||
// This is sub-optimal: markObjectForDeletion will search the instance to
|
||||
// remove in instances, so cost is O(n^2), n being the number of instances.
|
||||
// As we're unregistering an object which only happen during a hot-reloading,
|
||||
// this is fine.
|
||||
const instancesToRemove = instances.slice();
|
||||
for (let i = 0; i < instancesToRemove.length; i++) {
|
||||
this.markObjectForDeletion(instancesToRemove[i]);
|
||||
}
|
||||
this._cacheOrClearRemovedInstances();
|
||||
}
|
||||
this._objects.remove(objectName);
|
||||
this._instances.remove(objectName);
|
||||
this._instancesCache.remove(objectName);
|
||||
this._objectsCtor.remove(objectName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create objects from initial instances data (for example, the initial instances
|
||||
* of the scene or the instances of an external layout).
|
||||
*
|
||||
* @param data The instances data
|
||||
* @param xPos The offset on X axis
|
||||
* @param yPos The offset on Y axis
|
||||
* @param trackByPersistentUuid If true, objects are tracked by setting their `persistentUuid`
|
||||
* to the same as the associated instance. Useful for hot-reloading when instances are changed.
|
||||
*/
|
||||
createObjectsFrom(
|
||||
data: InstanceData[],
|
||||
xPos: float,
|
||||
yPos: float,
|
||||
trackByPersistentUuid: boolean
|
||||
) {
|
||||
for (let i = 0, len = data.length; i < len; ++i) {
|
||||
const instanceData = data[i];
|
||||
const objectName = instanceData.name;
|
||||
const newObject = this.createObject(objectName);
|
||||
if (newObject !== null) {
|
||||
if (trackByPersistentUuid) {
|
||||
// Give the object the same persistentUuid as the instance, so that
|
||||
// it can be hot-reloaded.
|
||||
newObject.persistentUuid = instanceData.persistentUuid || null;
|
||||
}
|
||||
newObject.setPosition(instanceData.x + xPos, instanceData.y + yPos);
|
||||
newObject.setZOrder(instanceData.zOrder);
|
||||
newObject.setAngle(instanceData.angle);
|
||||
newObject.setLayer(instanceData.layer);
|
||||
newObject
|
||||
.getVariables()
|
||||
.initFrom(instanceData.initialVariables, true);
|
||||
newObject.extraInitializationFromInitialInstance(instanceData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the default Z order for each layer, which is the highest Z order found on each layer.
|
||||
* Useful as it ensures that instances created from events are, by default, shown in front
|
||||
* of other instances.
|
||||
*/
|
||||
_setLayerDefaultZOrders() {
|
||||
if (
|
||||
this.getGame().getGameData().properties.useDeprecatedZeroAsDefaultZOrder
|
||||
) {
|
||||
// Deprecated option to still support games that were made considered 0 as the
|
||||
// default Z order for all layers.
|
||||
return;
|
||||
}
|
||||
const layerHighestZOrders: Record<string, number> = {};
|
||||
const allInstances = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0, len = allInstances.length; i < len; ++i) {
|
||||
const object = allInstances[i];
|
||||
let layerName = object.getLayer();
|
||||
const zOrder = object.getZOrder();
|
||||
if (
|
||||
layerHighestZOrders[layerName] === undefined ||
|
||||
layerHighestZOrders[layerName] < zOrder
|
||||
) {
|
||||
layerHighestZOrders[layerName] = zOrder;
|
||||
}
|
||||
}
|
||||
for (let layerName in layerHighestZOrders) {
|
||||
this.getLayer(layerName).setDefaultZOrder(
|
||||
layerHighestZOrders[layerName] + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_updateLayersCameraCoordinates(scale: float) {
|
||||
this._layersCameraCoordinates = this._layersCameraCoordinates || {};
|
||||
for (const name in this._layers.items) {
|
||||
if (this._layers.items.hasOwnProperty(name)) {
|
||||
const theLayer = this._layers.items[name];
|
||||
this._layersCameraCoordinates[name] = this._layersCameraCoordinates[
|
||||
name
|
||||
] || [0, 0, 0, 0];
|
||||
this._layersCameraCoordinates[name][0] =
|
||||
theLayer.getCameraX() - (theLayer.getCameraWidth() / 2) * scale;
|
||||
this._layersCameraCoordinates[name][1] =
|
||||
theLayer.getCameraY() - (theLayer.getCameraHeight() / 2) * scale;
|
||||
this._layersCameraCoordinates[name][2] =
|
||||
theLayer.getCameraX() + (theLayer.getCameraWidth() / 2) * scale;
|
||||
this._layersCameraCoordinates[name][3] =
|
||||
theLayer.getCameraY() + (theLayer.getCameraHeight() / 2) * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to update effects of layers before rendering.
|
||||
*/
|
||||
_updateLayersPreRender() {
|
||||
for (const name in this._layers.items) {
|
||||
if (this._layers.items.hasOwnProperty(name)) {
|
||||
const layer = this._layers.items[name];
|
||||
layer.updatePreRender(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to update visibility of the renderers of objects
|
||||
* rendered on the scene ("culling"), update effects (of visible objects)
|
||||
* and give a last chance for objects to update before rendering.
|
||||
*
|
||||
* Visibility is set to false if object is hidden, or if
|
||||
* object is too far from the camera of its layer ("culling").
|
||||
*/
|
||||
_updateObjectsPreRender() {
|
||||
const allInstancesList = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
|
||||
const object = allInstancesList[i];
|
||||
const rendererObject = object.getRendererObject();
|
||||
if (rendererObject) {
|
||||
rendererObject.visible = !object.isHidden();
|
||||
|
||||
// Update effects, only for visible objects.
|
||||
if (rendererObject.visible) {
|
||||
this.getGame()
|
||||
.getEffectsManager()
|
||||
.updatePreRender(object.getRendererEffects(), object);
|
||||
}
|
||||
}
|
||||
|
||||
// Perform pre-render update.
|
||||
object.updatePreRender(this);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Empty the list of the removed objects:
|
||||
*
|
||||
* When an object is removed from the container, it is still kept in
|
||||
* {@link gdjs.RuntimeInstanceContainer#_instancesRemoved}.
|
||||
*
|
||||
* This method should be called regularly (after events or behaviors steps) so as to clear this list
|
||||
* and allows the removed objects to be cached (or destroyed if the cache is full).
|
||||
*
|
||||
* The removed objects could not be sent directly to the cache, as events may still be using them after
|
||||
* removing them from the scene for example.
|
||||
*/
|
||||
_cacheOrClearRemovedInstances() {
|
||||
for (let k = 0, lenk = this._instancesRemoved.length; k < lenk; ++k) {
|
||||
// Cache the instance to recycle it into a new instance later.
|
||||
// If the object does not support recycling, the cache won't be defined.
|
||||
const cache = this._instancesCache.get(
|
||||
this._instancesRemoved[k].getName()
|
||||
);
|
||||
if (cache) {
|
||||
if (cache.length < 128) {
|
||||
cache.push(this._instancesRemoved[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
this._instancesRemoved.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool function filling _allInstancesList member with all the living object instances.
|
||||
*/
|
||||
private _constructListOfAllInstances() {
|
||||
let currentListSize = 0;
|
||||
for (const name in this._instances.items) {
|
||||
if (this._instances.items.hasOwnProperty(name)) {
|
||||
const list = this._instances.items[name];
|
||||
const oldSize = currentListSize;
|
||||
currentListSize += list.length;
|
||||
for (let j = 0, lenj = list.length; j < lenj; ++j) {
|
||||
if (oldSize + j < this._allInstancesList.length) {
|
||||
this._allInstancesList[oldSize + j] = list[j];
|
||||
} else {
|
||||
this._allInstancesList.push(list[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this._allInstancesList.length = currentListSize;
|
||||
this._allInstancesListIsUpToDate = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param objectName The name of the object
|
||||
* @returns the instances of a given object in the container.
|
||||
*/
|
||||
getInstancesOf(objectName: string): gdjs.RuntimeObject[] {
|
||||
return this._instances.items[objectName];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all {@link gdjs.RuntimeObject} living in the container.
|
||||
* You should not, normally, need this method at all. It's only to be used
|
||||
* in exceptional use cases where you need to loop through all objects,
|
||||
* and it won't be performant.
|
||||
*
|
||||
* @returns The list of all runtime objects in the container
|
||||
*/
|
||||
getAdhocListOfAllInstances(): gdjs.RuntimeObject[] {
|
||||
if (!this._allInstancesListIsUpToDate) {
|
||||
this._constructListOfAllInstances();
|
||||
}
|
||||
return this._allInstancesList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the objects before launching the events.
|
||||
*/
|
||||
_updateObjectsPreEvents() {
|
||||
// It is *mandatory* to create and iterate on a external list of all objects, as the behaviors
|
||||
// may delete the objects.
|
||||
const allInstancesList = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
|
||||
const obj = allInstancesList[i];
|
||||
const elapsedTime = obj.getElapsedTime();
|
||||
if (!obj.hasNoForces()) {
|
||||
const averageForce = obj.getAverageForce();
|
||||
const elapsedTimeInSeconds = elapsedTime / 1000;
|
||||
obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);
|
||||
obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);
|
||||
obj.update(this);
|
||||
obj.updateForces(elapsedTimeInSeconds);
|
||||
} else {
|
||||
obj.update(this);
|
||||
}
|
||||
obj.updateTimers(elapsedTime);
|
||||
allInstancesList[i].stepBehaviorsPreEvents(this);
|
||||
}
|
||||
|
||||
// Some behaviors may have request objects to be deleted.
|
||||
this._cacheOrClearRemovedInstances();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the objects (update positions, time management...)
|
||||
*/
|
||||
_updateObjectsPostEvents() {
|
||||
this._cacheOrClearRemovedInstances();
|
||||
|
||||
// It is *mandatory* to create and iterate on a external list of all objects, as the behaviors
|
||||
// may delete the objects.
|
||||
const allInstancesList = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0, len = allInstancesList.length; i < len; ++i) {
|
||||
allInstancesList[i].stepBehaviorsPostEvents(this);
|
||||
}
|
||||
|
||||
// Some behaviors may have request objects to be deleted.
|
||||
this._cacheOrClearRemovedInstances();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an object to the instances living in the container.
|
||||
* @param obj The object to be added.
|
||||
*/
|
||||
addObject(obj: gdjs.RuntimeObject) {
|
||||
if (!this._instances.containsKey(obj.name)) {
|
||||
this._instances.put(obj.name, []);
|
||||
}
|
||||
this._instances.get(obj.name).push(obj);
|
||||
this._allInstancesListIsUpToDate = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the instances of the object called name.
|
||||
* @param name Name of the object for which the instances must be returned.
|
||||
* @return The list of objects with the given name
|
||||
*/
|
||||
getObjects(name: string): gdjs.RuntimeObject[] | undefined {
|
||||
if (!this._instances.containsKey(name)) {
|
||||
logger.info(
|
||||
'RuntimeScene.getObjects: No instances called "' +
|
||||
name +
|
||||
'"! Adding it.'
|
||||
);
|
||||
this._instances.put(name, []);
|
||||
}
|
||||
return this._instances.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new object from its name. The object is also added to the instances
|
||||
* living in the container (No need to call {@link gdjs.RuntimeScene.addObject})
|
||||
* @param objectName The name of the object to be created
|
||||
* @return The created object
|
||||
*/
|
||||
createObject(objectName: string): gdjs.RuntimeObject | null {
|
||||
if (
|
||||
!this._objectsCtor.containsKey(objectName) ||
|
||||
!this._objects.containsKey(objectName)
|
||||
) {
|
||||
// There is no such object in this container.
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create a new object using the object constructor (cached during loading)
|
||||
// and the stored object's data:
|
||||
const cache = this._instancesCache.get(objectName);
|
||||
const ctor = this._objectsCtor.get(objectName);
|
||||
let obj;
|
||||
if (!cache || cache.length === 0) {
|
||||
obj = new ctor(this, this._objects.get(objectName));
|
||||
} else {
|
||||
// Reuse an objet destroyed before. If there is an object in the cache,
|
||||
// then it means it does support reinitialization.
|
||||
obj = cache.pop();
|
||||
obj.reinitialize(this._objects.get(objectName));
|
||||
}
|
||||
this.addObject(obj);
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be called whenever an object must be removed from the container.
|
||||
* @param obj The object to be removed.
|
||||
*/
|
||||
markObjectForDeletion(obj: gdjs.RuntimeObject) {
|
||||
// Add to the objects removed list.
|
||||
// The objects will be sent to the instances cache or really deleted from memory later.
|
||||
if (this._instancesRemoved.indexOf(obj) === -1) {
|
||||
this._instancesRemoved.push(obj);
|
||||
}
|
||||
|
||||
// Delete from the living instances.
|
||||
if (this._instances.containsKey(obj.getName())) {
|
||||
const objId = obj.id;
|
||||
const allInstances = this._instances.get(obj.getName());
|
||||
for (let i = 0, len = allInstances.length; i < len; ++i) {
|
||||
if (allInstances[i].id == objId) {
|
||||
allInstances.splice(i, 1);
|
||||
this._allInstancesListIsUpToDate = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notify the object it was removed from the container
|
||||
obj.onDestroyFromScene(this);
|
||||
|
||||
// Notify the global callbacks
|
||||
for (let j = 0; j < gdjs.callbacksObjectDeletedFromScene.length; ++j) {
|
||||
gdjs.callbacksObjectDeletedFromScene[j](this, obj);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the layer with the given name
|
||||
* @param name The name of the layer
|
||||
* @returns The layer, or the base layer if not found
|
||||
*/
|
||||
getLayer(name: string): gdjs.Layer {
|
||||
if (this._layers.containsKey(name)) {
|
||||
return this._layers.get(name);
|
||||
}
|
||||
return this._layers.get('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a layer exists
|
||||
* @param name The name of the layer
|
||||
*/
|
||||
hasLayer(name: string): boolean {
|
||||
return this._layers.containsKey(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a layer.
|
||||
* @param layerData The data to construct the layer
|
||||
*/
|
||||
addLayer(layerData: LayerData) {
|
||||
this._layers.put(layerData.name, new gdjs.Layer(layerData, this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a layer. All {@link gdjs.RuntimeObject} on this layer will
|
||||
* be moved back to the base layer.
|
||||
* @param layerName The name of the layer to remove
|
||||
*/
|
||||
removeLayer(layerName: string) {
|
||||
const allInstances = this.getAdhocListOfAllInstances();
|
||||
for (let i = 0; i < allInstances.length; ++i) {
|
||||
const runtimeObject = allInstances[i];
|
||||
if (runtimeObject.getLayer() === layerName) {
|
||||
runtimeObject.setLayer('');
|
||||
}
|
||||
}
|
||||
this._layers.remove(layerName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the position of a layer.
|
||||
*
|
||||
* @param layerName The name of the layer to reorder
|
||||
* @param index The new position in the list of layers
|
||||
*/
|
||||
setLayerIndex(layerName: string, index: integer): void {
|
||||
const layer: gdjs.Layer = this._layers.get(layerName);
|
||||
if (!layer) {
|
||||
return;
|
||||
}
|
||||
this.getRenderer().setLayerIndex(layer, index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill the array passed as argument with the names of all layers
|
||||
* @param result The array where to put the layer names
|
||||
*/
|
||||
getAllLayerNames(result: string[]) {
|
||||
this._layers.keys(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the number of instances of the specified object living in the container.
|
||||
* @param objectName The object name for which instances must be counted.
|
||||
*/
|
||||
getInstancesCountOnScene(objectName: string): integer {
|
||||
const instances = this._instances.get(objectName);
|
||||
if (instances) {
|
||||
return instances.length;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the objects positions according to their forces
|
||||
*/
|
||||
updateObjectsForces(): void {
|
||||
for (const name in this._instances.items) {
|
||||
if (this._instances.items.hasOwnProperty(name)) {
|
||||
const list = this._instances.items[name];
|
||||
for (let j = 0, listLen = list.length; j < listLen; ++j) {
|
||||
const obj = list[j];
|
||||
if (!obj.hasNoForces()) {
|
||||
const averageForce = obj.getAverageForce();
|
||||
const elapsedTimeInSeconds = obj.getElapsedTime() / 1000;
|
||||
obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);
|
||||
obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);
|
||||
obj.updateForces(elapsedTimeInSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any data structures to make sure memory is freed as soon as
|
||||
* possible.
|
||||
*/
|
||||
_destroy() {
|
||||
// It should not be necessary to reset these variables, but this help
|
||||
// ensuring that all memory related to the container is released immediately.
|
||||
this._layers = new Hashtable();
|
||||
this._objects = new Hashtable();
|
||||
this._instances = new Hashtable();
|
||||
this._instancesCache = new Hashtable();
|
||||
this._objectsCtor = new Hashtable();
|
||||
this._allInstancesList = [];
|
||||
this._instancesRemoved = [];
|
||||
}
|
||||
}
|
||||
}
|
74
GDJS/Runtime/RuntimeSceneLayer.ts
Normal file
74
GDJS/Runtime/RuntimeSceneLayer.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* GDevelop JS Platform
|
||||
* Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.
|
||||
* This project is released under the MIT License.
|
||||
*/
|
||||
namespace gdjs {
|
||||
/**
|
||||
* Represents a layer of a scene, used to display objects.
|
||||
*
|
||||
* Viewports and multiple cameras are not supported.
|
||||
*
|
||||
* It does some optimizations but works exactly the same as
|
||||
* {@link gdjs.Layer}.
|
||||
*/
|
||||
export class RuntimeSceneLayer extends gdjs.Layer {
|
||||
/**
|
||||
* @param layerData The data used to initialize the layer
|
||||
* @param scene The scene in which the layer is used
|
||||
*/
|
||||
constructor(layerData: LayerData, scene: gdjs.RuntimeScene) {
|
||||
super(layerData, scene);
|
||||
}
|
||||
|
||||
convertCoords(
|
||||
x: float,
|
||||
y: float,
|
||||
cameraId: integer = 0,
|
||||
result: FloatPoint
|
||||
): FloatPoint {
|
||||
// The result parameter used to be optional.
|
||||
let position = result || [0, 0];
|
||||
x -= this.getRuntimeScene()._cachedGameResolutionWidth / 2;
|
||||
y -= this.getRuntimeScene()._cachedGameResolutionHeight / 2;
|
||||
x /= Math.abs(this._zoomFactor);
|
||||
y /= Math.abs(this._zoomFactor);
|
||||
|
||||
// Only compute angle and cos/sin once (allow heavy optimization from JS engines).
|
||||
const angleInRadians = (this._cameraRotation / 180) * Math.PI;
|
||||
const tmp = x;
|
||||
const cosValue = Math.cos(angleInRadians);
|
||||
const sinValue = Math.sin(angleInRadians);
|
||||
x = cosValue * x - sinValue * y;
|
||||
y = sinValue * tmp + cosValue * y;
|
||||
position[0] = x + this.getCameraX(cameraId);
|
||||
position[1] = y + this.getCameraY(cameraId);
|
||||
return position;
|
||||
}
|
||||
|
||||
convertInverseCoords(
|
||||
x: float,
|
||||
y: float,
|
||||
cameraId: integer = 0,
|
||||
result: FloatPoint
|
||||
): FloatPoint {
|
||||
// The result parameter used to be optional.
|
||||
let position = result || [0, 0];
|
||||
x -= this.getCameraX(cameraId);
|
||||
y -= this.getCameraY(cameraId);
|
||||
|
||||
// Only compute angle and cos/sin once (allow heavy optimization from JS engines).
|
||||
const angleInRadians = (this._cameraRotation / 180) * Math.PI;
|
||||
const tmp = x;
|
||||
const cosValue = Math.cos(-angleInRadians);
|
||||
const sinValue = Math.sin(-angleInRadians);
|
||||
x = cosValue * x - sinValue * y;
|
||||
y = sinValue * tmp + cosValue * y;
|
||||
x *= Math.abs(this._zoomFactor);
|
||||
y *= Math.abs(this._zoomFactor);
|
||||
position[0] = x + this.getRuntimeScene()._cachedGameResolutionWidth / 2;
|
||||
position[1] = y + this.getRuntimeScene()._cachedGameResolutionHeight / 2;
|
||||
return position;
|
||||
}
|
||||
}
|
||||
}
|
@@ -639,7 +639,7 @@ namespace gdjs {
|
||||
newObjects.forEach((newObjectData) => {
|
||||
const objectName = newObjectData.name;
|
||||
const newBehaviors = newObjectData.behaviors;
|
||||
const runtimeObjects = runtimeScene.getObjects(objectName);
|
||||
const runtimeObjects = runtimeScene.getObjects(objectName)!;
|
||||
changedRuntimeBehaviors.forEach((changedRuntimeBehavior) => {
|
||||
const behaviorTypeName = changedRuntimeBehavior.behaviorTypeName;
|
||||
|
||||
@@ -784,7 +784,7 @@ namespace gdjs {
|
||||
runtimeScene.updateObject(newObjectData);
|
||||
|
||||
// Update existing instances
|
||||
const runtimeObjects = runtimeScene.getObjects(newObjectData.name);
|
||||
const runtimeObjects = runtimeScene.getObjects(newObjectData.name)!;
|
||||
|
||||
// Update instances state
|
||||
runtimeObjects.forEach((runtimeObject) => {
|
||||
|
@@ -7,215 +7,217 @@ namespace gdjs {
|
||||
export namespace evtTools {
|
||||
export namespace camera {
|
||||
export const setCameraX = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
x: float,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
runtimeScene.getLayer(layer).setCameraX(x, cameraId);
|
||||
instanceContainer.getLayer(layer).setCameraX(x, cameraId);
|
||||
};
|
||||
|
||||
export const setCameraY = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
y: float,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
runtimeScene.getLayer(layer).setCameraY(y, cameraId);
|
||||
instanceContainer.getLayer(layer).setCameraY(y, cameraId);
|
||||
};
|
||||
|
||||
export const getCameraX = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getCameraX();
|
||||
return instanceContainer.getLayer(layer).getCameraX();
|
||||
};
|
||||
|
||||
export const getCameraY = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getCameraY();
|
||||
return instanceContainer.getLayer(layer).getCameraY();
|
||||
};
|
||||
|
||||
export const getCameraWidth = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getCameraWidth();
|
||||
return instanceContainer.getLayer(layer).getCameraWidth();
|
||||
};
|
||||
|
||||
export const getCameraHeight = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getCameraHeight();
|
||||
return instanceContainer.getLayer(layer).getCameraHeight();
|
||||
};
|
||||
|
||||
export const getCameraBorderLeft = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return (
|
||||
getCameraX(runtimeScene, layer, cameraId) -
|
||||
getCameraWidth(runtimeScene, layer, cameraId) / 2
|
||||
getCameraX(instanceContainer, layer, cameraId) -
|
||||
getCameraWidth(instanceContainer, layer, cameraId) / 2
|
||||
);
|
||||
};
|
||||
|
||||
export const getCameraBorderRight = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return (
|
||||
getCameraX(runtimeScene, layer, cameraId) +
|
||||
getCameraWidth(runtimeScene, layer, cameraId) / 2
|
||||
getCameraX(instanceContainer, layer, cameraId) +
|
||||
getCameraWidth(instanceContainer, layer, cameraId) / 2
|
||||
);
|
||||
};
|
||||
|
||||
export const getCameraBorderTop = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return (
|
||||
getCameraY(runtimeScene, layer, cameraId) -
|
||||
getCameraHeight(runtimeScene, layer, cameraId) / 2
|
||||
getCameraY(instanceContainer, layer, cameraId) -
|
||||
getCameraHeight(instanceContainer, layer, cameraId) / 2
|
||||
);
|
||||
};
|
||||
|
||||
export const getCameraBorderBottom = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return (
|
||||
getCameraY(runtimeScene, layer, cameraId) +
|
||||
getCameraHeight(runtimeScene, layer, cameraId) / 2
|
||||
getCameraY(instanceContainer, layer, cameraId) +
|
||||
getCameraHeight(instanceContainer, layer, cameraId) / 2
|
||||
);
|
||||
};
|
||||
|
||||
export const showLayer = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).show(true);
|
||||
return instanceContainer.getLayer(layer).show(true);
|
||||
};
|
||||
|
||||
export const hideLayer = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).show(false);
|
||||
return instanceContainer.getLayer(layer).show(false);
|
||||
};
|
||||
|
||||
export const layerIsVisible = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string
|
||||
): boolean {
|
||||
return (
|
||||
runtimeScene.hasLayer(layer) &&
|
||||
runtimeScene.getLayer(layer).isVisible()
|
||||
instanceContainer.hasLayer(layer) &&
|
||||
instanceContainer.getLayer(layer).isVisible()
|
||||
);
|
||||
};
|
||||
|
||||
export const setCameraRotation = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
rotation: float,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.setCameraRotation(rotation, cameraId);
|
||||
};
|
||||
|
||||
export const getCameraRotation = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getCameraRotation(cameraId);
|
||||
return instanceContainer.getLayer(layer).getCameraRotation(cameraId);
|
||||
};
|
||||
|
||||
export const getCameraZoom = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getCameraZoom(cameraId);
|
||||
return instanceContainer.getLayer(layer).getCameraZoom(cameraId);
|
||||
};
|
||||
|
||||
export const setCameraZoom = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
newZoom: float,
|
||||
layer: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).setCameraZoom(newZoom, cameraId);
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.setCameraZoom(newZoom, cameraId);
|
||||
};
|
||||
|
||||
export const centerCamera = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
object: gdjs.RuntimeObject | null,
|
||||
anticipateMove: boolean,
|
||||
layerName: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layerName) || object == null) {
|
||||
if (!instanceContainer.hasLayer(layerName) || object == null) {
|
||||
return;
|
||||
}
|
||||
let xOffset = 0;
|
||||
@@ -223,11 +225,11 @@ namespace gdjs {
|
||||
if (anticipateMove && !object.hasNoForces()) {
|
||||
const objectAverageForce = object.getAverageForce();
|
||||
const elapsedTimeInSeconds =
|
||||
object.getElapsedTime(runtimeScene) / 1000;
|
||||
object.getElapsedTime(instanceContainer) / 1000;
|
||||
xOffset = objectAverageForce.getX() * elapsedTimeInSeconds;
|
||||
yOffset = objectAverageForce.getY() * elapsedTimeInSeconds;
|
||||
}
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
const layer = instanceContainer.getLayer(layerName);
|
||||
layer.setCameraX(object.getCenterXInScene() + xOffset, cameraId);
|
||||
layer.setCameraY(object.getCenterYInScene() + yOffset, cameraId);
|
||||
};
|
||||
@@ -236,7 +238,7 @@ namespace gdjs {
|
||||
* @deprecated prefer using centerCamera and clampCamera.
|
||||
*/
|
||||
export const centerCameraWithinLimits = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
object: gdjs.RuntimeObject | null,
|
||||
left: number,
|
||||
top: number,
|
||||
@@ -246,9 +248,15 @@ namespace gdjs {
|
||||
layerName: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
centerCamera(runtimeScene, object, anticipateMove, layerName, cameraId);
|
||||
centerCamera(
|
||||
instanceContainer,
|
||||
object,
|
||||
anticipateMove,
|
||||
layerName,
|
||||
cameraId
|
||||
);
|
||||
clampCamera(
|
||||
runtimeScene,
|
||||
instanceContainer,
|
||||
left,
|
||||
top,
|
||||
right,
|
||||
@@ -259,7 +267,7 @@ namespace gdjs {
|
||||
};
|
||||
|
||||
export const clampCamera = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
left: float,
|
||||
top: float,
|
||||
right: float,
|
||||
@@ -267,10 +275,10 @@ namespace gdjs {
|
||||
layerName: string,
|
||||
cameraId: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layerName)) {
|
||||
if (!instanceContainer.hasLayer(layerName)) {
|
||||
return;
|
||||
}
|
||||
const layer = runtimeScene.getLayer(layerName);
|
||||
const layer = instanceContainer.getLayer(layerName);
|
||||
const cameraHalfWidth = layer.getCameraWidth(cameraId) / 2;
|
||||
const cameraHalfHeight = layer.getCameraHeight(cameraId) / 2;
|
||||
|
||||
@@ -304,165 +312,167 @@ namespace gdjs {
|
||||
|
||||
/**
|
||||
* Update a layer effect parameter (with a number).
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer the container owning the layer
|
||||
* @param layer The name of the layer
|
||||
* @param effect The name of the effect
|
||||
* @param parameter The parameter to update
|
||||
* @param value The new value
|
||||
*/
|
||||
export const setLayerEffectDoubleParameter = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
effect: string,
|
||||
parameter: string,
|
||||
value: float
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.setEffectDoubleParameter(effect, parameter, value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Update a layer effect parameter (with a string).
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer the container owning the layer
|
||||
* @param layer The name of the layer
|
||||
* @param effect The name of the effect
|
||||
* @param parameter The parameter to update
|
||||
* @param value The new value
|
||||
*/
|
||||
export const setLayerEffectStringParameter = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
effect: string,
|
||||
parameter: string,
|
||||
value: string
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.setEffectStringParameter(effect, parameter, value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Enable or disable a layer effect parameter (boolean).
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer the container owning the layer
|
||||
* @param layer The name of the layer
|
||||
* @param effect The name of the effect
|
||||
* @param parameter The parameter to update
|
||||
* @param value The new value
|
||||
*/
|
||||
export const setLayerEffectBooleanParameter = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
effect: string,
|
||||
parameter: string,
|
||||
value: boolean
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.setEffectBooleanParameter(effect, parameter, value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Enable, or disable, an effect of a layer.
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer the container owning the layer
|
||||
* @param layer The name of the layer
|
||||
* @param effect The name of the effect
|
||||
* @param enabled true to enable, false to disable.
|
||||
*/
|
||||
export const enableLayerEffect = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
effect: string,
|
||||
enabled: boolean
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
runtimeScene.getLayer(layer).enableEffect(effect, enabled);
|
||||
instanceContainer.getLayer(layer).enableEffect(effect, enabled);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if an effect is enabled.
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer the container owning the layer
|
||||
* @param layer The name of the layer
|
||||
* @param effect The name of the effect
|
||||
* @return true if the effect is enabled, false otherwise.
|
||||
*/
|
||||
export const layerEffectEnabled = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
effect: string
|
||||
): boolean {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return true;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).isEffectEnabled(effect);
|
||||
return instanceContainer.getLayer(layer).isEffectEnabled(effect);
|
||||
};
|
||||
|
||||
export const setLayerTimeScale = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
timeScale: float
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).setTimeScale(timeScale);
|
||||
return instanceContainer.getLayer(layer).setTimeScale(timeScale);
|
||||
};
|
||||
|
||||
export const getLayerTimeScale = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 1;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getTimeScale();
|
||||
return instanceContainer.getLayer(layer).getTimeScale();
|
||||
};
|
||||
|
||||
export const setLayerDefaultZOrder = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
defaultZOrder: integer
|
||||
) {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).setDefaultZOrder(defaultZOrder);
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.setDefaultZOrder(defaultZOrder);
|
||||
};
|
||||
|
||||
export const getLayerDefaultZOrder = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
if (!instanceContainer.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getDefaultZOrder();
|
||||
return instanceContainer.getLayer(layer).getDefaultZOrder();
|
||||
};
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene
|
||||
* @param instanceContainer the container owning the layer
|
||||
* @param layerName The lighting layer with the ambient color.
|
||||
* @param rgbColor The color, in RGB format ("128;200;255").
|
||||
*/
|
||||
export const setLayerAmbientLightColor = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layerName: string,
|
||||
rgbColor: string
|
||||
) {
|
||||
if (
|
||||
!runtimeScene.hasLayer(layerName) ||
|
||||
!runtimeScene.getLayer(layerName).isLightingLayer()
|
||||
!instanceContainer.hasLayer(layerName) ||
|
||||
!instanceContainer.getLayer(layerName).isLightingLayer()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -470,7 +480,7 @@ namespace gdjs {
|
||||
if (colors.length < 3) {
|
||||
return;
|
||||
}
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getLayer(layerName)
|
||||
.setClearColor(
|
||||
parseInt(colors[0], 10),
|
||||
@@ -478,21 +488,6 @@ namespace gdjs {
|
||||
parseInt(colors[2], 10)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param runtimeScene The scene
|
||||
* @param layer The name of the layer
|
||||
* @return the highest Z order of objects in the layer
|
||||
*/
|
||||
export const getLayerHighestZOrder = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
layer: string
|
||||
): number {
|
||||
if (!runtimeScene.hasLayer(layer)) {
|
||||
return 0;
|
||||
}
|
||||
return runtimeScene.getLayer(layer).getHighestZOrder();
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -144,9 +144,12 @@ namespace gdjs {
|
||||
* Return true if the specified key is pressed
|
||||
*
|
||||
*/
|
||||
export const isKeyPressed = function (runtimeScene, key) {
|
||||
export const isKeyPressed = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
key: string
|
||||
) {
|
||||
if (gdjs.evtTools.input.keysNameToCode.hasOwnProperty(key)) {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isKeyPressed(gdjs.evtTools.input.keysNameToCode[key]);
|
||||
@@ -158,9 +161,12 @@ namespace gdjs {
|
||||
* Return true if the specified key was just released
|
||||
*
|
||||
*/
|
||||
export const wasKeyReleased = function (runtimeScene, key) {
|
||||
export const wasKeyReleased = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
key: string
|
||||
) {
|
||||
if (gdjs.evtTools.input.keysNameToCode.hasOwnProperty(key)) {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.wasKeyReleased(gdjs.evtTools.input.keysNameToCode[key]);
|
||||
@@ -171,8 +177,10 @@ namespace gdjs {
|
||||
/**
|
||||
* Return the name of the last key pressed in the game
|
||||
*/
|
||||
export const lastPressedKey = function (runtimeScene) {
|
||||
const keyCode = runtimeScene
|
||||
export const lastPressedKey = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
const keyCode = instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.getLastPressedKey();
|
||||
@@ -182,29 +190,36 @@ namespace gdjs {
|
||||
return '';
|
||||
};
|
||||
|
||||
export const anyKeyPressed = function (runtimeScene) {
|
||||
return runtimeScene.getGame().getInputManager().anyKeyPressed();
|
||||
export const anyKeyPressed = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return instanceContainer.getGame().getInputManager().anyKeyPressed();
|
||||
};
|
||||
|
||||
export const anyKeyReleased = function (runtimeScene) {
|
||||
return runtimeScene.getGame().getInputManager().anyKeyReleased();
|
||||
export const anyKeyReleased = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return instanceContainer.getGame().getInputManager().anyKeyReleased();
|
||||
};
|
||||
|
||||
export const isMouseButtonPressed = function (runtimeScene, button) {
|
||||
export const isMouseButtonPressed = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
button: string
|
||||
) {
|
||||
if (button === 'Left') {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonPressed(0);
|
||||
}
|
||||
if (button === 'Right') {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonPressed(1);
|
||||
}
|
||||
if (button === 'Middle') {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonPressed(2);
|
||||
@@ -212,21 +227,24 @@ namespace gdjs {
|
||||
return false;
|
||||
};
|
||||
|
||||
export const isMouseButtonReleased = function (runtimeScene, button) {
|
||||
export const isMouseButtonReleased = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
button: string
|
||||
) {
|
||||
if (button === 'Left') {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonReleased(0);
|
||||
}
|
||||
if (button === 'Right') {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonReleased(1);
|
||||
}
|
||||
if (button === 'Middle') {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseButtonReleased(2);
|
||||
@@ -234,129 +252,178 @@ namespace gdjs {
|
||||
return false;
|
||||
};
|
||||
|
||||
export const hideCursor = function (runtimeScene) {
|
||||
runtimeScene.getRenderer().hideCursor();
|
||||
export const hideCursor = function (
|
||||
instanceContainer: gdjs.RuntimeScene
|
||||
) {
|
||||
instanceContainer.getScene().getRenderer().hideCursor();
|
||||
};
|
||||
|
||||
export const showCursor = function (runtimeScene) {
|
||||
runtimeScene.getRenderer().showCursor();
|
||||
export const showCursor = function (
|
||||
instanceContainer: gdjs.RuntimeScene
|
||||
) {
|
||||
instanceContainer.getScene().getRenderer().showCursor();
|
||||
};
|
||||
|
||||
export const getMouseWheelDelta = function (runtimeScene) {
|
||||
return runtimeScene.getGame().getInputManager().getMouseWheelDelta();
|
||||
export const getMouseWheelDelta = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.getMouseWheelDelta();
|
||||
};
|
||||
|
||||
export const isScrollingUp = function (runtimeScene) {
|
||||
return runtimeScene.getGame().getInputManager().isScrollingUp();
|
||||
export const isScrollingUp = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return instanceContainer.getGame().getInputManager().isScrollingUp();
|
||||
};
|
||||
|
||||
export const isScrollingDown = function (runtimeScene) {
|
||||
return runtimeScene.getGame().getInputManager().isScrollingDown();
|
||||
export const isScrollingDown = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return instanceContainer.getGame().getInputManager().isScrollingDown();
|
||||
};
|
||||
|
||||
export const getMouseX = function (runtimeScene, layer, camera) {
|
||||
return runtimeScene
|
||||
export const getMouseX = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
camera: integer
|
||||
) {
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
gdjs.evtTools.input.getMouseX
|
||||
) as FloatPoint;
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.convertCoords(
|
||||
runtimeScene.getGame().getInputManager().getMouseX(),
|
||||
runtimeScene.getGame().getInputManager().getMouseY()
|
||||
instanceContainer.getGame().getInputManager().getMouseX(),
|
||||
instanceContainer.getGame().getInputManager().getMouseY(),
|
||||
0,
|
||||
workingPoint
|
||||
)[0];
|
||||
};
|
||||
|
||||
export const getMouseY = function (runtimeScene, layer, camera) {
|
||||
return runtimeScene
|
||||
export const getMouseY = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
layer: string,
|
||||
camera: integer
|
||||
) {
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
gdjs.evtTools.input.getMouseY
|
||||
) as FloatPoint;
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.convertCoords(
|
||||
runtimeScene.getGame().getInputManager().getMouseX(),
|
||||
runtimeScene.getGame().getInputManager().getMouseY()
|
||||
instanceContainer.getGame().getInputManager().getMouseX(),
|
||||
instanceContainer.getGame().getInputManager().getMouseY(),
|
||||
0,
|
||||
workingPoint
|
||||
)[1];
|
||||
};
|
||||
|
||||
export const isMouseInsideCanvas = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return runtimeScene.getGame().getInputManager().isMouseInsideCanvas();
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.isMouseInsideCanvas();
|
||||
};
|
||||
|
||||
export const _cursorIsOnObject = function (obj, runtimeScene) {
|
||||
return obj.cursorOnObject(runtimeScene);
|
||||
export const _cursorIsOnObject = function (
|
||||
obj: gdjs.RuntimeObject,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
return obj.cursorOnObject(instanceContainer);
|
||||
};
|
||||
|
||||
export const cursorOnObject = function (
|
||||
objectsLists,
|
||||
runtimeScene,
|
||||
accurate,
|
||||
inverted
|
||||
objectsLists: Hashtable<gdjs.RuntimeObject[]>,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
accurate: boolean,
|
||||
inverted: boolean
|
||||
) {
|
||||
return gdjs.evtTools.object.pickObjectsIf(
|
||||
gdjs.evtTools.input._cursorIsOnObject,
|
||||
objectsLists,
|
||||
inverted,
|
||||
runtimeScene
|
||||
instanceContainer
|
||||
);
|
||||
};
|
||||
|
||||
export const getTouchX = function (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
identifier: integer,
|
||||
layer: string,
|
||||
camera: integer
|
||||
) {
|
||||
return runtimeScene
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
gdjs.evtTools.input.getTouchX
|
||||
) as FloatPoint;
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.convertCoords(
|
||||
runtimeScene.getGame().getInputManager().getTouchX(identifier),
|
||||
runtimeScene.getGame().getInputManager().getTouchY(identifier)
|
||||
instanceContainer.getGame().getInputManager().getTouchX(identifier),
|
||||
instanceContainer.getGame().getInputManager().getTouchY(identifier),
|
||||
0,
|
||||
workingPoint
|
||||
)[0];
|
||||
};
|
||||
|
||||
export const getTouchY = (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
identifier: integer,
|
||||
layer: string,
|
||||
camera: integer
|
||||
) => {
|
||||
return runtimeScene
|
||||
const workingPoint: FloatPoint = gdjs.staticArray(
|
||||
gdjs.evtTools.input.getTouchY
|
||||
) as FloatPoint;
|
||||
return instanceContainer
|
||||
.getLayer(layer)
|
||||
.convertCoords(
|
||||
runtimeScene.getGame().getInputManager().getTouchX(identifier),
|
||||
runtimeScene.getGame().getInputManager().getTouchY(identifier)
|
||||
instanceContainer.getGame().getInputManager().getTouchX(identifier),
|
||||
instanceContainer.getGame().getInputManager().getTouchY(identifier),
|
||||
0,
|
||||
workingPoint
|
||||
)[1];
|
||||
};
|
||||
|
||||
export const hasAnyTouchStarted = (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): boolean => {
|
||||
return (
|
||||
runtimeScene.getGame().getInputManager().getStartedTouchIdentifiers()
|
||||
.length > 0
|
||||
instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.getStartedTouchIdentifiers().length > 0
|
||||
);
|
||||
};
|
||||
|
||||
export const getStartedTouchCount = (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
): integer => {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.getStartedTouchIdentifiers().length;
|
||||
};
|
||||
|
||||
export const getStartedTouchIdentifier = (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
index: integer
|
||||
): integer => {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.getStartedTouchIdentifiers()[index];
|
||||
};
|
||||
|
||||
export const hasTouchEnded = (
|
||||
runtimeScene: gdjs.RuntimeScene,
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
identifier: integer
|
||||
): boolean => {
|
||||
return runtimeScene
|
||||
return instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.hasTouchEnded(identifier);
|
||||
@@ -380,9 +447,9 @@ namespace gdjs {
|
||||
* @deprecated
|
||||
*/
|
||||
export const popStartedTouch = function (
|
||||
runtimeScene: gdjs.RuntimeScene
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
const startedTouchId = runtimeScene
|
||||
const startedTouchId = instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.popStartedTouch();
|
||||
@@ -396,8 +463,10 @@ namespace gdjs {
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
export const popEndedTouch = function (runtimeScene: gdjs.RuntimeScene) {
|
||||
const endedTouchId = runtimeScene
|
||||
export const popEndedTouch = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer
|
||||
) {
|
||||
const endedTouchId = instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.popEndedTouch();
|
||||
@@ -408,8 +477,14 @@ namespace gdjs {
|
||||
return false;
|
||||
};
|
||||
|
||||
export const touchSimulateMouse = function (runtimeScene, enable) {
|
||||
runtimeScene.getGame().getInputManager().touchSimulateMouse(enable);
|
||||
export const touchSimulateMouse = function (
|
||||
instanceContainer: gdjs.RuntimeInstanceContainer,
|
||||
enable: boolean
|
||||
) {
|
||||
instanceContainer
|
||||
.getGame()
|
||||
.getInputManager()
|
||||
.touchSimulateMouse(enable);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user