diff --git a/src/serialization/sb2.js b/src/serialization/sb2.js index 7b6defd1d..affdc2868 100644 --- a/src/serialization/sb2.js +++ b/src/serialization/sb2.js @@ -12,6 +12,7 @@ const Color = require('../util/color'); const log = require('../util/log'); const uid = require('../util/uid'); const StringUtil = require('../util/string-util'); +const MathUtil = require('../util/math-util'); const specMap = require('./sb2_specmap'); const Comment = require('../engine/comment'); const Variable = require('../engine/variable'); @@ -642,7 +643,10 @@ const parseScratchObject = function (object, runtime, extensions, topLevel, zip) target.visible = object.visible; } if (object.hasOwnProperty('currentCostumeIndex')) { - target.currentCostume = Math.round(object.currentCostumeIndex); + // Current costume index can sometimes be a floating + // point number, use Math.floor to come up with an appropriate index + // and clamp it to the actual number of costumes the object has for good measure. + target.currentCostume = MathUtil.clamp(Math.floor(object.currentCostumeIndex), 0, object.costumes.length - 1); } if (object.hasOwnProperty('rotationStyle')) { if (object.rotationStyle === 'none') { diff --git a/src/serialization/sb3.js b/src/serialization/sb3.js index bcea2c702..254257069 100644 --- a/src/serialization/sb3.js +++ b/src/serialization/sb3.js @@ -447,6 +447,13 @@ const serializeTarget = function (target, extensions) { obj.broadcasts = vars.broadcasts; [obj.blocks, targetExtensions] = serializeBlocks(target.blocks); obj.comments = serializeComments(target.comments); + + // TODO remove this check/patch when (#1901) is fixed + if (target.currentCostume < 0 || target.currentCostume >= target.costumes.length) { + log.warn(`currentCostume property for target ${target.name} is out of range`); + target.currentCostume = MathUtil.clamp(target.currentCostume, 0, target.costumes.length - 1); + } + obj.currentCostume = target.currentCostume; obj.costumes = target.costumes.map(serializeCostume); obj.sounds = target.sounds.map(serializeSound); @@ -1007,7 +1014,7 @@ const parseScratchObject = function (object, runtime, extensions, zip) { target.visible = object.visible; } if (object.hasOwnProperty('currentCostume')) { - target.currentCostume = object.currentCostume; + target.currentCostume = MathUtil.clamp(object.currentCostume, 0, object.costumes.length - 1); } if (object.hasOwnProperty('rotationStyle')) { target.rotationStyle = object.rotationStyle;