Datasets:
before_code stringlengths 83 9.98k | reviewer_comment stringlengths 50 25.5k | language stringclasses 37 values | diff_context stringlengths 21 28.7k | after_code stringlengths 102 9.96k | repo_name stringclasses 406 values | file_path stringlengths 6 186 | comment_type stringclasses 5 values | quality_score float32 0.5 1 |
|---|---|---|---|---|---|---|---|---|
}
setCustomCenter(customCenterX, customCenterY) {
this._customCenterX = customCenterX;
this._customCenterY = customCenterY;
this.invalidateHitboxes();
}
getRendererObject() {
return null;
}
getWidth() {
return this._customWidth;
}
getHeight() {
return this._customHeight;
}
setWidth(width) {
this._customWidth = width;
}
setHeight(height) {
return this._customHeight = height;
}
getCenterX() {
if (this._customCenterX === null) return super.getCenterX();
return this._customCenterX;
}
getCenterY() {
if (this._customCenterY === null) return super.getCenterY();
return this._customCenterY;
}
};
gdjs.registerObject('TestSpriteObject::TestSpriteObject', gdjs.TestSpriteRuntimeObject);
| ```suggestion
this._customHeight = height;
``` | JavaScript | @@ -62,6 +62,14 @@
return this._customHeight;
}
+ setWidth(width) {
+ this._customWidth = width;
+ }
+
+ setHeight(height) {
+ return this._customHeight = height; | }
setCustomCenter(customCenterX, customCenterY) {
this._customCenterX = customCenterX;
this._customCenterY = customCenterY;
this.invalidateHitboxes();
}
getRendererObject() {
return null;
}
getWidth() {
return this._customWidth;
}
getHeight() {
return this._customHeight;
}
setWidth(width) {
this._customWidth = width;
}
setHeight(height) {
this._customHeight = height;
}
getCenterX() {
if (this._customCenterX === null) return super.getCenterX();
return this._customCenterX;
}
getCenterY() {
if (this._customCenterY === null) return super.getCenterY();
return this._customCenterY;
}
};
gdjs.registerObject('TestSpriteObject::TestSpriteObject', gdjs.TestSpriteRuntimeObject);
| 4ian/GDevelop | GDJS/tests/tests/Extensions/testspriteruntimeobject.js | suggestion | 0.571 |
case 'RotateCamera':
case 'ZoomCamera':
case 'FixCamera':
case 'CentreCamera':
return ['smooth-camera-movement'];
case 'ChangeTimeScale':
return ['pause-menu'];
case 'EcrireFichierExp':
case 'EcrireFichierTxt':
case 'LireFichierExp':
case 'LireFichierTxt':
case 'ReadNumberFromStorage':
case 'ReadStringFromStorage':
return ['intermediate-storage'];
case 'PlatformBehavior::SimulateJumpKey':
return ['simple-trampoline-platformer'];
case 'AjoutObjConcern':
case 'PickNearest':
case 'AjoutHasard':
return ['intermediate-object-picking'];
case 'ToggleObjectVariableAsBoolean':
case 'ToggleGlobalVariableAsBoolean':
case 'ToggleSceneVariableAsBoolean':
case 'SetBooleanObjectVariable':
case 'SetBooleanVariable':
return ['iIntermediate-toggle-states-with-variable'];
case 'Scene':
case 'PushScene':
case 'PopScene':
return ['intermediate-level-select-menu'];
case 'Animation':
case 'AnimationName':
case 'ChangeAnimation':
case 'ChangeAnimationName':
case 'AnimatableCapability::AnimatableBehavior::Index':
case 'AnimatableCapability::AnimatableBehavior::Name':
case 'AnimatableCapability::AnimatableBehavior::SetIndex':
case 'AnimatableCapability::AnimatableBehavior::SetName':
return ['intermediate-changing-animations'];
case 'PopStartedTouch':
case 'MouseButtonPressed':
case 'HasAnyTouchOrMouseStarted':
case 'HasTouchEnded':
return ['intermediate-touchscreen-controls'];
default:
return [];
}
};
| ```suggestion
return ['intermediate-toggle-states-with-variable'];
``` | JavaScript | @@ -124,6 +126,8 @@ export const getInstructionTutorialIds = (type: string): Array<string> => {
case 'ToggleObjectVariableAsBoolean':
case 'ToggleGlobalVariableAsBoolean':
case 'ToggleSceneVariableAsBoolean':
+ case 'SetBooleanObjectVariable':
+ case 'SetBooleanVariable':
return ['iIntermediate-toggle-states-with-variable']; | case 'RotateCamera':
case 'ZoomCamera':
case 'FixCamera':
case 'CentreCamera':
return ['smooth-camera-movement'];
case 'ChangeTimeScale':
return ['pause-menu'];
case 'EcrireFichierExp':
case 'EcrireFichierTxt':
case 'LireFichierExp':
case 'LireFichierTxt':
case 'ReadNumberFromStorage':
case 'ReadStringFromStorage':
return ['intermediate-storage'];
case 'PlatformBehavior::SimulateJumpKey':
return ['simple-trampoline-platformer'];
case 'AjoutObjConcern':
case 'PickNearest':
case 'AjoutHasard':
return ['intermediate-object-picking'];
case 'ToggleObjectVariableAsBoolean':
case 'ToggleGlobalVariableAsBoolean':
case 'ToggleSceneVariableAsBoolean':
case 'SetBooleanObjectVariable':
case 'SetBooleanVariable':
return ['intermediate-toggle-states-with-variable'];
case 'Scene':
case 'PushScene':
case 'PopScene':
return ['intermediate-level-select-menu'];
case 'Animation':
case 'AnimationName':
case 'ChangeAnimation':
case 'ChangeAnimationName':
case 'AnimatableCapability::AnimatableBehavior::Index':
case 'AnimatableCapability::AnimatableBehavior::Name':
case 'AnimatableCapability::AnimatableBehavior::SetIndex':
case 'AnimatableCapability::AnimatableBehavior::SetName':
return ['intermediate-changing-animations'];
case 'PopStartedTouch':
case 'MouseButtonPressed':
case 'HasAnyTouchOrMouseStarted':
case 'HasTouchEnded':
return ['intermediate-touchscreen-controls'];
default:
return [];
}
};
| 4ian/GDevelop | newIDE/app/src/Utils/GDevelopServices/Tutorial.js | suggestion | 0.571 |
// @flow
export default function getObjectByName(
globalObjectsContainer: gdObjectsContainer | null,
objectsContainer?: ?gdObjectsContainer,
objectName: string
): ?gdObject {
if (objectsContainer && objectsContainer.hasObjectNamed(objectName))
return objectsContainer.getObject(objectName);
else if (
globalObjectsContainer &&
globalObjectsContainer.hasObjectNamed(objectName)
)
return globalObjectsContainer.getObject(objectName);
return null;
}
export const hasObjectWithName = (
globalObjectsContainer: gdObjectsContainer | null,
objectsContainer?: ?gdObjectsContainer,
objectName: string
): boolean => {
if (objectsContainer && objectsContainer.hasObjectNamed(objectName))
return true;
else if (
globalObjectsContainer &&
globalObjectsContainer.hasObjectNamed(objectName)
)
return true;
return false;
};
| `ObjectsContainersList` should be used instead. You can pass a `ProjectScopedContainersAccessor` to your component. | JavaScript | @@ -15,3 +15,18 @@ export default function getObjectByName(
return null;
}
+
+export const hasObjectWithName = (
+ globalObjectsContainer: gdObjectsContainer | null,
+ objectsContainer?: ?gdObjectsContainer,
+ objectName: string
+): boolean => { | // @flow
export default function getObjectByName(
globalObjectsContainer: gdObjectsContainer | null,
objectsContainer?: ?gdObjectsContainer,
objectName: string
): ?gdObject {
if (objectsContainer && objectsContainer.hasObjectNamed(objectName))
return objectsContainer.getObject(objectName);
else if (
globalObjectsContainer &&
globalObjectsContainer.hasObjectNamed(objectName)
)
return globalObjectsContainer.getObject(objectName);
return null;
}
| 4ian/GDevelop | newIDE/app/src/Utils/GetObjectByName.js | suggestion | 0.571 |
>
<QuickPublish
project={testProject.project}
gameAndBuildsManager={fakeEmptyGameAndBuildsManager}
isSavingProject={false}
isRequiredToSaveAsNewCloudProject={() =>
// Indicates that the project is already saved, there will be
// no need to save it as a new cloud project.
false
}
onSaveProject={async () => {}}
onlineWebExporter={onlineWebExporter}
setIsNavigationDisabled={() => {}}
onClose={action('onClose')}
onContinueQuickCustomization={action('onContinueQuickCustomization')}
onTryAnotherGame={action('onTryAnotherGame')}
/>
</AuthenticatedUserContext.Provider>
</Template>
);
};
export const AuthenticatedAndLoadingUserCloudProjects = () => {
return (
<Template>
<AuthenticatedUserContext.Provider
value={{
...fakeAuthenticatedUserWithNoSubscriptionAndCredits,
cloudProjects: null,
}}
>
<QuickPublish
project={testProject.project}
gameAndBuildsManager={fakeEmptyGameAndBuildsManager}
isSavingProject={false}
isRequiredToSaveAsNewCloudProject={() => true}
onSaveProject={async () => {}}
onlineWebExporter={onlineWebExporter}
setIsNavigationDisabled={() => {}}
onClose={action('onClose')}
onContinueQuickCustomization={action('onContinueQuickCustomization')}
onTryAnotherGame={action('onTryAnotherGame')}
/>
</AuthenticatedUserContext.Provider>
</Template>
);
};
export const AuthenticatedAndFails = () => {
return (
<Template> | I feel like this comment should be next to the props type in QuickPublish. I was not sure what it meant before reading this comment | JavaScript | @@ -119,6 +124,39 @@ export const AuthenticatedWithTooManyCloudProjects = () => {
</Template>
);
};
+
+export const AuthenticatedWithCloudProjectsMaximumReachedButSavedAlready = () => {
+ return (
+ <Template>
+ <AuthenticatedUserContext.Provider
+ value={{
+ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits,
+ // We have more projects than the maximum allowed, but the project is already saved
+ // so there are no problems.
+ cloudProjects: tenCloudProjects,
+ }}
+ >
+ <QuickPublish
+ project={testProject.project}
+ gameAndBuildsManager={fakeEmptyGameAndBuildsManager}
+ isSavingProject={false}
+ isRequiredToSaveAsNewCloudProject={() =>
+ // Indicates that the project is already saved, there will be | onClose={action('onClose')}
onContinueQuickCustomization={action('onContinueQuickCustomization')}
onTryAnotherGame={action('onTryAnotherGame')}
/>
</AuthenticatedUserContext.Provider>
</Template>
);
};
export const AuthenticatedWithCloudProjectsMaximumReachedButSavedAlready = () => {
return (
<Template>
<AuthenticatedUserContext.Provider
value={{
...fakeAuthenticatedUserWithNoSubscriptionAndCredits,
// We have more projects than the maximum allowed, but the project is already saved
// so there are no problems.
cloudProjects: tenCloudProjects,
}}
>
<QuickPublish
project={testProject.project}
gameAndBuildsManager={fakeGameAndBuildsManager}
isSavingProject={false}
isRequiredToSaveAsNewCloudProject={() =>
// Indicates that the project is already saved, there will be
// no need to save it as a new cloud project.
false
}
onSaveProject={async () => {}}
onlineWebExporter={onlineWebExporter}
setIsNavigationDisabled={() => {}}
onClose={action('onClose')}
onContinueQuickCustomization={action('onContinueQuickCustomization')}
onTryAnotherGame={action('onTryAnotherGame')}
/>
</AuthenticatedUserContext.Provider>
</Template>
);
};
export const AuthenticatedAndLoadingUserCloudProjects = () => {
return (
<Template>
<AuthenticatedUserContext.Provider
value={{
...fakeAuthenticatedUserWithNoSubscriptionAndCredits,
cloudProjects: null,
}}
>
<QuickPublish | 4ian/GDevelop | newIDE/app/src/stories/componentStories/QuickCustomization/QuickPublish.stories.js | suggestion | 0.571 |
if (!selectedItem) return;
if (selectedItem.content.isDescendantOf(item.content)) {
selectObjectFolderOrObjectWithContext(null);
}
},
[selectObjectFolderOrObjectWithContext, selectedItems]
);
// Force List component to be mounted again if project or objectsContainer
// has been changed. Avoid accessing to invalid objects that could
// crash the app.
const listKey = project.ptr + ';' + objectsContainer.ptr;
const initiallyOpenedNodeIds = [
globalObjectsRootFolder && globalObjectsRootFolder.getChildrenCount() > 0
? globalObjectsRootFolderId
: null,
sceneObjectsRootFolderId,
].filter(Boolean);
const arrowKeyNavigationProps = React.useMemo(
() => ({
onGetItemInside: (item: TreeViewItem): ?TreeViewItem => {
if (item.isPlaceholder || item.isRoot) return null;
const objectFolderOrObject = item.content.getObjectFolderOrObject();
if (!objectFolderOrObject) return null;
if (!objectFolderOrObject.isFolder()) return null;
else {
if (objectFolderOrObject.getChildrenCount() === 0) return null;
return createTreeViewItem({
objectFolderOrObject: objectFolderOrObject.getChildAt(0),
isGlobal: item.content.isGlobal(),
objectFolderTreeViewItemProps,
objectTreeViewItemProps,
});
}
},
onGetItemOutside: (item: TreeViewItem): ?TreeViewItem => {
if (item.isPlaceholder || item.isRoot) return null;
const objectFolderOrObject = item.content.getObjectFolderOrObject();
if (!objectFolderOrObject) return null;
const parent = objectFolderOrObject.getParent();
if (parent.isRootFolder()) return null;
return createTreeViewItem({
objectFolderOrObject: parent,
isGlobal: item.content.isGlobal(),
objectFolderTreeViewItemProps,
objectTreeViewItemProps,
});
},
}),
[objectFolderTreeViewItemProps, objectTreeViewItemProps] | Removing the column, you removed the margin, you should maybe remove the `noMargin` in the child Column | JavaScript | @@ -1363,28 +1393,16 @@ const ObjectsList = React.forwardRef<Props, ObjectsListInterface>(
return (
<Background maxWidth>
- <Column> | * does not stay selected and not visible to the user.
*/
const onCollapseItem = React.useCallback(
(item: TreeViewItem) => {
if (!selectedItems || selectedItems.length !== 1) return;
const selectedItem = selectedItems[0];
if (!selectedItem) return;
if (selectedItem.content.isDescendantOf(item.content)) {
selectObjectFolderOrObjectWithContext(null);
}
},
[selectObjectFolderOrObjectWithContext, selectedItems]
);
// Force List component to be mounted again if project or objectsContainer
// has been changed. Avoid accessing to invalid objects that could
// crash the app.
const listKey = project.ptr + ';' + objectsContainer.ptr;
const initiallyOpenedNodeIds = [
globalObjectsRootFolder && globalObjectsRootFolder.getChildrenCount() > 0
? globalObjectsRootFolderId
: null,
sceneObjectsRootFolderId,
].filter(Boolean);
const arrowKeyNavigationProps = React.useMemo(
() => ({
onGetItemInside: (item: TreeViewItem): ?TreeViewItem => {
if (item.isPlaceholder || item.isRoot) return null;
const objectFolderOrObject = item.content.getObjectFolderOrObject();
if (!objectFolderOrObject) return null;
if (!objectFolderOrObject.isFolder()) return null;
else {
if (objectFolderOrObject.getChildrenCount() === 0) return null;
return createTreeViewItem({
objectFolderOrObject: objectFolderOrObject.getChildAt(0),
isGlobal: item.content.isGlobal(),
objectFolderTreeViewItemProps,
objectTreeViewItemProps,
});
}
},
onGetItemOutside: (item: TreeViewItem): ?TreeViewItem => {
if (item.isPlaceholder || item.isRoot) return null;
const objectFolderOrObject = item.content.getObjectFolderOrObject();
if (!objectFolderOrObject) return null;
const parent = objectFolderOrObject.getParent();
if (parent.isRootFolder()) return null;
return createTreeViewItem({
objectFolderOrObject: parent,
isGlobal: item.content.isGlobal(), | 4ian/GDevelop | newIDE/app/src/ObjectsList/index.js | suggestion | 0.571 |
this._loadedTextures.clear();
const threeTextures: THREE.Texture[] = [];
this._loadedThreeTextures.values(threeTextures);
this._loadedThreeTextures.clear();
for (const threeTexture of threeTextures) {
threeTexture.dispose();
}
const threeMaterials: THREE.Material[] = [];
this._loadedThreeMaterials.values(threeMaterials);
this._loadedThreeMaterials.clear();
for (const threeMaterial of threeMaterials) {
threeMaterial.dispose();
}
const diskPixiTextures = [...this._diskTextures.values()];
this._diskTextures.clear();
for (const pixiTexture of diskPixiTextures) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
const rectanglePixiTextures = [...this._rectangleTextures.values()];
this._rectangleTextures.clear();
for (const pixiTexture of rectanglePixiTextures) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
const scaledPixiTextures = [...this._scaledTextures.values()];
this._scaledTextures.clear();
for (const pixiTexture of scaledPixiTextures) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
}
}
//Register the class to let the engine use it.
export const ImageManager = gdjs.PixiImageManager;
export type ImageManager = gdjs.PixiImageManager; | Will this work?
```
for (const pixiTexture of this._diskTextures.values()) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
this._diskTextures.clear();
```
Minus new array creation. | TypeScript | @@ -463,6 +463,54 @@ namespace gdjs {
}
return particleTexture;
}
+
+ dispose(): void {
+ this._loadedTextures.clear();
+
+ const threeTextures: THREE.Texture[] = [];
+ this._loadedThreeTextures.values(threeTextures);
+ this._loadedThreeTextures.clear();
+ for (const threeTexture of threeTextures) {
+ threeTexture.dispose();
+ }
+
+ const threeMaterials: THREE.Material[] = [];
+ this._loadedThreeMaterials.values(threeMaterials);
+ this._loadedThreeMaterials.clear();
+ for (const threeMaterial of threeMaterials) {
+ threeMaterial.dispose();
+ }
+
+ const diskPixiTextures = [...this._diskTextures.values()];
+ this._diskTextures.clear();
+ for (const pixiTexture of diskPixiTextures) {
+ if (pixiTexture.destroyed) {
+ continue;
+ }
+
+ pixiTexture.destroy();
+ } | * To be called when the game is disposed.
* Clear caches of loaded textures and materials.
*/
dispose(): void {
this._loadedTextures.clear();
const threeTextures: THREE.Texture[] = [];
this._loadedThreeTextures.values(threeTextures);
this._loadedThreeTextures.clear();
for (const threeTexture of threeTextures) {
threeTexture.dispose();
}
const threeMaterials: THREE.Material[] = [];
this._loadedThreeMaterials.values(threeMaterials);
this._loadedThreeMaterials.clear();
for (const threeMaterial of threeMaterials) {
threeMaterial.dispose();
}
for (const pixiTexture of this._diskTextures.values()) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
this._diskTextures.clear();
for (const pixiTexture of this._rectangleTextures.values()) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
this._rectangleTextures.clear();
for (const pixiTexture of this._scaledTextures.values()) {
if (pixiTexture.destroyed) {
continue;
}
pixiTexture.destroy();
}
this._scaledTextures.clear();
}
}
//Register the class to let the engine use it.
export const ImageManager = gdjs.PixiImageManager; | 4ian/GDevelop | GDJS/Runtime/pixi-renderers/pixi-image-manager.ts | suggestion | 0.786 |
/**
* @brief Return the scene variables of the current scene or the current
* extension. It allows legacy "scenevar" parameters to accept extension
* variables.
*/
const gd::VariablesContainer &GetLegacySceneVariables() const {
return legacySceneVariables;
};
const gd::PropertiesContainersList &GetPropertiesContainersList() const {
return propertiesContainersList;
};
const std::vector<const ParameterMetadataContainer *> &GetParametersVectorsList() const {
return parametersVectorsList;
};
/** Do not use - should be private but accessible to let Emscripten create a
* temporary. */
ProjectScopedContainers(){};
private:
gd::ObjectsContainersList objectsContainersList;
gd::VariablesContainersList variablesContainersList;
gd::VariablesContainer legacyGlobalVariables;
gd::VariablesContainer legacySceneVariables;
gd::PropertiesContainersList propertiesContainersList;
std::vector<const ParameterMetadataContainer *> parametersVectorsList;
};
} // namespace gd | These are not references/pointers but values, meaning that ProjectScopedContainers moved from "I'm just a set of lists pointing to things in your project" to "I actually hold stuff, and you will have a bad time if you destroyed me and kept references to things". | C/C++ | @@ -236,6 +230,8 @@ class ProjectScopedContainers {
private:
gd::ObjectsContainersList objectsContainersList;
gd::VariablesContainersList variablesContainersList;
+ gd::VariablesContainer legacyGlobalVariables;
+ gd::VariablesContainer legacySceneVariables; | /**
* @brief Return the scene variables of the current scene or the current
* extension. It allows legacy "scenevar" parameters to accept extension
* variables.
*/
const gd::VariablesContainer *GetLegacySceneVariables() const {
return legacySceneVariables;
};
const gd::PropertiesContainersList &GetPropertiesContainersList() const {
return propertiesContainersList;
};
const std::vector<const ParameterMetadataContainer *> &GetParametersVectorsList() const {
return parametersVectorsList;
};
/** Do not use - should be private but accessible to let Emscripten create a
* temporary. */
ProjectScopedContainers(){};
private:
gd::ObjectsContainersList objectsContainersList;
gd::VariablesContainersList variablesContainersList;
const gd::VariablesContainer *legacyGlobalVariables;
const gd::VariablesContainer *legacySceneVariables;
gd::PropertiesContainersList propertiesContainersList;
std::vector<const ParameterMetadataContainer *> parametersVectorsList;
};
} // namespace gd | 4ian/GDevelop | Core/GDCore/Project/ProjectScopedContainers.h | suggestion | 0.5 |
// We could pass it a string, but lets do it right
this.removeJoint(parseInt(jId, 10));
}
}
}
}
// Remove the joint
this.world.DestroyJoint(joint);
delete this.joints[jointId];
}
}
}
gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) {
if (
// @ts-ignore
runtimeScene.physics2SharedData &&
// @ts-ignore
runtimeScene.physics2SharedData.world
) {
// @ts-ignore
Box2D.destroy(runtimeScene.physics2SharedData.world);
}
});
export class Physics2RuntimeBehavior extends gdjs.RuntimeBehavior {
bodyType: string;
bullet: boolean;
fixedRotation: boolean;
canSleep: boolean;
shape: string;
shapeDimensionA: any;
shapeDimensionB: any;
shapeOffsetX: float;
shapeOffsetY: float;
polygonOrigin: string;
polygon: gdjs.Polygon | null;
density: float;
friction: float;
restitution: float;
linearDamping: float;
angularDamping: float;
gravityScale: float;
layers: integer;
masks: integer;
shapeScale: number = 1;
/**
* Array containing the beginning of contacts reported by onContactBegin. Each contact
* should be unique to avoid recording glitches where the object loses and regain
* contact between two frames. The array is updated each time the method | In the future, a `destroy()` method on the shared data would be I think safer (in the sense: it's part of the class, so there is less chance you forget to update it when needed) and we we should probably made the "shared data" something first class that is handled by the runtime scene (rather than something that is manually handled by the behavior like now). | TypeScript | @@ -300,14 +309,11 @@ namespace gdjs {
}
}
gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) {
- if (
- // @ts-ignore
- runtimeScene.physics2SharedData &&
- // @ts-ignore
- runtimeScene.physics2SharedData.world
- ) {
- // @ts-ignore
- Box2D.destroy(runtimeScene.physics2SharedData.world);
+ const physics2SharedData = runtimeScene.physics2SharedData;
+ if (physics2SharedData && physics2SharedData.world) {
+ Box2D.destroy(physics2SharedData.world); | if (
this.joints[jId].GetType() === Box2D.e_gearJoint &&
(Box2D.getPointer(
(this.joints[jId] as Box2D.b2GearJoint).GetJoint1()
) === Box2D.getPointer(joint) ||
Box2D.getPointer(
(this.joints[jId] as Box2D.b2GearJoint).GetJoint2()
) === Box2D.getPointer(joint))
) {
// We could pass it a string, but lets do it right
this.removeJoint(parseInt(jId, 10));
}
}
}
}
// Remove the joint
this.world.DestroyJoint(joint);
delete this.joints[jointId];
}
}
}
gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) {
const physics2SharedData = runtimeScene.physics2SharedData;
if (physics2SharedData && physics2SharedData.world) {
Box2D.destroy(physics2SharedData.world);
Box2D.destroy(physics2SharedData._tempb2Vec2);
Box2D.destroy(physics2SharedData._tempb2Vec2Sec);
}
});
export class Physics2RuntimeBehavior extends gdjs.RuntimeBehavior {
bodyType: string;
bullet: boolean;
fixedRotation: boolean;
canSleep: boolean;
shape: string;
shapeDimensionA: any;
shapeDimensionB: any;
shapeOffsetX: float;
shapeOffsetY: float;
polygonOrigin: string;
polygon: gdjs.Polygon | null;
density: float;
friction: float;
restitution: float;
linearDamping: float;
angularDamping: float;
gravityScale: float;
layers: integer;
masks: integer; | 4ian/GDevelop | Extensions/Physics2Behavior/physics2runtimebehavior.ts | suggestion | 0.786 |
} catch (error) {
console.error('Error while login:', error);
throw error;
}
}
async loginOrSignupWithProvider({
provider,
signal,
}: {|
provider: IdentityProvider,
signal?: AbortSignal,
|}) {
if (signal && signal.aborted) {
return Promise.reject(
new UserCancellationError(
'Login or Signup with provider already aborted.'
)
);
}
const promise = new Promise((resolve, reject) => {
// Listen for abort event on signal
if (signal) {
signal.addEventListener('abort', () => {
terminateWebSocket();
});
}
setupAuthenticationWebSocket({
onConnectionEstablished: connectionId => {
if (signal && signal.aborted) return;
const url = new URL(authenticationPortalUrl);
url.searchParams.set('connection-id', connectionId);
url.searchParams.set('provider', provider);
url.searchParams.set('env', isDev ? 'dev' : 'live');
Window.openExternalURL(url.toString());
},
onTokenReceived: async ({
provider,
data,
}: {|
provider: 'apple' | 'google' | 'github',
data: any,
|}) => {
if (signal && signal.aborted) return;
try {
const credential =
provider === 'google'
? GoogleAuthProvider.credential(data.credential)
: provider === 'github'
? GithubAuthProvider.credential(data.accessToken)
: new OAuthProvider('apple.com').credential({ | this seemed duplicated in this file and the browser one.
This was always causing an error in the console because the signal always aborts (we trigger it when we close the dialog)
I don't think this deserves to raise an error as it's the expected path? | JavaScript | @@ -61,11 +61,6 @@ class LocalLoginProvider implements LoginProvider, FirebaseBasedLoginProvider {
if (signal) {
signal.addEventListener('abort', () => {
terminateWebSocket();
- reject( | } catch (error) {
console.error('Error while login:', error);
throw error;
}
}
async loginOrSignupWithProvider({
provider,
signal,
}: {|
provider: IdentityProvider,
signal?: AbortSignal,
|}) {
if (signal && signal.aborted) {
return Promise.reject(
new UserCancellationError(
'Login or Signup with provider already aborted.'
)
);
}
const promise = new Promise((resolve, reject) => {
// Listen for abort event on signal
if (signal) {
signal.addEventListener('abort', () => {
terminateWebSocket();
reject(
new UserCancellationError(
'Login or Signup with provider already aborted.'
)
);
});
}
setupAuthenticationWebSocket({
onConnectionEstablished: connectionId => {
if (signal && signal.aborted) return;
const url = new URL(authenticationPortalUrl);
url.searchParams.set('connection-id', connectionId);
url.searchParams.set('provider', provider);
url.searchParams.set('env', isDev ? 'dev' : 'live');
Window.openExternalURL(url.toString());
},
onTokenReceived: async ({
provider,
data,
}: {|
provider: 'apple' | 'google' | 'github',
data: any,
|}) => {
if (signal && signal.aborted) return;
try {
const credential = | 4ian/GDevelop | newIDE/app/src/LoginProvider/LocalLoginProvider.js | refactor | 0.643 |
},
});
}
}
this.setState({
createAccountInProgress: false,
loginInProgress: false,
authenticatedUser: {
...this.state.authenticatedUser,
creatingOrLoggingInAccount: false,
},
});
this._automaticallyUpdateUserProfile = true;
};
_cancelLoginOrSignUp = () => {
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
}
this.setState({
loginInProgress: false,
createAccountInProgress: false,
authenticatedUser: {
...this.state.authenticatedUser,
creatingOrLoggingInAccount: false,
},
});
};
_doLogin = async (form: LoginForm) => {
const { authentication } = this.props;
if (!authentication) return;
this.setState({
loginInProgress: true,
apiCallError: null,
authenticatedUser: {
...this.state.authenticatedUser,
creatingOrLoggingInAccount: true,
authenticationError: null,
},
});
this._automaticallyUpdateUserProfile = false;
try {
await authentication.login(form);
await this._fetchUserProfileWithoutThrowingErrors({ resetState: true });
this.openLoginDialog(false);
this._showLoginSnackbar(this.state.authenticatedUser);
} catch (apiCallError) {
this.setState({ | I don't like doing this here. It looks like we're trying to "finish a process". But the process is already there:
<img width="776" alt="image" src="https://github.com/user-attachments/assets/6fe5b8b4-8d4c-4124-b83a-34f6d90bbd83">
There is already a catch (ensuring that an exception will never stop the end to run) and at the end we set the boolean back to false. | JavaScript | @@ -996,11 +996,19 @@ export default class AuthenticatedUserProvider extends React.Component<
this._automaticallyUpdateUserProfile = true;
};
- _cancelLogin = () => {
+ _cancelLoginOrSignUp = () => {
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
}
+ this.setState({
+ loginInProgress: false,
+ createAccountInProgress: false,
+ authenticatedUser: {
+ ...this.state.authenticatedUser,
+ creatingOrLoggingInAccount: false, | },
});
}
}
this.setState({
createAccountInProgress: false,
loginInProgress: false,
authenticatedUser: {
...this.state.authenticatedUser,
creatingOrLoggingInAccount: false,
},
});
this._automaticallyUpdateUserProfile = true;
};
_cancelLoginOrSignUp = () => {
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
}
};
_doLogin = async (form: LoginForm) => {
const { authentication } = this.props;
if (!authentication) return;
this.setState({
loginInProgress: true,
apiCallError: null,
authenticatedUser: {
...this.state.authenticatedUser,
creatingOrLoggingInAccount: true,
authenticationError: null,
},
});
this._automaticallyUpdateUserProfile = false;
try {
await authentication.login(form);
await this._fetchUserProfileWithoutThrowingErrors({ resetState: true });
this.openLoginDialog(false);
this._showLoginSnackbar(this.state.authenticatedUser);
} catch (apiCallError) {
this.setState({
apiCallError,
authenticatedUser: {
...this.state.authenticatedUser,
authenticationError: apiCallError,
},
});
}
this.setState({ | 4ian/GDevelop | newIDE/app/src/Profile/AuthenticatedUserProvider.js | suggestion | 0.643 |
preferences.getIsMenuBarHiddenInPreview,
preferences.getIsAlwaysOnTopInPreview,
preferences.values.openDiagnosticReportAutomatically,
currentlyRunningInAppTutorial,
getAuthenticatedPlayerForPreview,
quickCustomizationDialogOpenedFromGameId,
onCaptureFinished,
createCaptureOptionsForPreview,
]
);
const launchPreview = addCreateBadgePreHookIfNotClaimed(
authenticatedUser,
TRIVIAL_FIRST_PREVIEW,
_launchPreview
);
const launchNewPreview = React.useCallback(
async options => {
const numberOfWindows = options ? options.numberOfWindows : 1;
await launchPreview({ networkPreview: false, numberOfWindows });
},
[launchPreview]
);
const launchPreviewWithScreenshot = React.useCallback(
() =>
launchPreview({
networkPreview: false,
hotReload: false,
launchCaptureOptions: {
screenshots: [
{ delayTimeInSeconds: 3000 }, // Take only 1 screenshot per preview.
],
},
}),
[launchPreview]
);
const launchHotReloadPreview = React.useCallback(
() =>
launchPreview({
networkPreview: false,
hotReload: true,
}),
[launchPreview]
);
const launchNetworkPreview = React.useCallback(
() => launchPreview({ networkPreview: true, hotReload: false }),
[launchPreview] | Consider not adding yet-another-way-to-launch-preview and instead:
- Make the logic related to the timing inside the existing function.
- delayTimeInSeconds can also be in the function
- forcing a screenshot, bypassing the check for timing, is "just" a "forceScreenshot: true". But this is only used for quick customization. For normal previews, the buttons are unchanged. | JavaScript | @@ -1723,13 +1724,31 @@ const MainFrame = (props: Props) => {
const launchNewPreview = React.useCallback(
async options => {
const numberOfWindows = options ? options.numberOfWindows : 1;
- launchPreview({ networkPreview: false, numberOfWindows });
+ await launchPreview({ networkPreview: false, numberOfWindows });
},
[launchPreview]
);
+ const launchPreviewWithScreenshot = React.useCallback( | preferences.getIsMenuBarHiddenInPreview,
preferences.getIsAlwaysOnTopInPreview,
preferences.values.openDiagnosticReportAutomatically,
currentlyRunningInAppTutorial,
getAuthenticatedPlayerForPreview,
quickCustomizationDialogOpenedFromGameId,
onCaptureFinished,
createCaptureOptionsForPreview,
]
);
const launchPreview = addCreateBadgePreHookIfNotClaimed(
authenticatedUser,
TRIVIAL_FIRST_PREVIEW,
_launchPreview
);
const launchNewPreview = React.useCallback(
async options => {
const numberOfWindows = options ? options.numberOfWindows : 1;
await launchPreview({ networkPreview: false, numberOfWindows });
},
[launchPreview]
);
const launchHotReloadPreview = React.useCallback(
async () => {
const launchCaptureOptions = currentProject
? getHotReloadPreviewLaunchCaptureOptions(
currentProject.getProjectUuid()
)
: undefined;
await launchPreview({
networkPreview: false,
hotReload: true,
launchCaptureOptions,
});
},
[currentProject, launchPreview, getHotReloadPreviewLaunchCaptureOptions]
);
const launchNetworkPreview = React.useCallback(
() => launchPreview({ networkPreview: true, hotReload: false }),
[launchPreview]
);
const launchPreviewWithDiagnosticReport = React.useCallback(
() => launchPreview({ forceDiagnosticReport: true }),
[launchPreview]
);
| 4ian/GDevelop | newIDE/app/src/MainFrame/index.js | suggestion | 0.5 |
for (std::size_t c = 0; c < GetCameraCount(); ++c) {
SerializerElement& cameraElement = camerasElement.AddChild("camera");
cameraElement.SetAttribute("defaultSize", GetCamera(c).UseDefaultSize());
cameraElement.SetAttribute("width", GetCamera(c).GetWidth());
cameraElement.SetAttribute("height", GetCamera(c).GetHeight());
cameraElement.SetAttribute("defaultViewport",
GetCamera(c).UseDefaultViewport());
cameraElement.SetAttribute("viewportLeft", GetCamera(c).GetViewportX1());
cameraElement.SetAttribute("viewportTop", GetCamera(c).GetViewportY1());
cameraElement.SetAttribute("viewportRight", GetCamera(c).GetViewportX2());
cameraElement.SetAttribute("viewportBottom", GetCamera(c).GetViewportY2());
}
SerializerElement& effectsElement = element.AddChild("effects");
effectsContainer.SerializeTo(effectsElement);
}
/**
* \brief Unserialize the layer.
*/
void Layer::UnserializeFrom(const SerializerElement& element) {
SetName(element.GetStringAttribute("name", "", "Name"));
SetRenderingType(element.GetStringAttribute("renderingType", ""));
SetCameraType(element.GetStringAttribute("cameraType", "perspective"));
SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "keep-top-left-fixed-if-never-moved"));
SetVisibility(element.GetBoolAttribute("visibility", true, "Visibility"));
SetLocked(element.GetBoolAttribute("isLocked", false));
SetLightingLayer(element.GetBoolAttribute("isLightingLayer", false));
SetFollowBaseLayerCamera(
element.GetBoolAttribute("followBaseLayerCamera", false));
SetAmbientLightColor(element.GetIntAttribute("ambientLightColorR", 200),
element.GetIntAttribute("ambientLightColorG", 200),
element.GetIntAttribute("ambientLightColorB", 200));
SetCamera3DNearPlaneDistance(element.GetDoubleAttribute(
"camera3DNearPlaneDistance", 0.1, "threeDNearPlaneDistance"));
SetCamera3DFarPlaneDistance(element.GetDoubleAttribute(
"camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance"));
SetCamera3DFieldOfView(element.GetDoubleAttribute(
"camera3DFieldOfView", 45, "threeDFieldOfView"));
cameras.clear();
SerializerElement& camerasElement = element.GetChild("cameras");
camerasElement.ConsiderAsArrayOf("camera");
for (std::size_t i = 0; i < camerasElement.GetChildrenCount(); ++i) {
const SerializerElement& cameraElement = camerasElement.GetChild(i);
Camera camera;
camera.SetUseDefaultSize(
cameraElement.GetBoolAttribute("defaultSize", true));
camera.SetSize(cameraElement.GetDoubleAttribute("width"),
| to make it a bit shorter
```suggestion
SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "top-left-anchored-if-never-moved"));
``` | C++ | @@ -80,6 +84,7 @@ void Layer::UnserializeFrom(const SerializerElement& element) {
SetName(element.GetStringAttribute("name", "", "Name"));
SetRenderingType(element.GetStringAttribute("renderingType", ""));
SetCameraType(element.GetStringAttribute("cameraType", "perspective"));
+ SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "keep-top-left-fixed-if-never-moved"));
| for (std::size_t c = 0; c < GetCameraCount(); ++c) {
SerializerElement& cameraElement = camerasElement.AddChild("camera");
cameraElement.SetAttribute("defaultSize", GetCamera(c).UseDefaultSize());
cameraElement.SetAttribute("width", GetCamera(c).GetWidth());
cameraElement.SetAttribute("height", GetCamera(c).GetHeight());
cameraElement.SetAttribute("defaultViewport",
GetCamera(c).UseDefaultViewport());
cameraElement.SetAttribute("viewportLeft", GetCamera(c).GetViewportX1());
cameraElement.SetAttribute("viewportTop", GetCamera(c).GetViewportY1());
cameraElement.SetAttribute("viewportRight", GetCamera(c).GetViewportX2());
cameraElement.SetAttribute("viewportBottom", GetCamera(c).GetViewportY2());
}
SerializerElement& effectsElement = element.AddChild("effects");
effectsContainer.SerializeTo(effectsElement);
}
/**
* \brief Unserialize the layer.
*/
void Layer::UnserializeFrom(const SerializerElement& element) {
SetName(element.GetStringAttribute("name", "", "Name"));
SetRenderingType(element.GetStringAttribute("renderingType", ""));
SetCameraType(element.GetStringAttribute("cameraType", "perspective"));
SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "top-left-anchored-if-never-moved"));
SetVisibility(element.GetBoolAttribute("visibility", true, "Visibility"));
SetLocked(element.GetBoolAttribute("isLocked", false));
SetLightingLayer(element.GetBoolAttribute("isLightingLayer", false));
SetFollowBaseLayerCamera(
element.GetBoolAttribute("followBaseLayerCamera", false));
SetAmbientLightColor(element.GetIntAttribute("ambientLightColorR", 200),
element.GetIntAttribute("ambientLightColorG", 200),
element.GetIntAttribute("ambientLightColorB", 200));
SetCamera3DNearPlaneDistance(element.GetDoubleAttribute(
"camera3DNearPlaneDistance", 0.1, "threeDNearPlaneDistance"));
SetCamera3DFarPlaneDistance(element.GetDoubleAttribute(
"camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance"));
SetCamera3DFieldOfView(element.GetDoubleAttribute(
"camera3DFieldOfView", 45, "threeDFieldOfView"));
cameras.clear();
SerializerElement& camerasElement = element.GetChild("cameras");
camerasElement.ConsiderAsArrayOf("camera");
for (std::size_t i = 0; i < camerasElement.GetChildrenCount(); ++i) {
const SerializerElement& cameraElement = camerasElement.GetChild(i);
Camera camera;
camera.SetUseDefaultSize(
cameraElement.GetBoolAttribute("defaultSize", true));
camera.SetSize(cameraElement.GetDoubleAttribute("width"),
| 4ian/GDevelop | Core/GDCore/Project/Layer.cpp | suggestion | 0.786 |
// Handle scale mode.
if (this._game.getScaleMode() === 'nearest') {
gameCanvas.style['image-rendering'] = '-moz-crisp-edges';
gameCanvas.style['image-rendering'] = '-webkit-optimize-contrast';
gameCanvas.style['image-rendering'] = '-webkit-crisp-edges';
gameCanvas.style['image-rendering'] = 'pixelated';
}
// Handle pixels rounding.
if (this._game.getPixelsRounding()) {
PIXI.settings.ROUND_PIXELS = true;
}
// Handle resize: immediately adjust the game canvas (and dom element container)
// and notify the game (that may want to adjust to the new size of the window).
window.addEventListener('resize', () => {
this._game.onWindowInnerSizeChanged();
this._resizeCanvas();
});
// Focus the canvas when created.
gameCanvas.focus();
}
useCanvas(gameCanvas: HTMLCanvasElement): void {
if (typeof THREE !== "undefined") {
this._threeRenderer = new THREE.WebGLRenderer({
canvas: gameCanvas,
antialias:
this._game.getAntialiasingMode() !== "none" &&
(this._game.isAntialisingEnabledOnMobile() || !gdjs.evtTools.common.isMobile()),
preserveDrawingBuffer: true, // Keep to true to allow screenshots.
});
this._threeRenderer.useLegacyLights = true;
this._threeRenderer.autoClear = false;
this._threeRenderer.setSize(this._game.getGameResolutionWidth(), this._game.getGameResolutionHeight());
// Create a PixiJS renderer that use the same GL context as Three.js
// so that both can render to the canvas and even have PixiJS rendering
// reused in Three.js (by using a RenderTexture and the same internal WebGL texture).
this._pixiRenderer = new PIXI.Renderer({
width: this._game.getGameResolutionWidth(),
height: this._game.getGameResolutionHeight(),
view: gameCanvas,
// @ts-ignore - reuse the context from Three.js.
context: this._threeRenderer.getContext(),
clearBeforeRender: false,
preserveDrawingBuffer: true, // Keep to true to allow screenshots.
antialias: false,
backgroundAlpha: 0, | There is a lot of copy from the `createStandardCanvas` function. Could you rework `createStandardCanvas` so that it's using `useCanvas` under the hood?
Also, the name is probably not showing this is an important operation enough, that just can't be redone a second time. So I think it should be called `initializeForCanvas` | TypeScript | @@ -189,6 +189,120 @@ namespace gdjs {
gameCanvas.focus();
}
+ useCanvas(gameCanvas: HTMLCanvasElement): void { |
// Prevent magnifying glass on iOS with a long press.
// Note that there are related bugs on iOS 15 (see https://bugs.webkit.org/show_bug.cgi?id=231161)
// but it seems not to affect us as the `domElementsContainer` has `pointerEvents` set to `none`.
domElementsContainer.style['-webkit-user-select'] = 'none';
gameCanvas.parentNode?.appendChild(domElementsContainer);
this._domElementsContainer = domElementsContainer;
this._resizeCanvas();
// Handle scale mode.
if (this._game.getScaleMode() === 'nearest') {
gameCanvas.style['image-rendering'] = '-moz-crisp-edges';
gameCanvas.style['image-rendering'] = '-webkit-optimize-contrast';
gameCanvas.style['image-rendering'] = '-webkit-crisp-edges';
gameCanvas.style['image-rendering'] = 'pixelated';
}
// Handle pixels rounding.
if (this._game.getPixelsRounding()) {
PIXI.settings.ROUND_PIXELS = true;
}
// Handle resize: immediately adjust the game canvas (and dom element container)
// and notify the game (that may want to adjust to the new size of the window).
window.addEventListener('resize', () => {
this._game.onWindowInnerSizeChanged();
this._resizeCanvas();
});
// Focus the canvas when created.
gameCanvas.focus();
}
static getWindowInnerWidth() {
return typeof window !== 'undefined' ? window.innerWidth : 800;
}
static getWindowInnerHeight() {
return typeof window !== 'undefined' ? window.innerHeight : 800;
}
/**
* Update the game renderer size according to the "game resolution".
* Called when game resolution changes.
*
* Note that if the canvas is fullscreen, it won't be resized, but when going back to
* non fullscreen mode, the requested size will be used.
*/
updateRendererSize(): void { | 4ian/GDevelop | GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts | suggestion | 0.643 |
} else {
outputObjectsContainer.InsertNewObject(
project,
parameter.GetExtraInfo(),
objectName,
outputObjectsContainer.GetObjectsCount());
}
// Memorize the last object name. By convention, parameters that require
// an object (mainly, "objectvar" and "behavior") should be placed after
// the object in the list of parameters (if possible, just after).
// Search "lastObjectName" in the codebase for other place where this
// convention is enforced.
lastObjectName = objectName;
} else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) {
if (!lastObjectName.empty()) {
if (outputObjectsContainer.HasObjectNamed(lastObjectName)) {
const gd::String& behaviorName = parameter.GetName();
const gd::String& behaviorType = parameter.GetExtraInfo();
gd::Object& object = outputObjectsContainer.GetObject(lastObjectName);
allObjectBehaviorNames[lastObjectName].insert(behaviorName);
// Check if we can keep the existing behavior.
if (object.HasBehaviorNamed(behaviorName)) {
if (object.GetBehavior(behaviorName).GetTypeName() !=
behaviorType) {
// Behavior type has changed, remove it so it is re-created.
object.RemoveBehavior(behaviorName);
}
}
if (!object.HasBehaviorNamed(behaviorName)) {
object.AddNewBehavior(
project, parameter.GetExtraInfo(), behaviorName);
}
}
}
}
}
// Remove objects that are not in the parameters anymore.
std::set<gd::String> objectNamesInContainer =
outputObjectsContainer.GetAllObjectNames();
for (const auto& objectName : objectNamesInContainer) {
if (allObjectNames.find(objectName) == allObjectNames.end()) {
outputObjectsContainer.RemoveObject(objectName);
}
}
// Remove behaviors of objects that are not in the parameters anymore. | I wonder if the name can be confusing because a free function could have an object parameter without object type and the following behavior parameters be some capabilities (default behavior). It also won't be "all" the behaviors of the actual objects.
I guess it's kind of the required behavior for objects passed in parameter, but "required" may be confusing as it's already used for behavior properties.
```suggestion
objectAdditionnalBehaviorNames[lastObjectName].insert(behaviorName);
```
| C++ | @@ -71,7 +75,7 @@ void ParameterMetadataTools::ParametersToObjectsContainer(
const gd::String& behaviorType = parameter.GetExtraInfo();
gd::Object& object = outputObjectsContainer.GetObject(lastObjectName);
- allObjectBehaviorNames[lastObjectName].insert(behaviorName);
+ allObjectNonDefaultBehaviorNames[lastObjectName].insert(behaviorName); | // are all present (and no more than required by the object type).
// Non default behaviors coming from parameters will be added or removed later.
project.EnsureObjectDefaultBehaviors(outputObjectsContainer.GetObject(objectName));
} else {
// Create a new object (and its default behaviors) if needed.
outputObjectsContainer.InsertNewObject(
project,
objectType,
objectName,
outputObjectsContainer.GetObjectsCount());
}
// Memorize the last object name. By convention, parameters that require
// an object (mainly, "objectvar" and "behavior") should be placed after
// the object in the list of parameters (if possible, just after).
// Search "lastObjectName" in the codebase for other place where this
// convention is enforced.
lastObjectName = objectName;
} else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) {
if (!lastObjectName.empty()) {
if (outputObjectsContainer.HasObjectNamed(lastObjectName)) {
const gd::String& behaviorName = parameter.GetName();
const gd::String& behaviorType = parameter.GetExtraInfo();
gd::Object& object = outputObjectsContainer.GetObject(lastObjectName);
allObjectNonDefaultBehaviorNames[lastObjectName].insert(behaviorName);
// Check if we can keep the existing behavior.
if (object.HasBehaviorNamed(behaviorName)) {
if (object.GetBehavior(behaviorName).GetTypeName() !=
behaviorType) {
// Behavior type has changed, remove it so it is re-created.
object.RemoveBehavior(behaviorName);
}
}
if (!object.HasBehaviorNamed(behaviorName)) {
object.AddNewBehavior(
project, parameter.GetExtraInfo(), behaviorName);
}
}
}
}
}
// Remove objects that are not in the parameters anymore.
std::set<gd::String> objectNamesInContainer =
outputObjectsContainer.GetAllObjectNames();
for (const auto& objectName : objectNamesInContainer) {
if (allObjectNames.find(objectName) == allObjectNames.end()) {
outputObjectsContainer.RemoveObject(objectName); | 4ian/GDevelop | Core/GDCore/Extensions/Metadata/ParameterMetadataTools.cpp | suggestion | 1 |
parameters.removeParameter('MySpriteObject2');
expect(parameters.getParametersCount()).toBe(7);
objectsContainer = new gd.ObjectsContainer(gd.ObjectsContainer.Function);
gd.ParameterMetadataTools.parametersToObjectsContainer(
project,
parameters,
objectsContainer
);
// Check that object parameters are considered as objects in the objects container.
expect(objectsContainer.getObjectsCount()).toBe(2);
expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true);
expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true);
const objectWithoutType = objectsContainer.getObject('MyObjectWithoutType');
expect(objectWithoutType.getType()).toBe(
''
);
const mySpriteObject = objectsContainer.getObject('MySpriteObject');
expect(objectsContainer.getObject('MySpriteObject').getType()).toBe(
'Sprite'
);
// Check that behaviors were also added.
expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual(
['MyFirstBehavior', 'MySecondBehavior']
);
// Call a second time and verify no changes.
gd.ParameterMetadataTools.parametersToObjectsContainer(
project,
parameters,
objectsContainer
);
expect(objectsContainer.getObjectsCount()).toBe(2);
expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true);
expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true);
expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual(
['MyFirstBehavior', 'MySecondBehavior']
);
// Verify that objects are even stable in memory.
expect(objectWithoutType).toBe(objectsContainer.getObject('MyObjectWithoutType'));
expect(gd.getPointer(objectWithoutType)).toBe(gd.getPointer(objectsContainer.getObject('MyObjectWithoutType')));
expect(mySpriteObject).toBe(objectsContainer.getObject('MySpriteObject'));
expect(gd.getPointer(mySpriteObject)).toBe(gd.getPointer(objectsContainer.getObject('MySpriteObject')));
// Change an object type, rename a behavior and add a new object.
parameters.getParameter("MyObjectWithoutType").setExtraInfo('Sprite'); | Maybe `ObjectMetadata::AddDefaultBehavior` can be used to simulate a change of capability in a custom object. | JavaScript | @@ -4295,19 +4295,37 @@ describe('libGD.js', function () {
expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true);
expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true);
- const objectWithoutType = objectsContainer.getObject('MyObjectWithoutType');
- expect(objectWithoutType.getType()).toBe(
- ''
+ const objectWithoutType = objectsContainer.getObject(
+ 'MyObjectWithoutType'
);
+ expect(objectWithoutType.getType()).toBe('');
const mySpriteObject = objectsContainer.getObject('MySpriteObject');
expect(objectsContainer.getObject('MySpriteObject').getType()).toBe(
'Sprite'
);
- // Check that behaviors were also added.
- expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual(
- ['MyFirstBehavior', 'MySecondBehavior']
- );
+ // Check that behaviors were also added AND that default behaviors are also present. |
parameters.removeParameter('MySpriteObject2');
expect(parameters.getParametersCount()).toBe(7);
objectsContainer = new gd.ObjectsContainer();
gd.ParameterMetadataTools.parametersToObjectsContainer(
project,
parameters,
objectsContainer
);
// Check that object parameters are considered as objects in the objects container.
expect(objectsContainer.getObjectsCount()).toBe(2);
expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true);
expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true);
const objectWithoutType = objectsContainer.getObject(
'MyObjectWithoutType'
);
expect(objectWithoutType.getType()).toBe('');
const mySpriteObject = objectsContainer.getObject('MySpriteObject');
expect(objectsContainer.getObject('MySpriteObject').getType()).toBe(
'Sprite'
);
// Check that behaviors were also added AND that default behaviors are also present.
expect(
objectsContainer
.getObject('MySpriteObject')
.getAllBehaviorNames()
.toJSArray()
).toEqual([
'Animation',
'Effect',
'Flippable',
'MyFirstBehavior',
'MySecondBehavior',
'Opacity',
'Resizable',
'Scale',
]);
expect(
objectsContainer
.getObject('MyObjectWithoutType')
.getAllBehaviorNames()
.toJSArray()
).toEqual([]);
// Call a second time and verify no changes.
gd.ParameterMetadataTools.parametersToObjectsContainer(
project, | 4ian/GDevelop | GDevelop.js/__tests__/Core.js | suggestion | 0.571 |
std::set<gd::String> objectNamesInContainer =
outputObjectsContainer.GetAllObjectNames();
for (const auto& objectName : objectNamesInContainer) {
if (allObjectNames.find(objectName) == allObjectNames.end()) {
outputObjectsContainer.RemoveObject(objectName);
}
}
// Remove behaviors of objects that are not in the parameters anymore.
for (const auto& objectName : allObjectNames) {
if (!outputObjectsContainer.HasObjectNamed(objectName)) {
// Should not happen.
continue;
}
auto& object = outputObjectsContainer.GetObject(objectName);
for (const auto& behaviorName : object.GetAllBehaviorNames()) {
const auto& allBehaviorNames = allObjectBehaviorNames[objectName];
if (allBehaviorNames.find(behaviorName) == allBehaviorNames.end()) {
object.RemoveBehavior(behaviorName);
}
}
}
}
void ParameterMetadataTools::ForEachParameterMatchingSearch(
const std::vector<const ParameterMetadataContainer*>&
parametersVectorsList,
const gd::String& search,
std::function<void(const gd::ParameterMetadata&)> cb) {
for (auto it = parametersVectorsList.rbegin();
it != parametersVectorsList.rend();
++it) {
const ParameterMetadataContainer* parametersVector = *it;
for (const auto ¶meterMetadata :
parametersVector->GetInternalVector()) {
if (parameterMetadata->GetName().FindCaseInsensitive(search) !=
gd::String::npos)
cb(*parameterMetadata);
}
}
}
bool ParameterMetadataTools::Has(
const std::vector<const ParameterMetadataContainer*>& parametersVectorsList,
const gd::String& parameterName) {
for (auto it = parametersVectorsList.rbegin();
it != parametersVectorsList.rend();
++it) {
const ParameterMetadataContainer* parametersVector = *it; | Actually, I think it's legit to add behavior parameters to require capabilities on an object without any specified type. | C++ | @@ -108,8 +112,14 @@ void ParameterMetadataTools::ParametersToObjectsContainer(
}
auto& object = outputObjectsContainer.GetObject(objectName);
+ const auto& allBehaviorNames = allObjectNonDefaultBehaviorNames[objectName];
for (const auto& behaviorName : object.GetAllBehaviorNames()) {
- const auto& allBehaviorNames = allObjectBehaviorNames[objectName];
+ if (object.GetBehavior(behaviorName).IsDefaultBehavior()) {
+ // Default behaviors are already ensured to be all present
+ // (and no more than required by the object type).
+ continue; | }
}
// Remove objects that are not in the parameters anymore.
std::set<gd::String> objectNamesInContainer =
outputObjectsContainer.GetAllObjectNames();
for (const auto& objectName : objectNamesInContainer) {
if (allObjectNames.find(objectName) == allObjectNames.end()) {
outputObjectsContainer.RemoveObject(objectName);
}
}
// Remove behaviors of objects that are not in the parameters anymore.
for (const auto& objectName : allObjectNames) {
if (!outputObjectsContainer.HasObjectNamed(objectName)) {
// Should not happen.
continue;
}
auto& object = outputObjectsContainer.GetObject(objectName);
const auto& allBehaviorNames = allObjectNonDefaultBehaviorNames[objectName];
for (const auto& behaviorName : object.GetAllBehaviorNames()) {
if (object.GetBehavior(behaviorName).IsDefaultBehavior()) {
// Default behaviors are already ensured to be all present
// (and no more than required by the object type).
continue;
}
if (allBehaviorNames.find(behaviorName) == allBehaviorNames.end()) {
object.RemoveBehavior(behaviorName);
}
}
}
}
void ParameterMetadataTools::ForEachParameterMatchingSearch(
const std::vector<const ParameterMetadataContainer*>&
parametersVectorsList,
const gd::String& search,
std::function<void(const gd::ParameterMetadata&)> cb) {
for (auto it = parametersVectorsList.rbegin();
it != parametersVectorsList.rend();
++it) {
const ParameterMetadataContainer* parametersVector = *it;
for (const auto ¶meterMetadata :
parametersVector->GetInternalVector()) {
if (parameterMetadata->GetName().FindCaseInsensitive(search) !=
gd::String::npos)
cb(*parameterMetadata);
} | 4ian/GDevelop | Core/GDCore/Extensions/Metadata/ParameterMetadataTools.cpp | suggestion | 0.5 |
import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay';
const electron = optionalRequire('electron');
const path = optionalRequire('path');
export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) =>
isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4));
export const getProjectDisplayDate = (i18n: I18nType, date: number) =>
getRelativeOrAbsoluteDisplayDate({
i18n,
dateAsNumber: date,
sameDayFormat: 'todayAndHour',
dayBeforeFormat: 'yesterdayAndHour',
relativeLimit: 'currentWeek',
sameWeekFormat: 'thisWeek',
});
export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) =>
i18n.date(date, {
dateStyle: 'short',
timeStyle: 'short',
});
const getNoProjectAlertMessage = () => {
if (!electron) {
// Trying to open a local project from the web app of the mobile app.
return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`;
} else {
return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`;
}
};
const styles = {
tooltipButtonContainer: {
display: 'flex',
flexDirection: 'column',
alignItems: 'stretch',
},
buttonsContainer: {
display: 'flex',
flexShrink: 0,
flexDirection: 'column',
justifyContent: 'center',
},
iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' },
title: {
...textEllipsisStyle,
overflowWrap: 'break-word',
},
projectFilesButton: { minWidth: 32 },
fileIcon: {
width: 16, | I'd rather say `Your project must be stored on your computer` rather than surely, it feels more english | JavaScript | @@ -50,13 +51,37 @@ import PreferencesContext from '../MainFrame/Preferences/PreferencesContext';
import { textEllipsisStyle } from '../UI/TextEllipsis';
import FileWithLines from '../UI/CustomSvgIcons/FileWithLines';
import TextButton from '../UI/TextButton';
-import { Tooltip } from '@material-ui/core';
+import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay';
const electron = optionalRequire('electron');
const path = optionalRequire('path');
export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) =>
isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4));
+export const getProjectDisplayDate = (i18n: I18nType, date: number) =>
+ getRelativeOrAbsoluteDisplayDate({
+ i18n,
+ dateAsNumber: date,
+ sameDayFormat: 'todayAndHour',
+ dayBeforeFormat: 'yesterdayAndHour',
+ relativeLimit: 'currentWeek',
+ sameWeekFormat: 'thisWeek',
+ });
+export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) =>
+ i18n.date(date, {
+ dateStyle: 'short',
+ timeStyle: 'short',
+ });
+
+const getNoProjectAlertMessage = () => {
+ if (!electron) {
+ // Trying to open a local project from the web app of the mobile app.
+ return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`; | import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay';
const electron = optionalRequire('electron');
const path = optionalRequire('path');
export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) =>
isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4));
export const getProjectDisplayDate = (i18n: I18nType, date: number) =>
getRelativeOrAbsoluteDisplayDate({
i18n,
dateAsNumber: date,
sameDayFormat: 'todayAndHour',
dayBeforeFormat: 'yesterdayAndHour',
relativeLimit: 'currentWeek',
sameWeekFormat: 'thisWeek',
});
export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) =>
i18n.date(date, {
dateStyle: 'short',
timeStyle: 'short',
});
const getNoProjectAlertMessage = () => {
if (!electron) {
// Trying to open a local project from the web app of the mobile app.
return t`Looks like your project isn't there!${'\n\n'}Your project must be stored on your computer.`;
} else {
return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`;
}
};
const styles = {
tooltipButtonContainer: {
display: 'flex',
flexDirection: 'column',
alignItems: 'stretch',
},
buttonsContainer: {
display: 'flex',
flexShrink: 0,
flexDirection: 'column',
justifyContent: 'center',
},
iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' },
title: {
...textEllipsisStyle,
overflowWrap: 'break-word',
},
projectFilesButton: { minWidth: 32 },
fileIcon: {
width: 16, | 4ian/GDevelop | newIDE/app/src/GameDashboard/GameDashboardCard.js | suggestion | 0.5 |
onChange();
}}
/>
<Checkbox
label={<Trans>Expand inner area with parent</Trans>}
checked={eventsBasedObject.isInnerAreaFollowingParentSize()}
onCheck={(e, checked) => {
eventsBasedObject.markAsInnerAreaFollowingParentSize(checked);
onChange();
onEventsBasedObjectChildrenEdited();
}}
/>
{isDev && (
<Checkbox
label={<Trans>Use legacy renderer</Trans>}
checked={eventsBasedObject.isUsingLegacyInstancesRenderer()}
onCheck={(e, checked) => {
eventsBasedObject.makAsUsingLegacyInstancesRenderer(checked);
onChange();
onEventsBasedObjectChildrenEdited();
}}
/>
)}
<Checkbox
label={<Trans>Private</Trans>}
checked={eventsBasedObject.isPrivate()}
onCheck={(e, checked) => {
eventsBasedObject.setPrivate(checked);
onChange();
onEventsBasedObjectChildrenEdited();
}}
/>
<Line noMargin justifyContent="center">
<RaisedButton
label={<Trans>Open visual editor for the object</Trans>}
primary
onClick={onOpenCustomObjectEditor}
/>
</Line>
<Line noMargin>
<HelpButton
key="help"
helpPagePath="/objects/custom-objects-prefab-template"
/>
</Line>
</ColumnStackLayout>
);
}
| ```suggestion
label={<Trans>Private (can only be used inside the extension)</Trans>}
``` | JavaScript | @@ -141,6 +141,15 @@ export default function EventsBasedObjectEditor({
}}
/>
)}
+ <Checkbox
+ label={<Trans>Private</Trans>} | eventsBasedObject.markAsTextContainer(checked);
onChange();
}}
/>
<Checkbox
label={<Trans>Expand inner area with parent</Trans>}
checked={eventsBasedObject.isInnerAreaFollowingParentSize()}
onCheck={(e, checked) => {
eventsBasedObject.markAsInnerAreaFollowingParentSize(checked);
onChange();
onEventsBasedObjectChildrenEdited();
}}
/>
{isDev && (
<Checkbox
label={<Trans>Use legacy renderer</Trans>}
checked={eventsBasedObject.isUsingLegacyInstancesRenderer()}
onCheck={(e, checked) => {
eventsBasedObject.makAsUsingLegacyInstancesRenderer(checked);
onChange();
onEventsBasedObjectChildrenEdited();
}}
/>
)}
<Checkbox
label={<Trans>Private</Trans>}
checked={eventsBasedObject.isPrivate()}
onCheck={(e, checked) => {
eventsBasedObject.setPrivate(checked);
onChange();
onEventsBasedObjectChildrenEdited();
}}
tooltipOrHelperText={
eventsBasedObject.isPrivate() ? (
<Trans>
This object won't be visible in the scene and events editors.
</Trans>
) : (
<Trans>
This object will be visible in the scene and events editors.
</Trans>
)
}
/>
<Line noMargin justifyContent="center">
<RaisedButton
label={<Trans>Open visual editor for the object</Trans>}
primary
onClick={onOpenCustomObjectEditor}
/>
</Line> | 4ian/GDevelop | newIDE/app/src/EventsBasedObjectEditor/index.js | suggestion | 0.643 |
type: 'separator',
},
{
label: i18n._(t`Copy`),
click: () => this.copy(),
accelerator: 'CmdOrCtrl+C',
},
{
label: i18n._(t`Cut`),
click: () => this.cut(),
accelerator: 'CmdOrCtrl+X',
},
{
label: i18n._(t`Paste`),
enabled: Clipboard.has(EVENTS_BASED_OBJECT_CLIPBOARD_KIND),
click: () => this.paste(),
accelerator: 'CmdOrCtrl+V',
},
].filter(Boolean);
}
renderRightComponent(i18n: I18nType): ?React.Node {
return this.eventsBasedObject.isPrivate() ? (
<Tooltip
title={
<Trans>This object won't be visible in the events editor.</Trans>
}
>
<VisibilityOff
fontSize="small"
style={{
...styles.tooltip,
color: this.props.gdevelopTheme.text.color.disabled,
}}
/>
</Tooltip>
) : null;
}
delete(): void {
this._deleteEventsBasedObject({
askForConfirmation: true,
});
}
async _deleteEventsBasedObject({
askForConfirmation,
}: {|
askForConfirmation: boolean,
|}): Promise<void> {
const { eventsBasedObjectsList } = this.props; | ```suggestion
<Trans>This object won't be visible in the scene editor.</Trans>
``` | JavaScript | @@ -193,7 +206,21 @@ export class EventsBasedObjectTreeViewItemContent
}
renderRightComponent(i18n: I18nType): ?React.Node {
- return null;
+ return this.eventsBasedObject.isPrivate() ? (
+ <Tooltip
+ title={
+ <Trans>This object won't be visible in the events editor.</Trans> | type: 'separator',
},
{
label: i18n._(t`Copy`),
click: () => this.copy(),
accelerator: 'CmdOrCtrl+C',
},
{
label: i18n._(t`Cut`),
click: () => this.cut(),
accelerator: 'CmdOrCtrl+X',
},
{
label: i18n._(t`Paste`),
enabled: Clipboard.has(EVENTS_BASED_OBJECT_CLIPBOARD_KIND),
click: () => this.paste(),
accelerator: 'CmdOrCtrl+V',
},
].filter(Boolean);
}
renderRightComponent(i18n: I18nType): ?React.Node {
return this.eventsBasedObject.isPrivate() ? (
<Tooltip
title={
<Trans>
This object won't be visible in the scene and events editors.
</Trans>
}
>
<VisibilityOff
fontSize="small"
style={{
...styles.tooltip,
color: this.props.gdevelopTheme.text.color.disabled,
}}
/>
</Tooltip>
) : null;
}
delete(): void {
this._deleteEventsBasedObject({
askForConfirmation: true,
});
}
async _deleteEventsBasedObject({
askForConfirmation,
}: {|
askForConfirmation: boolean, | 4ian/GDevelop | newIDE/app/src/EventsFunctionsList/EventsBasedObjectTreeViewItemContent.js | suggestion | 0.571 |
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
};
} else if (valueType === 'textarea') {
return {
name,
valueType: 'textarea',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
};
} else if(valueType ==='animationname')
{
function getChoices()
{
if(!object)
{ return [{value:"Object is not valid !", label:"Object is not valid !"}] }
let animationArray = [];
for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ )
{
animationArray.push(object.getConfiguration().getAnimationName(i));
}
return animationArray.map(value => ({ value, label: value }));
}
return {
name,
valueType: 'string',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
console.log(instance, name, newValue);
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
getChoices,
} | The editor should ensure it never happens.
If we only allow to define "AnimationName" properties in the "Behavior properties" tab here (and not in "Scene properties"):

There should always be an object when a behavior propeties values are edited. So, it should be fine to return an empty Array. | JavaScript | @@ -220,7 +220,40 @@ const createField = (
getLabel,
getDescription,
};
- } else {
+ } else if(valueType ==='animationname')
+ {
+ function getChoices()
+ {
+ if(!object)
+ { return [{value:"Object is not valid !", label:"Object is not valid !"}] } | onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
};
} else if (valueType === 'textarea') {
return {
name,
valueType: 'textarea',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
};
} else if (valueType === 'animationname') {
return {
getChoices: () => {
if (!object) {
return [];
}
const animationArray = mapFor(
0,
object.getConfiguration().getAnimationsCount(),
i => {
const animationName = object.getConfiguration().getAnimationName(i);
if (animationName === '') {
return null;
}
return {
value: animationName,
label: animationName,
};
}
).filter(Boolean);
animationArray.push({ value: '', label: '(no animation)' });
return animationArray;
},
name,
valueType: 'string',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => { | 4ian/GDevelop | newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js | suggestion | 0.5 |
name,
valueType: 'textarea',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
};
} else if(valueType ==='animationname')
{
function getChoices()
{
if(!object)
{ return [{value:"Object is not valid !", label:"Object is not valid !"}] }
let animationArray = [];
for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ )
{
animationArray.push(object.getConfiguration().getAnimationName(i));
}
return animationArray.map(value => ({ value, label: value }));
}
return {
name,
valueType: 'string',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
console.log(instance, name, newValue);
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
getChoices,
}
}
else {
console.error(
`A property with type=${valueType} could not be mapped to a field. Ensure that this type is correct and understood by the IDE.`
);
return null; | You can use the `mapFor` fonction to shorten the code a bit.
The empty string should be added to the list. | JavaScript | @@ -220,7 +220,40 @@ const createField = (
getLabel,
getDescription,
};
- } else {
+ } else if(valueType ==='animationname')
+ {
+ function getChoices()
+ {
+ if(!object)
+ { return [{value:"Object is not valid !", label:"Object is not valid !"}] }
+
+ let animationArray = [];
+ for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ )
+ {
+ animationArray.push(object.getConfiguration().getAnimationName(i));
+ }
+ return animationArray.map(value => ({ value, label: value })); | name,
valueType: 'textarea',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
onUpdateProperty(instance, name, newValue);
},
getLabel,
getDescription,
};
} else if (valueType === 'animationname') {
return {
getChoices: () => {
if (!object) {
return [];
}
const animationArray = mapFor(
0,
object.getConfiguration().getAnimationsCount(),
i => {
const animationName = object.getConfiguration().getAnimationName(i);
if (animationName === '') {
return null;
}
return {
value: animationName,
label: animationName,
};
}
).filter(Boolean);
animationArray.push({ value: '', label: '(no animation)' });
return animationArray;
},
name,
valueType: 'string',
getValue: (instance: Instance): string => {
return getProperties(instance)
.get(name)
.getValue();
},
setValue: (instance: Instance, newValue: string) => {
onUpdateProperty(instance, name, newValue);
},
getLabel,
};
} else {
console.error(
`A property with type=${valueType} could not be mapped to a field. Ensure that this type is correct and understood by the IDE.` | 4ian/GDevelop | newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js | suggestion | 0.571 |
forceUpdate();
onPropertiesUpdated &&
onPropertiesUpdated();
}}
fullWidth
>
<SelectOption
key="property-type-number"
value="Number"
label={t`Number`}
/>
<SelectOption
key="property-type-string"
value="String"
label={t`String`}
/>
<SelectOption
key="property-type-boolean"
value="Boolean"
label={t`Boolean (checkbox)`}
/>
<SelectOption
key="property-type-animationname"
value="AnimationName"
label={t`Animation Name (text)`}
/>
<SelectOption
key="property-type-choice"
value="Choice"
label={t`String from a list of options (text)`}
/>
<SelectOption
key="property-type-color"
value="Color"
label={t`Color (text)`}
/>
<SelectOption
key="property-type-resource"
value="Resource"
label={t`Resource (JavaScript only)`}
/>
{!isSceneProperties && (
<SelectOption
key="property-type-behavior"
value="Behavior"
label={t`Required behavior`}
/>
)}
</SelectField>
{property.getType() === 'Number' && (
<SelectField | I wonder if it should be below the "Choice" type as it's a bit more specific.
```suggestion
<SelectOption
key="property-type-animationname"
value="AnimationName"
label={t`Animation name (text)`}
/>
``` | JavaScript | @@ -729,6 +729,11 @@ export default function EventsBasedBehaviorPropertiesEditor({
value="Boolean"
label={t`Boolean (checkbox)`}
/>
+ <SelectOption
+ key="property-type-animationname"
+ value="AnimationName"
+ label={t`Animation Name (text)`}
+ /> | forceUpdate();
onPropertiesUpdated &&
onPropertiesUpdated();
}}
fullWidth
>
<SelectOption
key="property-type-number"
value="Number"
label={t`Number`}
/>
<SelectOption
key="property-type-string"
value="String"
label={t`String`}
/>
<SelectOption
key="property-type-boolean"
value="Boolean"
label={t`Boolean (checkbox)`}
/>
<SelectOption
key="property-type-animationname"
value="AnimationName"
label={t`Animation name (text)`}
/>
<SelectOption
key="property-type-choice"
value="Choice"
label={t`String from a list of options (text)`}
/>
<SelectOption
key="property-type-color"
value="Color"
label={t`Color (text)`}
/>
<SelectOption
key="property-type-resource"
value="Resource"
label={t`Resource (JavaScript only)`}
/>
{!isSceneProperties && (
<SelectOption
key="property-type-behavior"
value="Behavior"
label={t`Required behavior`}
/>
)}
</SelectField>
{property.getType() === 'Number' && (
<SelectField | 4ian/GDevelop | newIDE/app/src/EventsBasedBehaviorEditor/EventsBasedBehaviorPropertiesEditor.js | suggestion | 1 |
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('padding')
.setValue((objectContent.padding || 0).toString())
.setType('number')
.setLabel(_('Padding'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('maxLength')
.setValue(objectContent.maxLength || 20)
.setType('number')
.setLabel(_('Max length'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addExtraInfo('left')
.addExtraInfo('right')
.addExtraInfo('center')
.setLabel(_('text Alignement'))
.setGroup(_('Border appearance'));
return objectProperties;
};
textInputObject.content = {
initialValue: '',
placeholder: 'Touch to start typing',
fontResourceName: '',
fontSize: 20,
inputType: 'text',
textColor: '0;0;0',
fillColor: '255;255;255',
fillOpacity: 255,
borderColor: '0;0;0',
borderOpacity: 255,
borderWidth: 1,
readOnly: false,
disabled: false,
padding: 0,
textAlign: 'left',
maxLength: '20',
};
textInputObject.updateInitialInstanceProperty = function (
instance,
propertyName,
newValue | I think that the order is important here. I see that the text uses the order `left, center right`, so we might as well use the same here | JavaScript | @@ -200,6 +209,30 @@ module.exports = {
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
+ objectProperties
+ .getOrCreate('padding')
+ .setValue((objectContent.padding || 0).toString())
+ .setType('number')
+ .setLabel(_('Padding'))
+ .setGroup(_('Border appearance'));
+
+ objectProperties
+ .getOrCreate('maxLength')
+ .setValue(objectContent.maxLength || 20)
+ .setType('number')
+ .setLabel(_('Max length'))
+ .setGroup(_('Border appearance'));
+
+ objectProperties
+ .getOrCreate('textAlign')
+ .setValue(objectContent.textAlign || 'left')
+ .setType('choice')
+ .addExtraInfo('left')
+ .addExtraInfo('right')
+ .addExtraInfo('center') | .setGroup(_('Border appearance'));
objectProperties
.getOrCreate('padding')
.setValue((objectContent.padding || 0).toString())
.setType('number')
.setLabel(_('Padding'))
.setGroup(_('Font'));
objectProperties
.getOrCreate('maxLength')
.setValue((objectContent.maxLength || 0).toString())
.setType('number')
.setLabel(_('Max length'))
.setDescription(
_(
'The maximum length of the input value (this property will be ignored if the input type is a number).'
)
)
.setAdvanced(true);
objectProperties
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
.setGroup(_('Font'));
return objectProperties;
};
textInputObject.content = {
initialValue: '',
placeholder: 'Touch to start typing',
fontResourceName: '',
fontSize: 20,
inputType: 'text',
textColor: '0;0;0',
fillColor: '255;255;255',
fillOpacity: 255,
borderColor: '0;0;0',
borderOpacity: 255,
borderWidth: 1,
readOnly: false,
disabled: false,
padding: 0,
textAlign: 'left',
maxLength: 0,
};
| 4ian/GDevelop | Extensions/TextInput/JsExtension.js | suggestion | 0.571 |
)
)
.setFunctionName('setOpacity')
.setGetter('getOpacity')
.setHidden();
object
.addScopedCondition(
'Focused',
_('Focused'),
_(
'Check if the text input is focused (the cursor is in the field and player can type text in).'
),
_('_PARAM0_ is focused'),
'',
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isFocused');
object
.addScopedCondition(
'IsInputSubmitted',
_('Input is Submitted (Enter pressed'),
_(
'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.'
),
_('_PARAM0_ got input submitted'),
'',
'res/conditions/surObject24.png',
'res/conditions/surObject.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isSubmitted');
object
.addScopedAction(
'Focus',
_('Focus'),
_(
'Focus the input so that text can be entered (like if it was touched/clicked).'
),
_('Focus _PARAM0_'),
_(''),
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false) | ```suggestion
_('Input is submitted'),
```
I think it's better not mentioning any platform specific detail in the name | JavaScript | @@ -572,6 +609,22 @@ module.exports = {
.getCodeExtraInformation()
.setFunctionName('isFocused');
+ object
+ .addScopedCondition(
+ 'IsInputSubmitted',
+ _('Input is Submitted (Enter pressed'), | 'number',
gd.ParameterOptions.makeNewOptions().setDescription(
_('Opacity (0-255)')
)
)
.setFunctionName('setOpacity')
.setGetter('getOpacity')
.setHidden();
object
.addScopedCondition(
'Focused',
_('Focused'),
_(
'Check if the text input is focused (the cursor is in the field and player can type text in).'
),
_('_PARAM0_ is focused'),
'',
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isFocused');
object
.addScopedCondition(
'IsInputSubmitted',
_('Input is submitted'),
_(
'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.'
),
_('_PARAM0_ value was submitted'),
'',
'res/conditions/surObject24.png',
'res/conditions/surObject.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isSubmitted');
object
.addScopedAction(
'Focus',
_('Focus'),
_(
'Focus the input so that text can be entered (like if it was touched/clicked).'
),
_('Focus _PARAM0_'),
_(''),
'res/conditions/surObjet24.png', | 4ian/GDevelop | Extensions/TextInput/JsExtension.js | suggestion | 0.786 |
.setHidden();
object
.addScopedCondition(
'Focused',
_('Focused'),
_(
'Check if the text input is focused (the cursor is in the field and player can type text in).'
),
_('_PARAM0_ is focused'),
'',
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isFocused');
object
.addScopedCondition(
'IsInputSubmitted',
_('Input is Submitted (Enter pressed'),
_(
'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.'
),
_('_PARAM0_ got input submitted'),
'',
'res/conditions/surObject24.png',
'res/conditions/surObject.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isSubmitted');
object
.addScopedAction(
'Focus',
_('Focus'),
_(
'Focus the input so that text can be entered (like if it was touched/clicked).'
),
_('Focus _PARAM0_'),
_(''),
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('focus');
return extension; | ```suggestion
_('_PARAM0_ value was submitted'),
``` | JavaScript | @@ -572,6 +609,22 @@ module.exports = {
.getCodeExtraInformation()
.setFunctionName('isFocused');
+ object
+ .addScopedCondition(
+ 'IsInputSubmitted',
+ _('Input is Submitted (Enter pressed'),
+ _(
+ 'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.'
+ ),
+ _('_PARAM0_ got input submitted'), | )
.setFunctionName('setOpacity')
.setGetter('getOpacity')
.setHidden();
object
.addScopedCondition(
'Focused',
_('Focused'),
_(
'Check if the text input is focused (the cursor is in the field and player can type text in).'
),
_('_PARAM0_ is focused'),
'',
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isFocused');
object
.addScopedCondition(
'IsInputSubmitted',
_('Input is submitted'),
_(
'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.'
),
_('_PARAM0_ value was submitted'),
'',
'res/conditions/surObject24.png',
'res/conditions/surObject.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation()
.setFunctionName('isSubmitted');
object
.addScopedAction(
'Focus',
_('Focus'),
_(
'Focus the input so that text can be entered (like if it was touched/clicked).'
),
_('Focus _PARAM0_'),
_(''),
'res/conditions/surObjet24.png',
'res/conditions/surObjet.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.getCodeExtraInformation() | 4ian/GDevelop | Extensions/TextInput/JsExtension.js | suggestion | 0.571 |
};
const formatRgbAndOpacityToCssRgba = (
rgbColor: [float, float, float],
opacity: float
) => {
return (
'rgba(' +
rgbColor[0] +
',' +
rgbColor[1] +
',' +
rgbColor[2] +
',' +
opacity / 255 +
')'
);
};
class TextInputRuntimeObjectPixiRenderer {
private _object: gdjs.TextInputRuntimeObject;
private _input: HTMLInputElement | HTMLTextAreaElement | null = null;
private _instanceContainer: gdjs.RuntimeInstanceContainer;
private _runtimeGame: gdjs.RuntimeGame;
private _form: HTMLFormElement | null = null;
private _isSubmited: boolean;
constructor(
runtimeObject: gdjs.TextInputRuntimeObject,
instanceContainer: gdjs.RuntimeInstanceContainer
) {
this._object = runtimeObject;
this._instanceContainer = instanceContainer;
this._runtimeGame = this._instanceContainer.getGame();
this._createElement();
this._isSubmited = false;
}
_createElement() {
if (!!this._input)
throw new Error('Tried to recreate an input while it already exists.');
this._form = document.createElement('form');
this._form.setAttribute('id', 'dynamicForm');
const isTextArea = this._object.getInputType() === 'text area';
this._input = document.createElement(isTextArea ? 'textarea' : 'input');
this._form.style.border = '0px';
this._input.autocomplete = 'off';
this._form.style.borderRadius = '0px';
this._form.style.backgroundColor = 'transparent'; | ```suggestion
private _isSubmitted: boolean;
``` | TypeScript | @@ -31,6 +37,8 @@ namespace gdjs {
private _input: HTMLInputElement | HTMLTextAreaElement | null = null;
private _instanceContainer: gdjs.RuntimeInstanceContainer;
private _runtimeGame: gdjs.RuntimeGame;
+ private _form: HTMLFormElement | null = null;
+ private _isSubmited: boolean; | return (
'rgba(' +
rgbColor[0] +
',' +
rgbColor[1] +
',' +
rgbColor[2] +
',' +
opacity / 255 +
')'
);
};
class TextInputRuntimeObjectPixiRenderer {
private _object: gdjs.TextInputRuntimeObject;
private _input: HTMLInputElement | HTMLTextAreaElement | null = null;
private _instanceContainer: gdjs.RuntimeInstanceContainer;
private _runtimeGame: gdjs.RuntimeGame;
private _form: HTMLFormElement | null = null;
constructor(
runtimeObject: gdjs.TextInputRuntimeObject,
instanceContainer: gdjs.RuntimeInstanceContainer
) {
this._object = runtimeObject;
this._instanceContainer = instanceContainer;
this._runtimeGame = this._instanceContainer.getGame();
this._createElement();
}
_createElement() {
if (!!this._input)
throw new Error('Tried to recreate an input while it already exists.');
this._form = document.createElement('form');
const isTextArea = this._object.getInputType() === 'text area';
this._input = document.createElement(isTextArea ? 'textarea' : 'input');
this._form.style.border = '0px';
this._form.style.borderRadius = '0px';
this._form.style.backgroundColor = 'transparent';
this._form.style.position = 'absolute';
this._form.style.outline = 'none';
this._form.style.resize = 'none';
this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched.
this._form.style.display = 'none'; // Hide while object is being set up.
this._form.style.boxSizing = 'border-box';
this._form.style.textAlign = this._object.getTextAlign();
| 4ian/GDevelop | Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts | suggestion | 0.571 |
}
getText() {
return this._string;
}
setText(newString: string) {
if (newString === this._string) return;
this._string = newString;
this._renderer.updateString();
}
/**
* Called by the renderer when the value of the input shown on the screen
* was changed (because the user typed something).
* This does not propagate back the value to the renderer, which would
* result in the cursor being sent back to the end of the text.
*
* Do not use this if you are not inside the renderer - use `setString` instead.
*/
onRendererInputValueChanged(inputValue: string) {
this._string = inputValue;
}
onRendererFormSubmitted(inputValue: boolean) {
this._isSubmitted = inputValue;
}
getFontResourceName() {
return this._fontResourceName;
}
setFontResourceName(resourceName: string) {
if (this._fontResourceName === resourceName) return;
this._fontResourceName = resourceName;
this._renderer.updateFont();
}
getFontSize() {
return this._fontSize;
}
setFontSize(newSize: number) {
this._fontSize = newSize;
}
/**
* Get the placeholder shown when no text is entered
*/ | ```suggestion
onRendererFormSubmitted() {
``` | TypeScript | @@ -348,6 +379,10 @@ namespace gdjs {
onRendererInputValueChanged(inputValue: string) {
this._string = inputValue;
}
+
+ onRendererFormSubmitted(inputValue: boolean) { | * @deprecated use `getText` instead
*/
getString() {
return this.getText();
}
/**
* Replace the text inside the text input.
* @deprecated use `setText` instead
*/
setString(text: string) {
this.setText(text);
}
getText() {
return this._string;
}
setText(newString: string) {
if (newString === this._string) return;
this._string = newString;
this._renderer.updateString();
}
/**
* Called by the renderer when the value of the input shown on the screen
* was changed (because the user typed something).
* This does not propagate back the value to the renderer, which would
* result in the cursor being sent back to the end of the text.
*
* Do not use this if you are not inside the renderer - use `setString` instead.
*/
onRendererInputValueChanged(inputValue: string) {
this._string = inputValue;
}
onRendererFormSubmitted() {
this._isSubmitted = true;
}
getFontResourceName() {
return this._fontResourceName;
}
setFontResourceName(resourceName: string) {
if (this._fontResourceName === resourceName) return;
this._fontResourceName = resourceName;
this._renderer.updateFont();
} | 4ian/GDevelop | Extensions/TextInput/textinputruntimeobject.ts | suggestion | 0.571 |
this._input.style.borderColor = formatRgbAndOpacityToCssRgba(
this._object._getRawBorderColor(),
this._object.getBorderOpacity()
);
}
updateBorderWidth() {
if (!this._input) return;
this._input.style.borderWidth = this._object.getBorderWidth() + 'px';
}
updateDisabled() {
if (!this._form) return;
this._form.disabled = this._object.isDisabled();
}
updateReadOnly() {
if (!this._form) return;
this._form.readOnly = this._object.isReadOnly();
}
updateMaxLength() {
if (!this._input) return;
if (this._object.getMaxLength() <= 0) {
this._input?.removeAttribute('maxLength');
return;
}
this._input.maxLength = this._object.getMaxLength();
}
updatePadding() {
if (!this._input) return;
this._input.style.padding = this._object.getPadding() + 'px';
}
updateTextAlign() {
if (!this._input) return;
const newTextAlign = this._object.getTextAlign() || 'left';
this._input.style.textAlign = newTextAlign;
}
isFocused() {
return this._input === document.activeElement;
}
focus() {
if (!this._input) return;
| to avoid having the `?`, you could do this:
```js
const input = this._input;
if (!input) return;
// From then on, you can use `input` without TS complaining
``` | TypeScript | @@ -297,14 +317,36 @@ namespace gdjs {
this._input.style.borderWidth = this._object.getBorderWidth() + 'px';
}
updateDisabled() {
- if (!this._input) return;
+ if (!this._form) return;
- this._input.disabled = this._object.isDisabled();
+ this._form.disabled = this._object.isDisabled();
}
updateReadOnly() {
+ if (!this._form) return;
+
+ this._form.readOnly = this._object.isReadOnly();
+ }
+
+ updateMaxLength() {
+ if (!this._input) return;
+ if (this._object.getMaxLength() <= 0) {
+ this._input?.removeAttribute('maxLength'); | );
}
updateBorderColorAndOpacity() {
if (!this._input) return;
this._input.style.borderColor = formatRgbAndOpacityToCssRgba(
this._object._getRawBorderColor(),
this._object.getBorderOpacity()
);
}
updateBorderWidth() {
if (!this._input) return;
this._input.style.borderWidth = this._object.getBorderWidth() + 'px';
}
updateDisabled() {
if (!this._form) return;
this._form.disabled = this._object.isDisabled();
}
updateReadOnly() {
if (!this._form) return;
this._form.readOnly = this._object.isReadOnly();
}
updateMaxLength() {
const input = this._input;
if (!input) return;
if (this._object.getMaxLength() <= 0) {
input.removeAttribute('maxLength');
return;
}
input.maxLength = this._object.getMaxLength();
}
updatePadding() {
if (!this._input) return;
this._input.style.padding = this._object.getPadding() + 'px';
}
updateTextAlign() {
if (!this._input) return;
const newTextAlign = this._object.getTextAlign();
this._input.style.textAlign = newTextAlign;
}
isFocused() { | 4ian/GDevelop | Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts | suggestion | 0.786 |
: 255
).toString()
)
.setType('number')
.setLabel(_('Opacity'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('borderWidth')
.setValue((objectContent.borderWidth || 0).toString())
.setType('number')
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('padding')
.setValue((objectContent.padding || 0).toString())
.setType('number')
.setLabel(_('Padding'))
.setGroup(_('Font'));
objectProperties
.getOrCreate('maxLength')
.setValue((objectContent.maxLength || 0).toString())
.setType('number')
.setLabel(_('Max length'))
.setDescription(_('The maximum length of the input value.'))
.setAdvanced(true);
objectProperties
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
.setGroup(_('Font'));
return objectProperties;
};
textInputObject.content = {
initialValue: '',
placeholder: 'Touch to start typing',
fontResourceName: '',
fontSize: 20,
inputType: 'text',
textColor: '0;0;0',
fillColor: '255;255;255',
fillOpacity: 255,
borderColor: '0;0;0',
borderOpacity: 255, | I added a comment on the PR, I think you should add in the description that this property will not be used if the input type is a number. | JavaScript | @@ -200,6 +209,30 @@ module.exports = {
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
+ objectProperties
+ .getOrCreate('padding')
+ .setValue((objectContent.padding || 0).toString())
+ .setType('number')
+ .setLabel(_('Padding'))
+ .setGroup(_('Font'));
+ objectProperties
+ .getOrCreate('maxLength')
+ .setValue((objectContent.maxLength || 0).toString())
+ .setType('number')
+ .setLabel(_('Max length'))
+ .setDescription(_('The maximum length of the input value.')) | : 255
).toString()
)
.setType('number')
.setLabel(_('Opacity'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('borderWidth')
.setValue((objectContent.borderWidth || 0).toString())
.setType('number')
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('padding')
.setValue((objectContent.padding || 0).toString())
.setType('number')
.setLabel(_('Padding'))
.setGroup(_('Font'));
objectProperties
.getOrCreate('maxLength')
.setValue((objectContent.maxLength || 0).toString())
.setType('number')
.setLabel(_('Max length'))
.setDescription(
_(
'The maximum length of the input value (this property will be ignored if the input type is a number).'
)
)
.setAdvanced(true);
objectProperties
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
.setGroup(_('Font'));
return objectProperties;
};
textInputObject.content = {
initialValue: '',
placeholder: 'Touch to start typing',
fontResourceName: '',
fontSize: 20,
inputType: 'text',
textColor: '0;0;0', | 4ian/GDevelop | Extensions/TextInput/JsExtension.js | suggestion | 0.571 |
// Display after the object is positioned.
this._form.style.display = 'initial';
}
updateString() {
if (!this._input) return;
this._input.value = this._object.getString();
}
updatePlaceholder() {
if (!this._input) return;
this._input.placeholder = this._object.getPlaceholder();
}
updateFont() {
if (!this._input) return;
this._input.style.fontFamily = this._instanceContainer
.getGame()
.getFontManager()
.getFontFamily(this._object.getFontResourceName());
}
updateOpacity() {
if (!this._form) return;
this._form.style.opacity = '' + this._object.getOpacity() / 255;
}
updateInputType() {
if (!this._input) return;
const isTextArea = this._input instanceof HTMLTextAreaElement;
const shouldBeTextArea = this._object.getInputType() === 'text area';
if (isTextArea !== shouldBeTextArea) {
this._destroyElement();
this._createElement();
}
const newType =
userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text';
this._input.setAttribute('type', newType);
}
updateTextColor() {
if (!this._input) return;
this._input.style.color = formatRgbAndOpacityToCssRgba(
this._object._getRawTextColor(),
255
);
} | I think you could use `(this._object.getOpacity() / 255).toFixed(3)` instead. The result of the division could be `0.59200000000005`, and I'm not sure if CSS has some limitations about that. | TypeScript | @@ -246,8 +271,8 @@ namespace gdjs {
}
updateOpacity() {
- if (!this._input) return;
- this._input.style.opacity = '' + this._object.getOpacity() / 255;
+ if (!this._form) return;
+ this._form.style.opacity = '' + this._object.getOpacity() / 255; |
// Display after the object is positioned.
this._form.style.display = 'initial';
}
updateString() {
if (!this._input) return;
this._input.value = this._object.getString();
}
updatePlaceholder() {
if (!this._input) return;
this._input.placeholder = this._object.getPlaceholder();
}
updateFont() {
if (!this._input) return;
this._input.style.fontFamily = this._instanceContainer
.getGame()
.getFontManager()
.getFontFamily(this._object.getFontResourceName());
}
updateOpacity() {
if (!this._form) return;
this._form.style.opacity = (this._object.getOpacity() / 255).toFixed(3);
}
updateInputType() {
if (!this._input) return;
const isTextArea = this._input instanceof HTMLTextAreaElement;
const shouldBeTextArea = this._object.getInputType() === 'text area';
if (isTextArea !== shouldBeTextArea) {
this._destroyElement();
this._createElement();
}
const newType =
userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text';
this._input.setAttribute('type', newType);
}
updateTextColor() {
if (!this._input) return;
this._input.style.color = formatRgbAndOpacityToCssRgba(
this._object._getRawTextColor(),
255
);
} | 4ian/GDevelop | Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts | suggestion | 0.571 |
updateReadOnly() {
if (!this._form) return;
this._form.readOnly = this._object.isReadOnly();
}
updateMaxLength() {
const input = this._input;
if (!input) return;
if (this._object.getMaxLength() <= 0) {
input.removeAttribute('maxLength');
return;
}
input.maxLength = this._object.getMaxLength();
}
updatePadding() {
if (!this._input) return;
this._input.style.padding = this._object.getPadding() + 'px';
}
updateTextAlign() {
if (!this._input) return;
const newTextAlign = this._object.getTextAlign() || 'left';
this._input.style.textAlign = newTextAlign;
}
isFocused() {
return this._input === document.activeElement;
}
focus() {
if (!this._input) return;
this._input.focus();
}
}
export const TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer;
export type TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer;
}
| Is the `|| 'left'` necessary? I think we can be confident that the object only stores correct values | TypeScript | @@ -297,14 +322,37 @@ namespace gdjs {
this._input.style.borderWidth = this._object.getBorderWidth() + 'px';
}
updateDisabled() {
- if (!this._input) return;
+ if (!this._form) return;
- this._input.disabled = this._object.isDisabled();
+ this._form.disabled = this._object.isDisabled();
}
updateReadOnly() {
+ if (!this._form) return;
+
+ this._form.readOnly = this._object.isReadOnly();
+ }
+
+ updateMaxLength() {
+ const input = this._input;
+ if (!input) return;
+ if (this._object.getMaxLength() <= 0) {
+ input.removeAttribute('maxLength');
+ return;
+ }
+ input.maxLength = this._object.getMaxLength();
+ }
+
+ updatePadding() {
+ if (!this._input) return;
+
+ this._input.style.padding = this._object.getPadding() + 'px';
+ }
+
+ updateTextAlign() {
if (!this._input) return;
- this._input.readOnly = this._object.isReadOnly();
+ const newTextAlign = this._object.getTextAlign() || 'left'; | updateReadOnly() {
if (!this._form) return;
this._form.readOnly = this._object.isReadOnly();
}
updateMaxLength() {
const input = this._input;
if (!input) return;
if (this._object.getMaxLength() <= 0) {
input.removeAttribute('maxLength');
return;
}
input.maxLength = this._object.getMaxLength();
}
updatePadding() {
if (!this._input) return;
this._input.style.padding = this._object.getPadding() + 'px';
}
updateTextAlign() {
if (!this._input) return;
const newTextAlign = this._object.getTextAlign();
this._input.style.textAlign = newTextAlign;
}
isFocused() {
return this._input === document.activeElement;
}
focus() {
if (!this._input) return;
this._input.focus();
}
}
export const TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer;
export type TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer;
}
| 4ian/GDevelop | Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts | suggestion | 0.5 |
)
.setType('number')
.setLabel(_('Opacity'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('borderWidth')
.setValue((objectContent.borderWidth || 0).toString())
.setType('number')
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('padding')
.setValue((objectContent.padding || 0).toString())
.setType('number')
.setLabel(_('Padding'))
.setGroup(_('Font'));
objectProperties
.getOrCreate('maxLength')
.setValue((objectContent.maxLength || 0).toString())
.setType('number')
.setLabel(_('Max length'))
.setDescription(
_(
'The maximum length of the input value. (this property will be ignored if the input type is a number'
)
)
.setAdvanced(true);
objectProperties
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
.setGroup(_('Font'));
return objectProperties;
};
textInputObject.content = {
initialValue: '',
placeholder: 'Touch to start typing',
fontResourceName: '',
fontSize: 20,
inputType: 'text',
textColor: '0;0;0',
fillColor: '255;255;255',
fillOpacity: 255, | ```suggestion
'The maximum length of the input value (this property will be ignored if the input type is a number).'
``` | JavaScript | @@ -200,6 +209,34 @@ module.exports = {
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
+ objectProperties
+ .getOrCreate('padding')
+ .setValue((objectContent.padding || 0).toString())
+ .setType('number')
+ .setLabel(_('Padding'))
+ .setGroup(_('Font'));
+ objectProperties
+ .getOrCreate('maxLength')
+ .setValue((objectContent.maxLength || 0).toString())
+ .setType('number')
+ .setLabel(_('Max length'))
+ .setDescription(
+ _(
+ 'The maximum length of the input value. (this property will be ignored if the input type is a number' | )
.setType('number')
.setLabel(_('Opacity'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('borderWidth')
.setValue((objectContent.borderWidth || 0).toString())
.setType('number')
.setLabel(_('Width'))
.setGroup(_('Border appearance'));
objectProperties
.getOrCreate('padding')
.setValue((objectContent.padding || 0).toString())
.setType('number')
.setLabel(_('Padding'))
.setGroup(_('Font'));
objectProperties
.getOrCreate('maxLength')
.setValue((objectContent.maxLength || 0).toString())
.setType('number')
.setLabel(_('Max length'))
.setDescription(
_(
'The maximum length of the input value (this property will be ignored if the input type is a number).'
)
)
.setAdvanced(true);
objectProperties
.getOrCreate('textAlign')
.setValue(objectContent.textAlign || 'left')
.setType('choice')
.addExtraInfo('left')
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
.setGroup(_('Font'));
return objectProperties;
};
textInputObject.content = {
initialValue: '',
placeholder: 'Touch to start typing',
fontResourceName: '',
fontSize: 20,
inputType: 'text',
textColor: '0;0;0',
fillColor: '255;255;255',
fillOpacity: 255, | 4ian/GDevelop | Extensions/TextInput/JsExtension.js | suggestion | 0.857 |
// Display after the object is positioned.
this._form.style.display = 'initial';
}
updateString() {
if (!this._input) return;
this._input.value = this._object.getString();
}
updatePlaceholder() {
if (!this._input) return;
this._input.placeholder = this._object.getPlaceholder();
}
updateFont() {
if (!this._input) return;
this._input.style.fontFamily = this._instanceContainer
.getGame()
.getFontManager()
.getFontFamily(this._object.getFontResourceName());
}
updateOpacity() {
if (!this._form) return;
this._form.style.opacity =
'' + (this._object.getOpacity() / 255).toFixed(3);
}
updateInputType() {
if (!this._input) return;
const isTextArea = this._input instanceof HTMLTextAreaElement;
const shouldBeTextArea = this._object.getInputType() === 'text area';
if (isTextArea !== shouldBeTextArea) {
this._destroyElement();
this._createElement();
}
const newType =
userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text';
this._input.setAttribute('type', newType);
}
updateTextColor() {
if (!this._input) return;
this._input.style.color = formatRgbAndOpacityToCssRgba(
this._object._getRawTextColor(),
255
);
} | ```suggestion
(this._object.getOpacity() / 255).toFixed(3);
```
toFixed returns as string already | TypeScript | @@ -246,8 +271,9 @@ namespace gdjs {
}
updateOpacity() {
- if (!this._input) return;
- this._input.style.opacity = '' + this._object.getOpacity() / 255;
+ if (!this._form) return;
+ this._form.style.opacity =
+ '' + (this._object.getOpacity() / 255).toFixed(3); | // Display after the object is positioned.
this._form.style.display = 'initial';
}
updateString() {
if (!this._input) return;
this._input.value = this._object.getString();
}
updatePlaceholder() {
if (!this._input) return;
this._input.placeholder = this._object.getPlaceholder();
}
updateFont() {
if (!this._input) return;
this._input.style.fontFamily = this._instanceContainer
.getGame()
.getFontManager()
.getFontFamily(this._object.getFontResourceName());
}
updateOpacity() {
if (!this._form) return;
this._form.style.opacity = (this._object.getOpacity() / 255).toFixed(3);
}
updateInputType() {
if (!this._input) return;
const isTextArea = this._input instanceof HTMLTextAreaElement;
const shouldBeTextArea = this._object.getInputType() === 'text area';
if (isTextArea !== shouldBeTextArea) {
this._destroyElement();
this._createElement();
}
const newType =
userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text';
this._input.setAttribute('type', newType);
}
updateTextColor() {
if (!this._input) return;
this._input.style.color = formatRgbAndOpacityToCssRgba(
this._object._getRawTextColor(),
255
);
}
| 4ian/GDevelop | Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts | suggestion | 0.714 |
import { LineStackLayout } from '../../UI/Layout';
import GlobalVariableIcon from '../../UI/CustomSvgIcons/GlobalVariable';
import SceneVariableIcon from '../../UI/CustomSvgIcons/SceneVariable';
import ObjectVariableIcon from '../../UI/CustomSvgIcons/ObjectVariable';
import LocalVariableIcon from '../../UI/CustomSvgIcons/LocalVariable';
import PropertyIcon from '../../UI/CustomSvgIcons/Settings';
import ParameterIcon from '../../UI/CustomSvgIcons/Parameter';
import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope';
import Link from '../../UI/Link';
import Add from '../../UI/CustomSvgIcons/Add';
const gd: libGDevelop = global.gd;
export type VariableDialogOpeningProps = {
variableName: string,
shouldCreate: boolean,
};
type Props = {
...ParameterFieldProps,
isObjectVariable: boolean,
variablesContainers: Array<gdVariablesContainer>,
getVariableSourceFromVariableName: (
variableRootName: string,
projectScopedContainers: gdProjectScopedContainers
) => VariablesContainer_SourceType,
enumerateVariables: () => Array<EnumeratedVariable>,
forceDeclaration?: boolean,
onOpenDialog: (VariableDialogOpeningProps => void) | null,
};
type VariableNameQuickAnalyzeResult = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
export type VariableFieldInterface = {|
...ParameterFieldInterface,
updateAutocompletions: () => void,
|};
export const VariableNameQuickAnalyzeResults = {
OK: 0,
WRONG_QUOTE: 1,
WRONG_SPACE: 2,
WRONG_EXPRESSION: 3,
UNDECLARED_VARIABLE: 4,
NAME_COLLISION_WITH_OBJECT: 5,
PARAMETER_WITH_CHILD: 6,
PROPERTY_WITH_CHILD: 7,
};
export const getRootVariableName = (name: string): string => {
const dotPosition = name.indexOf('.'); | Let's call this:
```suggestion
getVariableSourceFromIdentifierName: (
identifierName: string,
projectScopedContainers: gdProjectScopedContainers
) => VariablesContainer_SourceType,
```
to emphasis that we don't know if it's a variable name, a property name or a parameter name, and it could be a mix. | JavaScript | @@ -55,6 +54,10 @@ type Props = {
...ParameterFieldProps,
isObjectVariable: boolean,
variablesContainers: Array<gdVariablesContainer>,
+ getVariableSourceFromVariableName: (
+ variableRootName: string,
+ projectScopedContainers: gdProjectScopedContainers
+ ) => VariablesContainer_SourceType, | import { LineStackLayout } from '../../UI/Layout';
import GlobalVariableIcon from '../../UI/CustomSvgIcons/GlobalVariable';
import SceneVariableIcon from '../../UI/CustomSvgIcons/SceneVariable';
import ObjectVariableIcon from '../../UI/CustomSvgIcons/ObjectVariable';
import LocalVariableIcon from '../../UI/CustomSvgIcons/LocalVariable';
import PropertyIcon from '../../UI/CustomSvgIcons/Settings';
import ParameterIcon from '../../UI/CustomSvgIcons/Parameter';
import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope';
import Link from '../../UI/Link';
import Add from '../../UI/CustomSvgIcons/Add';
const gd: libGDevelop = global.gd;
export type VariableDialogOpeningProps = {
variableName: string,
shouldCreate: boolean,
};
type Props = {
...ParameterFieldProps,
isObjectVariable: boolean,
variablesContainers: Array<gdVariablesContainer>,
getVariableSourceFromIdentifier: (
identifier: string,
projectScopedContainers: gdProjectScopedContainers
) => VariablesContainer_SourceType,
enumerateVariables: () => Array<EnumeratedVariable>,
forceDeclaration?: boolean,
onOpenDialog: (VariableDialogOpeningProps => void) | null,
};
type VariableNameQuickAnalyzeResult = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
export type VariableFieldInterface = {|
...ParameterFieldInterface,
updateAutocompletions: () => void,
|};
export const VariableNameQuickAnalyzeResults = {
OK: 0,
WRONG_QUOTE: 1,
WRONG_SPACE: 2,
WRONG_EXPRESSION: 3,
UNDECLARED_VARIABLE: 4,
NAME_COLLISION_WITH_OBJECT: 5,
PARAMETER_WITH_CHILD: 6,
PROPERTY_WITH_CHILD: 7,
};
export const getRootVariableName = (name: string): string => {
const dotPosition = name.indexOf('.'); | 4ian/GDevelop | newIDE/app/src/EventsSheet/ParameterFields/VariableField.js | suggestion | 1 |
otherProjectFile.fileMetadata.fileIdentifier
);
});
}
return false;
};
const getDashboardItemsToDisplay = ({
project,
currentFileMetadata,
allDashboardItems,
searchText,
searchClient,
currentPage,
orderBy,
}: {|
project: ?gdProject,
currentFileMetadata: ?FileMetadata,
allDashboardItems: ?Array<DashboardItem>,
searchText: string,
searchClient: Fuse,
currentPage: number,
orderBy: GamesDashboardOrderBy,
|}): ?Array<DashboardItem> => {
if (!allDashboardItems) return null;
let itemsToDisplay: DashboardItem[] = allDashboardItems;
if (searchText) {
// If there is a search, just return those items, ordered by the search relevance.
const searchResults = searchClient.search(
getFuseSearchQueryForMultipleKeys(searchText, [
'game.gameName',
'projectFiles.fileMetadata.name',
])
);
itemsToDisplay = searchResults.map(result => result.item);
} else {
// If there is no search, sort the items by the selected order.
itemsToDisplay =
orderBy === 'totalSessions'
? itemsToDisplay.sort(totalSessionsSort)
: orderBy === 'weeklySessions'
? itemsToDisplay.sort(lastWeekSessionsSort)
: orderBy === 'lastModifiedAt'
? itemsToDisplay.sort(lastModifiedAtSort)
: itemsToDisplay;
// If a project is opened, no search is done, and sorted by last modified date,
// then the opened project should be displayed first.
if (project && orderBy === 'lastModifiedAt') {
const currentProjectId = project.getProjectUuid(); | I don't know if this array should be copied with a destructuring operation because it can be sorted below, affecting both `itemsToDisplay` and `allDashboardItems` I think | JavaScript | @@ -146,13 +146,7 @@ const getDashboardItemsToDisplay = ({
orderBy: GamesDashboardOrderBy,
|}): ?Array<DashboardItem> => {
if (!allDashboardItems) return null;
- let itemsToDisplay: DashboardItem[] = allDashboardItems.filter(
- item =>
- // First, filter out unsaved games, unless they are the opened project.
- !item.game ||
- item.game.savedStatus !== 'draft' ||
- (project && item.game.id === project.getProjectUuid())
- );
+ let itemsToDisplay: DashboardItem[] = allDashboardItems; | otherProjectFile.fileMetadata.fileIdentifier
);
});
}
return false;
};
const getDashboardItemsToDisplay = ({
project,
currentFileMetadata,
allDashboardItems,
searchText,
searchClient,
currentPage,
orderBy,
}: {|
project: ?gdProject,
currentFileMetadata: ?FileMetadata,
allDashboardItems: ?Array<DashboardItem>,
searchText: string,
searchClient: Fuse,
currentPage: number,
orderBy: GamesDashboardOrderBy,
|}): ?Array<DashboardItem> => {
if (!allDashboardItems) return null;
let itemsToDisplay: DashboardItem[] = [...allDashboardItems];
if (searchText) {
// If there is a search, just return those items, ordered by the search relevance.
const searchResults = searchClient.search(
getFuseSearchQueryForMultipleKeys(searchText, [
'game.gameName',
'projectFiles.fileMetadata.name',
])
);
itemsToDisplay = searchResults.map(result => result.item);
} else {
// If there is no search, sort the items by the selected order.
if (orderBy) {
itemsToDisplay.sort(
orderBy === 'totalSessions'
? totalSessionsSort
: orderBy === 'weeklySessions'
? lastWeekSessionsSort
: lastModifiedAtSort
);
}
// If a project is opened, no search is done, and sorted by last modified date,
// then the opened project should be displayed first.
if (project && orderBy === 'lastModifiedAt') { | 4ian/GDevelop | newIDE/app/src/GameDashboard/GamesList.js | suggestion | 0.571 |
/** Base parameters for {@link gdjs.Cube3DRuntimeObject} */
export interface Cube3DObjectData extends Object3DData {
/** The base parameters of the Cube3D object */
content: Object3DDataContent & {
enableTextureTransparency: boolean;
facesOrientation: 'Y' | 'Z';
frontFaceResourceName: string;
backFaceResourceName: string;
backFaceUpThroughWhichAxisRotation: 'X' | 'Y';
leftFaceResourceName: string;
rightFaceResourceName: string;
topFaceResourceName: string;
bottomFaceResourceName: string;
frontFaceResourceRepeat: boolean;
backFaceResourceRepeat: boolean;
leftFaceResourceRepeat: boolean;
rightFaceResourceRepeat: boolean;
topFaceResourceRepeat: boolean;
bottomFaceResourceRepeat: boolean;
frontFaceVisible: boolean;
backFaceVisible: boolean;
leftFaceVisible: boolean;
rightFaceVisible: boolean;
topFaceVisible: boolean;
bottomFaceVisible: boolean;
color: THREE.Color;
materialType: 'Basic' | 'StandardWithoutMetalness';
};
}
type FaceName = 'front' | 'back' | 'left' | 'right' | 'top' | 'bottom';
const faceNameToBitmaskIndex = {
front: 0,
back: 1,
left: 2,
right: 3,
top: 4,
bottom: 5,
};
type Cube3DObjectNetworkSyncDataType = {
fo: 'Y' | 'Z';
bfu: 'X' | 'Y';
vfb: integer;
trfb: integer;
frn: [string, string, string, string, string, string];
mt: number;
};
type Cube3DObjectNetworkSyncData = Object3DNetworkSyncData &
Cube3DObjectNetworkSyncDataType;
| You should be able to go back to where content comes from.
Long story short, it comes from the project serialized in JSON, meaning that the possible types of this object can only be `null`, `string` or `number`, or an array of those, or a child JSON. So it cannot be a `THREE.Color`. You can find examples in the textInputRuntimeObject with the attribute `fillColor` for instance | TypeScript | @@ -24,10 +24,10 @@ namespace gdjs {
rightFaceVisible: boolean;
topFaceVisible: boolean;
bottomFaceVisible: boolean;
+ color: THREE.Color; | /** Base parameters for {@link gdjs.Cube3DRuntimeObject} */
export interface Cube3DObjectData extends Object3DData {
/** The base parameters of the Cube3D object */
content: Object3DDataContent & {
enableTextureTransparency: boolean;
facesOrientation: 'Y' | 'Z';
frontFaceResourceName: string;
backFaceResourceName: string;
backFaceUpThroughWhichAxisRotation: 'X' | 'Y';
leftFaceResourceName: string;
rightFaceResourceName: string;
topFaceResourceName: string;
bottomFaceResourceName: string;
frontFaceResourceRepeat: boolean;
backFaceResourceRepeat: boolean;
leftFaceResourceRepeat: boolean;
rightFaceResourceRepeat: boolean;
topFaceResourceRepeat: boolean;
bottomFaceResourceRepeat: boolean;
frontFaceVisible: boolean;
backFaceVisible: boolean;
leftFaceVisible: boolean;
rightFaceVisible: boolean;
topFaceVisible: boolean;
bottomFaceVisible: boolean;
tint: string;
materialType: 'Basic' | 'StandardWithoutMetalness';
};
}
type FaceName = 'front' | 'back' | 'left' | 'right' | 'top' | 'bottom';
const faceNameToBitmaskIndex = {
front: 0,
back: 1,
left: 2,
right: 3,
top: 4,
bottom: 5,
};
type Cube3DObjectNetworkSyncDataType = {
fo: 'Y' | 'Z';
bfu: 'X' | 'Y';
vfb: integer;
trfb: integer;
frn: [string, string, string, string, string, string];
mt: number;
tint: number;
};
type Cube3DObjectNetworkSyncData = Object3DNetworkSyncData &
Cube3DObjectNetworkSyncDataType; | 4ian/GDevelop | Extensions/3D/Cube3DRuntimeObject.ts | suggestion | 0.786 |
return this.isFaceAtIndexVisible(faceIndex);
}
/** @internal */
isFaceAtIndexVisible(faceIndex): boolean {
return (this._visibleFacesBitmask & (1 << faceIndex)) !== 0;
}
/** @internal */
shouldRepeatTextureOnFaceAtIndex(faceIndex): boolean {
return (this._textureRepeatFacesBitmask & (1 << faceIndex)) !== 0;
}
setFaceResourceName(faceName: FaceName, resourceName: string): void {
const faceIndex = faceNameToBitmaskIndex[faceName];
if (faceIndex === undefined) {
return;
}
if (this._faceResourceNames[faceIndex] === resourceName) {
return;
}
this._faceResourceNames[faceIndex] = resourceName;
this._renderer.updateFace(faceIndex);
}
setCubeColor(color: THREE.Color): void {
if (color === this._color) return;
this._color = color;
}
/** @internal */
getFaceAtIndexResourceName(faceIndex: integer): string {
return this._faceResourceNames[faceIndex];
}
getRenderer(): gdjs.RuntimeObject3DRenderer {
return this._renderer;
}
getBackFaceUpThroughWhichAxisRotation(): 'X' | 'Y' {
return this._backFaceUpThroughWhichAxisRotation;
}
setBackFaceUpThroughWhichAxisRotation(axis: 'X' | 'Y'): void {
this._backFaceUpThroughWhichAxisRotation = axis;
this._renderer.updateFace(faceNameToBitmaskIndex['back']);
}
getFacesOrientation(): 'Y' | 'Z' {
return this._facesOrientation;
} | This method is part of a public interface. We don't want to rely THREE objects for inputs. You can check `setFillColor` int he codebase to see how it's done in other objects. | TypeScript | @@ -203,10 +206,13 @@ namespace gdjs {
if (this._faceResourceNames[faceIndex] === resourceName) {
return;
}
-
this._faceResourceNames[faceIndex] = resourceName;
this._renderer.updateFace(faceIndex);
}
+ setCubeColor(color: THREE.Color): void { | if (faceIndex === undefined) {
return false;
}
return this.isFaceAtIndexVisible(faceIndex);
}
/** @internal */
isFaceAtIndexVisible(faceIndex): boolean {
return (this._visibleFacesBitmask & (1 << faceIndex)) !== 0;
}
/** @internal */
shouldRepeatTextureOnFaceAtIndex(faceIndex): boolean {
return (this._textureRepeatFacesBitmask & (1 << faceIndex)) !== 0;
}
setFaceResourceName(faceName: FaceName, resourceName: string): void {
const faceIndex = faceNameToBitmaskIndex[faceName];
if (faceIndex === undefined) {
return;
}
if (this._faceResourceNames[faceIndex] === resourceName) {
return;
}
this._faceResourceNames[faceIndex] = resourceName;
this._renderer.updateFace(faceIndex);
}
setTint(tint: string): void {
const tintInHex = gdjs.rgbOrHexStringToNumber(tint);
if (tintInHex === this._tint) return;
this._tint = tintInHex;
this._renderer.updateTint();
}
/** @internal */
getFaceAtIndexResourceName(faceIndex: integer): string {
return this._faceResourceNames[faceIndex];
}
getRenderer(): gdjs.RuntimeObject3DRenderer {
return this._renderer;
}
getBackFaceUpThroughWhichAxisRotation(): 'X' | 'Y' {
return this._backFaceUpThroughWhichAxisRotation;
}
setBackFaceUpThroughWhichAxisRotation(axis: 'X' | 'Y'): void {
this._backFaceUpThroughWhichAxisRotation = axis;
this._renderer.updateFace(faceNameToBitmaskIndex['back']); | 4ian/GDevelop | Extensions/3D/Cube3DRuntimeObject.ts | suggestion | 0.5 |
}
return runtimeObject
.getInstanceContainer()
.getGame()
.getImageManager()
.getThreeMaterial(runtimeObject.getFaceAtIndexResourceName(faceIndex), {
useTransparentTexture: runtimeObject.shouldUseTransparentTexture(),
forceBasicMaterial:
runtimeObject._materialType ===
gdjs.Cube3DRuntimeObject.MaterialType.Basic,
});
};
class Cube3DRuntimeObjectPixiRenderer extends gdjs.RuntimeObject3DRenderer {
private _cube3DRuntimeObject: gdjs.Cube3DRuntimeObject;
private _boxMesh: THREE.Mesh;
constructor(
runtimeObject: gdjs.Cube3DRuntimeObject,
instanceContainer: gdjs.RuntimeInstanceContainer
) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
// TODO (3D) - feature: support color instead of texture?
const materials: THREE.Material[] = [];
for (let i = 0; i < 6; i++) {
const material: THREE.Material = getFaceMaterial(
runtimeObject,
materialIndexToFaceIndex[i]
);
const basicMaterial: THREE.MeshBasicMaterial =
new THREE.MeshBasicMaterial();
basicMaterial.copy(material);
materials.push(
basicMaterial.map
? getFaceMaterial(runtimeObject, materialIndexToFaceIndex[i])
: new THREE.MeshBasicMaterial({ vertexColors: true })
);
}
let colors: number[] = [];
for (let i = 0; i < geometry.attributes.position.count; i++) {
colors.push(
runtimeObject._color.r,
runtimeObject._color.g,
runtimeObject._color.b
);
}
geometry.setAttribute(
'color', | Good idea to use a loop!
In JS, there's a more elegant way to do this, with a `map`.
So you could write:
```js
const materials = new Array(6).fill(0).map((_, index) => {
return material;
})
``` | TypeScript | @@ -75,14 +80,37 @@ namespace gdjs {
) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
// TODO (3D) - feature: support color instead of texture?
- const materials = [
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[0]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[1]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[2]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[3]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[4]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[5]),
- ];
+ const materials: THREE.Material[] = [];
+
+ for (let i = 0; i < 6; i++) { | .getThreeMaterial(runtimeObject.getFaceAtIndexResourceName(faceIndex), {
useTransparentTexture: runtimeObject.shouldUseTransparentTexture(),
forceBasicMaterial:
runtimeObject._materialType ===
gdjs.Cube3DRuntimeObject.MaterialType.Basic,
});
};
class Cube3DRuntimeObjectPixiRenderer extends gdjs.RuntimeObject3DRenderer {
private _cube3DRuntimeObject: gdjs.Cube3DRuntimeObject;
private _boxMesh: THREE.Mesh;
constructor(
runtimeObject: gdjs.Cube3DRuntimeObject,
instanceContainer: gdjs.RuntimeInstanceContainer
) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const materials: THREE.Material[] = new Array(6)
.fill(0)
.map((_, index) =>
getFaceMaterial(runtimeObject, materialIndexToFaceIndex[index])
);
const boxMesh = new THREE.Mesh(geometry, materials);
super(runtimeObject, instanceContainer, boxMesh);
this._boxMesh = boxMesh;
this._cube3DRuntimeObject = runtimeObject;
this.updateSize();
this.updatePosition();
this.updateRotation();
this.updateTint();
}
updateTint() {
const tints: number[] = [];
const normalizedTint = gdjs
.hexNumberToRGBArray(this._cube3DRuntimeObject._tint)
.map((component) => component / 255);
for (
let i = 0;
i < this._boxMesh.geometry.attributes.position.count;
i++
) {
tints.push(...normalizedTint);
}
this._boxMesh.geometry.setAttribute( | 4ian/GDevelop | Extensions/3D/Cube3DRuntimeObjectPixiRenderer.ts | suggestion | 0.857 |
};
class Cube3DRuntimeObjectPixiRenderer extends gdjs.RuntimeObject3DRenderer {
private _cube3DRuntimeObject: gdjs.Cube3DRuntimeObject;
private _boxMesh: THREE.Mesh;
constructor(
runtimeObject: gdjs.Cube3DRuntimeObject,
instanceContainer: gdjs.RuntimeInstanceContainer
) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
// TODO (3D) - feature: support color instead of texture?
const materials: THREE.Material[] = [];
for (let i = 0; i < 6; i++) {
const material: THREE.Material = getFaceMaterial(
runtimeObject,
materialIndexToFaceIndex[i]
);
const basicMaterial: THREE.MeshBasicMaterial = new THREE.MeshBasicMaterial();
basicMaterial.copy(material);
materials.push(
basicMaterial.map
? getFaceMaterial(runtimeObject, materialIndexToFaceIndex[i])
: new THREE.MeshBasicMaterial({ vertexColors: true })
);
}
let colors: number[] = [];
for (let i = 0; i < geometry.attributes.position.count; i++) {
colors.push(
runtimeObject._color.r,
runtimeObject._color.g,
runtimeObject._color.b
);
}
geometry.setAttribute(
'color',
new THREE.BufferAttribute(new Float32Array(colors), 3)
);
const boxMesh = new THREE.Mesh(geometry, materials);
super(runtimeObject, instanceContainer, boxMesh);
this._boxMesh = boxMesh;
this._cube3DRuntimeObject = runtimeObject;
this.updateSize();
this.updatePosition();
this.updateRotation(); | This seems unnecessary to me.
I feel like you could just do:
```js
const material = ...
materials.push(material)
```
since `getFaceMaterial` already returns a `MeshBasicMaterial` if no resource | TypeScript | @@ -75,14 +80,36 @@ namespace gdjs {
) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
// TODO (3D) - feature: support color instead of texture?
- const materials = [
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[0]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[1]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[2]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[3]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[4]),
- getFaceMaterial(runtimeObject, materialIndexToFaceIndex[5]),
- ];
+ const materials: THREE.Material[] = [];
+
+ for (let i = 0; i < 6; i++) {
+ const material: THREE.Material = getFaceMaterial(
+ runtimeObject,
+ materialIndexToFaceIndex[i]
+ );
+ const basicMaterial: THREE.MeshBasicMaterial = new THREE.MeshBasicMaterial();
+ basicMaterial.copy(material);
+ materials.push(
+ basicMaterial.map
+ ? getFaceMaterial(runtimeObject, materialIndexToFaceIndex[i])
+ : new THREE.MeshBasicMaterial({ vertexColors: true })
+ ); |
constructor(
runtimeObject: gdjs.Cube3DRuntimeObject,
instanceContainer: gdjs.RuntimeInstanceContainer
) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const materials: THREE.Material[] = new Array(6)
.fill(0)
.map((_, index) =>
getFaceMaterial(runtimeObject, materialIndexToFaceIndex[index])
);
const boxMesh = new THREE.Mesh(geometry, materials);
super(runtimeObject, instanceContainer, boxMesh);
this._boxMesh = boxMesh;
this._cube3DRuntimeObject = runtimeObject;
this.updateSize();
this.updatePosition();
this.updateRotation();
this.updateTint();
}
updateTint() {
const tints: number[] = [];
const normalizedTint = gdjs
.hexNumberToRGBArray(this._cube3DRuntimeObject._tint)
.map((component) => component / 255);
for (
let i = 0;
i < this._boxMesh.geometry.attributes.position.count;
i++
) {
tints.push(...normalizedTint);
}
this._boxMesh.geometry.setAttribute(
'color',
new THREE.BufferAttribute(new Float32Array(tints), 3)
);
}
updateFace(faceIndex: integer) {
const materialIndex = faceIndexToMaterialIndex[faceIndex];
if (materialIndex === undefined) return;
this._boxMesh.material[materialIndex] = getFaceMaterial(
this._cube3DRuntimeObject, | 4ian/GDevelop | Extensions/3D/Cube3DRuntimeObjectPixiRenderer.ts | suggestion | 0.857 |
// Delete actions.
// Don't allow removing project if opened, as it would not result in any change in the list.
// (because an opened project is always displayed)
if (isCurrentProjectOpened || projectsList.length > 1) {
// No delete action possible.
} else {
if (actions.length > 0) {
actions.push({
type: 'separator',
});
}
actions.push({
label: i18n._(t`Delete`),
click: async () => {
// Extract word translation to ensure it is not wrongly translated in the sentence.
const translatedConfirmText = i18n._(t`delete`);
const hasPlayerMessage = countOfSessionsLastWeek
? t`${countOfSessionsLastWeek} views on the last 7 days`
: t`No players`;
const hasBeenPublished = isPublishedOnGdGames
? t`Is published on gd.games`
: t`Not published`;
const message = t`You're deleting a game that has:${'\n\n'}
- ${i18n._(hasPlayerMessage)}
${'\n'}
- ${i18n._(hasBeenPublished)}
${'\n\n'}
If you continue the game and this project will be deleted.${'\n\n'}
This action is irreversible. Do you want to continue?`;
const answer = await showDeleteConfirmation({
title: t`Delete game`,
header: (
<GameThumbnail
gameName={gameName || 'unknown game'}
gameId={game ? game.id : undefined}
thumbnailUrl={gameThumbnailUrl}
background="light"
width={getThumbnailWidth({ isMobile })}
/>
),
message: message,
confirmButtonLabel: t`Delete game`,
fieldMessage: t`To confirm, type "${translatedConfirmText}"`,
confirmText: translatedConfirmText,
});
if (!answer) return; | I would change the text because here you can have a case:
`You're deleting a game that has: ... - is published`
I would suggest:
`You're deleting a game which: - has x views... - is published...`
| JavaScript | @@ -513,9 +518,34 @@ const GameDashboardCard = ({
// Extract word translation to ensure it is not wrongly translated in the sentence.
const translatedConfirmText = i18n._(t`delete`);
+ const hasPlayerMessage = countOfSessionsLastWeek
+ ? t`${countOfSessionsLastWeek} views on the last 7 days`
+ : t`No players`;
+ const hasBeenPublished = isPublishedOnGdGames
+ ? t`Is published on gd.games`
+ : t`Not published`;
+
+ const message = t`You're deleting a game that has:${'\n\n'} | // (because an opened project is always displayed)
if (isCurrentProjectOpened || projectsList.length > 1) {
// No delete action possible.
} else {
if (actions.length > 0) {
actions.push({
type: 'separator',
});
}
actions.push({
label: i18n._(t`Delete`),
click: async () => {
// Extract word translation to ensure it is not wrongly translated in the sentence.
const translatedConfirmText = i18n._(t`delete`);
const hasBeenPublished = isPublishedOnGdGames
? t`Is published on gd.games`
: t`Is not published on gd.games`;
const hasPlayerMessage = countOfSessionsLastWeek
? t`Had ${countOfSessionsLastWeek} players in the last week`
: t`Had no players in the last week`;
const message = t`You're deleting a game which:${'\n\n'}
- ${i18n._(hasBeenPublished)}
${'\n'}
- ${i18n._(hasPlayerMessage)}
${'\n\n'}
If you continue, the game and this project will be deleted.${'\n\n'}
This action is irreversible. Do you want to continue?`;
const answer = await showDeleteConfirmation({
title: t`Delete ${gameName}`,
header: renderThumbnail(),
message: message,
confirmButtonLabel: t`Delete game`,
fieldMessage: t`To confirm, type "${translatedConfirmText}"`,
confirmText: translatedConfirmText,
});
if (!answer) return;
// If the game is registered, unregister it.
// If it fails, this will throw, to prevent deleting a game with leaderboards or not owned.
if (game) {
try {
await onUnregisterGame();
} catch (error) {
console.error('Unable to unregister the game.', error);
// Alert is handled by onUnregisterGame. Just ensure we don't continue.
return; | 4ian/GDevelop | newIDE/app/src/GameDashboard/GameDashboardCard.js | suggestion | 0.643 |
.setFunctionName('isAnimationPaused');
// Deprecated
object
.addCondition(
'HasAnimationEnded',
_('Animation finished'),
_(
'Check if the animation being played by the Sprite object is finished.'
),
_('The animation of _PARAM0_ is finished'),
_('Animations and images'),
'res/conditions/animation24.png',
'res/conditions/animation.png'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.markAsSimple()
.setHidden()
.setFunctionName('hasAnimationEnded');
object
.addScopedAction(
'SetCrossfadeDuration',
_('Set cross fade duration'),
_('Set the duration of the cross fading between two animations.'),
'Set cross fading duration of _PARAM0_ to _PARAM1_',
_('Duration'),
'res/conditions/3d_box.svg',
'res/conditions/3d_box.svg'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.addParameter('number', _('Cross fade duration'), '', false)
.setFunctionName('setCrossfadeDuration');
}
const Cube3DObject = new gd.ObjectJsImplementation();
Cube3DObject.updateProperty = function (propertyName, newValue) {
const objectContent = this.content;
if (
propertyName === 'width' ||
propertyName === 'height' ||
propertyName === 'depth'
) {
objectContent[propertyName] = parseFloat(newValue);
return true;
}
if (
propertyName === 'frontFaceResourceName' ||
propertyName === 'backFaceResourceName' ||
propertyName === 'leftFaceResourceName' ||
propertyName === 'rightFaceResourceName' || | I think in english it's a single word usually:
```suggestion
_('Set crossfade duration'),
_('Set the crossfade duration when switching to a new animation.'),
'Set crossfade duration of _PARAM0_ to _PARAM1_',
``` | JavaScript | @@ -800,6 +800,20 @@ module.exports = {
.markAsSimple()
.setHidden()
.setFunctionName('hasAnimationEnded');
+
+ object
+ .addScopedAction(
+ 'SetCrossfadeDuration',
+ _('Set cross fade duration'),
+ _('Set the duration of the cross fading between two animations.'),
+ 'Set cross fading duration of _PARAM0_ to _PARAM1_', | .setFunctionName('isAnimationPaused');
// Deprecated
object
.addCondition(
'HasAnimationEnded',
_('Animation finished'),
_(
'Check if the animation being played by the Sprite object is finished.'
),
_('The animation of _PARAM0_ is finished'),
_('Animations and images'),
'res/conditions/animation24.png',
'res/conditions/animation.png'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.markAsSimple()
.setHidden()
.setFunctionName('hasAnimationEnded');
object
.addScopedAction(
'SetCrossfadeDuration',
_('Set crossfade duration'),
_('Set the crossfade duration when switching to a new animation.'),
_('Set crossfade duration of _PARAM0_ to _PARAM1_'),
_('Duration'),
'res/conditions/animation24.png',
'res/conditions/animation.svg'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.addParameter('number', _('Crossfade duration'), '', false)
.setFunctionName('setCrossfadeDuration');
}
const Cube3DObject = new gd.ObjectJsImplementation();
Cube3DObject.updateProperty = function (propertyName, newValue) {
const objectContent = this.content;
if (
propertyName === 'width' ||
propertyName === 'height' ||
propertyName === 'depth'
) {
objectContent[propertyName] = parseFloat(newValue);
return true;
}
if (
propertyName === 'frontFaceResourceName' ||
propertyName === 'backFaceResourceName' ||
propertyName === 'leftFaceResourceName' ||
propertyName === 'rightFaceResourceName' || | 4ian/GDevelop | Extensions/3D/JsExtension.js | suggestion | 0.786 |
_('Animation finished'),
_(
'Check if the animation being played by the Sprite object is finished.'
),
_('The animation of _PARAM0_ is finished'),
_('Animations and images'),
'res/conditions/animation24.png',
'res/conditions/animation.png'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.markAsSimple()
.setHidden()
.setFunctionName('hasAnimationEnded');
object
.addScopedAction(
'SetCrossfadeDuration',
_('Set cross fade duration'),
_('Set the duration of the cross fading between two animations.'),
'Set cross fading duration of _PARAM0_ to _PARAM1_',
_('Duration'),
'res/conditions/3d_box.svg',
'res/conditions/3d_box.svg'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.addParameter('number', _('Cross fade duration'), '', false)
.setFunctionName('setCrossfadeDuration');
}
const Cube3DObject = new gd.ObjectJsImplementation();
Cube3DObject.updateProperty = function (propertyName, newValue) {
const objectContent = this.content;
if (
propertyName === 'width' ||
propertyName === 'height' ||
propertyName === 'depth'
) {
objectContent[propertyName] = parseFloat(newValue);
return true;
}
if (
propertyName === 'frontFaceResourceName' ||
propertyName === 'backFaceResourceName' ||
propertyName === 'leftFaceResourceName' ||
propertyName === 'rightFaceResourceName' ||
propertyName === 'topFaceResourceName' ||
propertyName === 'bottomFaceResourceName' ||
propertyName === 'backFaceUpThroughWhichAxisRotation' ||
propertyName === 'facesOrientation' ||
propertyName === 'materialType' ||
propertyName === 'tint' | ```suggestion
.addParameter('number', _('Crossfade duration'), '', false)
``` | JavaScript | @@ -800,6 +800,20 @@ module.exports = {
.markAsSimple()
.setHidden()
.setFunctionName('hasAnimationEnded');
+
+ object
+ .addScopedAction(
+ 'SetCrossfadeDuration',
+ _('Set cross fade duration'),
+ _('Set the duration of the cross fading between two animations.'),
+ 'Set cross fading duration of _PARAM0_ to _PARAM1_',
+ _('Duration'),
+ 'res/conditions/3d_box.svg',
+ 'res/conditions/3d_box.svg'
+ )
+ .addParameter('object', _('3D model'), 'Model3DObject', false)
+ .addParameter('number', _('Cross fade duration'), '', false) | _('Animation finished'),
_(
'Check if the animation being played by the Sprite object is finished.'
),
_('The animation of _PARAM0_ is finished'),
_('Animations and images'),
'res/conditions/animation24.png',
'res/conditions/animation.png'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.markAsSimple()
.setHidden()
.setFunctionName('hasAnimationEnded');
object
.addScopedAction(
'SetCrossfadeDuration',
_('Set crossfade duration'),
_('Set the crossfade duration when switching to a new animation.'),
_('Set crossfade duration of _PARAM0_ to _PARAM1_'),
_('Duration'),
'res/conditions/animation24.png',
'res/conditions/animation.svg'
)
.addParameter('object', _('3D model'), 'Model3DObject', false)
.addParameter('number', _('Crossfade duration'), '', false)
.setFunctionName('setCrossfadeDuration');
}
const Cube3DObject = new gd.ObjectJsImplementation();
Cube3DObject.updateProperty = function (propertyName, newValue) {
const objectContent = this.content;
if (
propertyName === 'width' ||
propertyName === 'height' ||
propertyName === 'depth'
) {
objectContent[propertyName] = parseFloat(newValue);
return true;
}
if (
propertyName === 'frontFaceResourceName' ||
propertyName === 'backFaceResourceName' ||
propertyName === 'leftFaceResourceName' ||
propertyName === 'rightFaceResourceName' ||
propertyName === 'topFaceResourceName' ||
propertyName === 'bottomFaceResourceName' ||
propertyName === 'backFaceUpThroughWhichAxisRotation' ||
propertyName === 'facesOrientation' ||
propertyName === 'materialType' ||
propertyName === 'tint' | 4ian/GDevelop | Extensions/3D/JsExtension.js | suggestion | 0.571 |
/**
GDevelop - Particle System Extension
Copyright (c) 2010-2016 Florian Rival (Florian.Rival@gmail.com)
This project is released under the MIT License.
*/
#include "Model3DObjectConfiguration.h"
#include "GDCore/CommonTools.h"
#include "GDCore/IDE/Project/ArbitraryResourceWorker.h"
#include "GDCore/Project/InitialInstance.h"
#include "GDCore/Project/MeasurementUnit.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/Project.h"
#include "GDCore/Project/PropertyDescriptor.h"
#include "GDCore/Serialization/SerializerElement.h"
#include "GDCore/Tools/Localization.h"
using namespace std;
Model3DObjectConfiguration::Model3DObjectConfiguration()
: width(100), height(100), depth(100), rotationX(0), rotationY(0),
rotationZ(0), modelResourceName(""), materialType("StandardWithoutMetalness"),
originLocation("ModelOrigin"), centerLocation("ModelOrigin"),
keepAspectRatio(true), crossFadeDuration(0.0f) {}
bool Model3DObjectConfiguration::UpdateProperty(const gd::String &propertyName,
const gd::String &newValue) {
if (propertyName == "width") {
width = newValue.To<double>();
return true;
}
if (propertyName == "height") {
height = newValue.To<double>();
return true;
}
if (propertyName == "depth") {
depth = newValue.To<double>();
return true;
}
if (propertyName == "rotationX") {
rotationX = newValue.To<double>();
return true;
}
if (propertyName == "rotationY") {
rotationY = newValue.To<double>();
return true;
}
if (propertyName == "rotationZ") {
rotationZ = newValue.To<double>(); | Nitpicking, here and everywhere: `crossfadeDuration` (your PR contains a mix of crossFade and crossfade). Let's use crossfade everywhere it's possible. | C++ | @@ -23,7 +23,7 @@ Model3DObjectConfiguration::Model3DObjectConfiguration()
: width(100), height(100), depth(100), rotationX(0), rotationY(0),
rotationZ(0), modelResourceName(""), materialType("StandardWithoutMetalness"),
originLocation("ModelOrigin"), centerLocation("ModelOrigin"),
- keepAspectRatio(true) {}
+ keepAspectRatio(true), crossFadeDuration(0.0f) {} | /**
GDevelop - Particle System Extension
Copyright (c) 2010-2016 Florian Rival (Florian.Rival@gmail.com)
This project is released under the MIT License.
*/
#include "Model3DObjectConfiguration.h"
#include "GDCore/CommonTools.h"
#include "GDCore/IDE/Project/ArbitraryResourceWorker.h"
#include "GDCore/Project/InitialInstance.h"
#include "GDCore/Project/MeasurementUnit.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/Project.h"
#include "GDCore/Project/PropertyDescriptor.h"
#include "GDCore/Serialization/SerializerElement.h"
#include "GDCore/Tools/Localization.h"
using namespace std;
Model3DObjectConfiguration::Model3DObjectConfiguration()
: width(100), height(100), depth(100), rotationX(0), rotationY(0),
rotationZ(0), modelResourceName(""), materialType("StandardWithoutMetalness"),
originLocation("ModelOrigin"), centerLocation("ModelOrigin"),
keepAspectRatio(true), crossfadeDuration(0.0f) {}
bool Model3DObjectConfiguration::UpdateProperty(const gd::String &propertyName,
const gd::String &newValue) {
if (propertyName == "width") {
width = newValue.To<double>();
return true;
}
if (propertyName == "height") {
height = newValue.To<double>();
return true;
}
if (propertyName == "depth") {
depth = newValue.To<double>();
return true;
}
if (propertyName == "rotationX") {
rotationX = newValue.To<double>();
return true;
}
if (propertyName == "rotationY") {
rotationY = newValue.To<double>();
return true;
}
if (propertyName == "rotationZ") {
rotationZ = newValue.To<double>(); | 4ian/GDevelop | Extensions/3D/Model3DObjectConfiguration.cpp | suggestion | 0.571 |
let rewardedVideoLoading = false; // Becomes true when the video is loading.
let rewardedVideoReady = false; // Becomes true when the video is loaded and ready to be shown.
let rewardedVideoShowing = false; // Becomes true when the video is showing.
let rewardedVideoRewardReceived = false; // Becomes true when the video is closed and the reward is received.
let rewardedVideoErrored = false; // Becomes true when the video fails to load.
let npaValue = '0'; // 0 means that the user has consented to personalized ads, 1 means that the user has not consented to personalized ads.
// Admob initialization listener
document.addEventListener(
'deviceready',
async () => {
logger.info('Starting AdMob.');
isStarting = true;
if (cordova.platformId === 'ios') {
/*
trackingStatus:
0 = notDetermined
1 = restricted
2 = denied
3 = authorized
*/
let trackingStatus = await consent.trackingAuthorizationStatus();
// If tracking is not determined, we ask the user for tracking authorization.
if (trackingStatus === 0) {
trackingStatus = await consent.requestTrackingAuthorization();
}
// If tracking is restricted or denied, we set npaValue to 1.
if (trackingStatus === 1 || trackingStatus === 2) {
npaValue = '1';
}
// otherwise, we set npaValue to 0.
npaValue = '0';
}
const consentStatus = await consent.getConsentStatus();
if (consentStatus === consent.ConsentStatus.Required) {
await consent.requestInfoUpdate();
}
await consent.loadAndShowIfRequired();
if (await consent.canRequestAds()) {
await admob.start();
logger.info('AdMob successfully started.');
isStarting = false; | I wonder if it's a good idea to delay this by 2 seconds, and offer:
- an action to cancel automatic consent dialog/tracking authorization display.
- an action to do it manually.
So that if I want to postpone this (because it's better if my player plays a bit or click a button in the menu, so I have the opportunity to tell them "we'll ask for your consent, please say yes!"), I can do by:
- using the first action at launch of my game
- using the second action whenever I want. | TypeScript | @@ -108,22 +109,53 @@ namespace gdjs {
let rewardedVideoRewardReceived = false; // Becomes true when the video is closed and the reward is received.
let rewardedVideoErrored = false; // Becomes true when the video fails to load.
- let npaValue = '0'; // TODO: expose an API to change this and also an automatic way using the consent SDK.
+ let npaValue = '0'; // 0 means that the user has consented to personalized ads, 1 means that the user has not consented to personalized ads.
// Admob initialization listener
document.addEventListener(
'deviceready',
async () => {
- // Obtain user consent ?
-
logger.info('Starting AdMob.');
isStarting = true;
- await admob.start();
+ if (cordova.platformId === 'ios') { | let rewardedVideoLoading = false; // Becomes true when the video is loading.
let rewardedVideoReady = false; // Becomes true when the video is loaded and ready to be shown.
let rewardedVideoShowing = false; // Becomes true when the video is showing.
let rewardedVideoRewardReceived = false; // Becomes true when the video is closed and the reward is received.
let rewardedVideoErrored = false; // Becomes true when the video fails to load.
let npaValue = '0'; // 0 means that the user has consented to personalized ads, 1 means that the user has not consented to personalized ads.
let setupTimeoutId: NodeJS.Timeout | null = null;
const askForConsentAndInitializeAdmob = async () => {
if (admobStarted) {
logger.warn('AdMob is already started.');
return;
}
if (isStarting) {
logger.warn('AdMob is already starting.');
return;
}
try {
logger.info('Starting AdMob.');
isStarting = true;
if (cordova.platformId === 'ios') {
try {
/*
trackingStatus:
0 = notDetermined
1 = restricted
2 = denied
3 = authorized
*/
let trackingStatus = await consent.trackingAuthorizationStatus();
// If tracking is not determined, we ask the user for tracking authorization.
if (trackingStatus === 0) {
trackingStatus = await consent.requestTrackingAuthorization();
}
// If tracking is restricted or denied, we set npaValue to 1.
if (trackingStatus === 1 || trackingStatus === 2) {
npaValue = '1';
}
// otherwise, we set npaValue to 0.
npaValue = '0';
} catch (error) {
logger.error(
'Error while asking for tracking authorization, continuing:', | 4ian/GDevelop | Extensions/AdMob/admobtools.ts | security | 0.5 |
'SetTestMode',
_('Enable test mode'),
_(
'Activate or deactivate the test mode ("development" mode).\n' +
'When activated, tests ads will be served instead of real ones.\n' +
'\n' +
'It is important to enable test ads during development so that you can click on them without ' +
'charging advertisers. If you click on too many ads without being in test mode, you risk your ' +
'account being flagged for invalid activity.'
),
_('Enable test mode (serving test ads, for development): _PARAM0_'),
'',
'JsPlatform/Extensions/admobicon24.png',
'JsPlatform/Extensions/admobicon16.png'
)
.addParameter('yesorno', _('Enable test mode?'), '', false)
.getCodeExtraInformation()
.setIncludeFile('Extensions/AdMob/admobtools.js')
.setFunctionName('gdjs.adMob.setTestMode');
extension
.addAction(
'PreventAdmobAutoInitialization',
_('Prevent Admob auto initialization'),
_(
'Prevent Admob from initializing automatically. You will need to call InitAdmob manually.\n' +
'This is useful if you want to control when the consent dialog will be shown (for example, after the user has accepted your game terms).'
),
_('Prevent Admob auto initialization'),
'',
'JsPlatform/Extensions/admobicon24.png',
'JsPlatform/Extensions/admobicon16.png'
)
.getCodeExtraInformation()
.setIncludeFile('Extensions/AdMob/admobtools.js')
.setFunctionName('gdjs.adMob.preventAdmobAutoInitialization');
extension
.addAction(
'InitializeAdmob',
_('Initialize Admob'),
_('Manually initialize Admob.'),
_(
'Initialize Admob manually. This will trigger the consent dialog if needed, and then load the ads.\n' +
'Use this action if you have disabled the auto init and want to control when the consent dialog will be shown.'
),
_('Initialize Admob'),
'',
'JsPlatform/Extensions/admobicon24.png',
'JsPlatform/Extensions/admobicon16.png'
) | ```suggestion
'Prevent AdMob from initializing automatically. You will need to call the "Initialize AdMob" action instead.\n' +
``` | JavaScript | @@ -93,6 +93,41 @@ module.exports = {
.setIncludeFile('Extensions/AdMob/admobtools.js')
.setFunctionName('gdjs.adMob.setTestMode');
+ extension
+ .addAction(
+ 'PreventAdmobAutoInitialization',
+ _('Prevent Admob auto initialization'),
+ _(
+ 'Prevent Admob from initializing automatically. You will need to call InitAdmob manually.\n' + | 'SetTestMode',
_('Enable test mode'),
_(
'Activate or deactivate the test mode ("development" mode).\n' +
'When activated, tests ads will be served instead of real ones.\n' +
'\n' +
'It is important to enable test ads during development so that you can click on them without ' +
'charging advertisers. If you click on too many ads without being in test mode, you risk your ' +
'account being flagged for invalid activity.'
),
_('Enable test mode (serving test ads, for development): _PARAM0_'),
'',
'JsPlatform/Extensions/admobicon24.png',
'JsPlatform/Extensions/admobicon16.png'
)
.addParameter('yesorno', _('Enable test mode?'), '', false)
.getCodeExtraInformation()
.setIncludeFile('Extensions/AdMob/admobtools.js')
.setFunctionName('gdjs.adMob.setTestMode');
extension
.addAction(
'PreventAdmobAutoInitialization',
_('Prevent AdMob auto initialization'),
_(
'Prevent AdMob from initializing automatically. You will need to call "Initialize AdMob" action manually.\n' +
'This is useful if you want to control when the consent dialog will be shown (for example, after the user has accepted your game terms).'
),
_('Prevent AdMob auto initialization'),
'',
'JsPlatform/Extensions/admobicon24.png',
'JsPlatform/Extensions/admobicon16.png'
)
.getCodeExtraInformation()
.setIncludeFile('Extensions/AdMob/admobtools.js')
.setFunctionName('gdjs.adMob.preventAdmobAutoInitialization');
extension
.addAction(
'InitializeAdmob',
_('Initialize AdMob manually'),
_(
'Initialize AdMob manually. This will trigger the consent dialog if needed, and then load the ads.\n' +
'Use this action if you have disabled the auto init and want to control when the consent dialog will be shown.'
),
_('Initialize AdMob'),
'',
'JsPlatform/Extensions/admobicon24.png',
'JsPlatform/Extensions/admobicon16.png'
)
.getCodeExtraInformation() | 4ian/GDevelop | Extensions/AdMob/JsExtension.js | suggestion | 0.786 |
End of preview. Expand
in Data Studio
CodeReview-Bench
A benchmark for evaluating models on two code review tasks, curated from ronantakizawa/github-codereview.
Tasks
1. Code Editing
Given code and a reviewer comment, apply the requested change.
- Input:
before_code,reviewer_comment,language,diff_context - Target:
after_code
from datasets import load_dataset
ds = load_dataset("ronantakizawa/codereview-bench", "code-editing")
example = ds["test"][0]
prompt = f"""Apply the following review comment to the code.
Review: {example['reviewer_comment']}
Code:
{example['before_code']}
Updated code:"""
2. Comment Generation
Given a code diff, generate the review comment a human reviewer would write.
- Input:
before_code,after_code,diff_context,language - Target:
reviewer_comment
ds = load_dataset("ronantakizawa/codereview-bench", "comment-generation")
example = ds["test"][0]
prompt = f"""Review the following code change and provide feedback.
Before:
{example['before_code']}
After:
{example['after_code']}
Review comment:"""
Filtering Criteria
This benchmark is a quality-filtered subset of the full dataset:
| Filter | Threshold |
|---|---|
| Positive examples only | is_negative = False |
| Quality score | >= 0.5 |
| Comment length | >= 50 characters |
| Code context | >= 10 lines (before and after) |
| Comment types | bug, security, performance, refactor, suggestion |
Excluded: nitpick, style, question, and negative examples.
Schema
Code Editing
| Column | Type | Role |
|---|---|---|
before_code |
string | Input |
reviewer_comment |
string | Input |
language |
string | Input |
diff_context |
string | Input |
after_code |
string | Target |
repo_name |
string | Metadata |
file_path |
string | Metadata |
comment_type |
string | Metadata |
quality_score |
float | Metadata |
Comment Generation
| Column | Type | Role |
|---|---|---|
before_code |
string | Input |
after_code |
string | Input |
diff_context |
string | Input |
language |
string | Input |
reviewer_comment |
string | Target |
repo_name |
string | Metadata |
file_path |
string | Metadata |
comment_type |
string | Metadata |
quality_score |
float | Metadata |
Evaluation
Code Editing
- CodeBLEU: Measures structural and syntactic similarity of generated code
- Exact match: Percentage of outputs matching the target exactly
- Edit similarity: Normalized edit distance between generated and target code
Comment Generation
- BERTScore: Semantic similarity between generated and reference comments
- ROUGE-L: Longest common subsequence overlap
- Human evaluation: Recommended for final assessment — automated metrics correlate poorly with review quality
Splits
| Split | Description |
|---|---|
| train | Training data (90%) |
| test | Held-out evaluation (5%) |
| validation | Development/tuning (5%) |
Splits are repo-deterministic — no repo appears in multiple splits.
Citation
@dataset{takizawa2026codereviewbench,
title={CodeReview-Bench: A Benchmark for Review-Driven Code Changes},
author={Takizawa, Ronan},
year={2026},
publisher={Hugging Face},
url={https://huggingface.co/datasets/ronantakizawa/codereview-bench}
}
- Downloads last month
- 38