Do you think the default RMMV damage formula evaluation can be hard to debug?

I suspect both Game_Action.prototype.evalDamageFormula and Game_Action.prototype.applyGuard can be quite hard to debug:

Spoiler
Game_Action.prototype.evalDamageFormula = function(target) { try { var item = this.item(); var a = this.subject(); var b = target; var v = $gameVariables._data; var sign = ([3, 4].contains(item.damage.type) ? -1 : 1); return Math.max(eval(item.damage.formula), 0) * sign; } catch (e) { return 0; }};
Code:
Game_Action.prototype.applyGuard = function(damage, target) {    return damage / (damage > 0 && target.isGuard() ? 2 * target.grd : 1);};
Right now I can find 2 problems for Game_Action.prototype.evalDamageFormula and 1 problem for Game_Action.prototype.applyGuard:

Spoiler
Game_Action.prototype.evalDamageFormula -

1. If eval(item.damage.formula) returns NaN, Math.max(eval(item.damage.formula), 0) * sign will also return NaN, which won't be caught by catch (e) and will be carried all along as all the subsequent validation checks will fail to stop NaN from being passed, causing the final hp/mp to be NaN.

2. If an exception's thrown which is caught by catch (e), 0 will be returned instead, meaning such exception handling is effectively hiding the error, as sometimes a damage formula can legitimately return 0.

Game_Action.prototype.applyGuard -

1. If at least 1 of the targets having grd as 0% are guarding when hit, damage / (damage > 0 && target.isGuard() ? 2 * target.grd : 1) will return NaN which will be carried all along as all the subsequent validation checks will fail to stop NaN from being passed, causing the final hp/mp to be NaN.
The below damage flow(from making hp/mp damage to setting the final hp/mp value) shows why the return value of Game_Action.prototype.evalDamageFormula/Game_Action.prototype.applyGuard will be carried all along and unstopped by all the subsequent validation checks, leading to the final hp/mp being NaN:

Spoiler
Game_Action.prototype.makeDamageValue = function(target, critical) { var item = this.item(); var baseValue = this.evalDamageFormula(target); var value = baseValue * this.calcElementRate(target); if (this.isPhysical()) { value *= target.pdr; } if (this.isMagical()) { value *= target.mdr; } if (baseValue < 0) { value *= target.rec; } if (critical) { value = this.applyCritical(value); } value = this.applyVariance(value, item.damage.variance); value = this.applyGuard(value, target); value = Math.round(value); return value;};Game_Action.prototype.executeDamage = function(target, value) { var result = target.result(); if (value === 0) { result.critical = false; } if (this.isHpEffect()) { this.executeHpDamage(target, value); } if (this.isMpEffect()) { this.executeMpDamage(target, value); }};Game_Action.prototype.executeHpDamage = function(target, value) { if (this.isDrain()) { value = Math.min(target.hp, value); } this.makeSuccess(target); target.gainHp(-value); if (value > 0) { target.onDamage(value); } this.gainDrainedHp(value);};Game_Action.prototype.executeMpDamage = function(target, value) { if (!this.isMpRecover()) { value = Math.min(target.mp, value); } if (value !== 0) { this.makeSuccess(target); } target.gainMp(-value); this.gainDrainedMp(value);};Game_Action.prototype.gainDrainedHp = function(value) { if (this.isDrain()) { this.subject().gainHp(value); }};Game_Action.prototype.gainDrainedMp = function(value) { if (this.isDrain()) { this.subject().gainMp(value); }};
Code:
Game_Battler.prototype.gainHp = function(value) {    this._result.hpDamage = -value;    this._result.hpAffected = true;    this.setHp(this.hp + value);};Game_Battler.prototype.gainMp = function(value) {    this._result.mpDamage = -value;    this.setMp(this.mp + value);};
Code:
Game_BattlerBase.prototype.setHp = function(hp) {    this._hp = hp;    this.refresh();};Game_BattlerBase.prototype.setMp = function(mp) {    this._mp = mp;    this.refresh();};
Code:
Game_BattlerBase.prototype.refresh = function() {    this.stateResistSet().forEach(function(stateId) {        this.eraseState(stateId);    }, this);    this._hp = this._hp.clamp(0, this.mhp);    this._mp = this._mp.clamp(0, this.mmp);    this._tp = this._tp.clamp(0, this.maxTp());};
Code:
/** * Returns a number whose value is limited to the given range. * * @method Number.prototype.clamp * @param {Number} min The lower boundary * @param {Number} max The upper boundary * @return {Number} A number in the range (min, max) */Number.prototype.clamp = function(min, max) {    return Math.min(Math.max(this, min), max);};
I'd suggest both Game_Action.prototype.evalDamageFormula and Game_Action.prototype.applyGuard to be changed into something like these:

Spoiler
Game_Action.prototype.evalDamageFormula = function(target) { try { var item = this.item(); var a = this.subject(); var b = target; var v = $gameVariables._data; var sign = ([3, 4].contains(item.damage.type) ? -1 : 1); // Rewritten var value = Math.max(eval(item.damage.formula), 0) * sign; if (isNan(value)) { console.log("The damage formula: " + item.damage.formula + " of item: " + item.name + " used by subject: " + a.name + " targeting target: " + b.name + " has return NaN."); // Exceptions can also be thrown right afterwards if it'd do more good than harm here in most cases } return value; // } catch (e) { // Added console.log("The damage formula: " + item.damage.formula + " of item: " + item.name + " used by subject: " + a.name + " targeting target: " + b.name + " has caused the below error:"); console.log(e.name, e.message); // return 0; }};
Code:
Game_Action.prototype.applyGuard = function(damage, target) {    var value = damage / (damage > 0 && target.isGuard() ? 2 * target.grd : 1);    if (isNan(value)) {    console.log("The grd of target: " + target.name + " is 0");    // Exceptions can also be thrown right afterwards if it'd do more good than harm here in most cases    }};
If throwing exceptions here can become too intrusive, RMMV users can still keep the console open and constantly check what's logged there.

Do you think the default RMMV damage formula evaluation can be hard to debug? Let's share your experiences, observations and views here 🙂
I don't have too much trouble debugging the damage formula.  Its a single section of code I need to debug, and I just write my formulas in Notepad++ and recheck things after I find the area that is incorrect.

The trick is not writing a super long and complicated damage formula.  For instance, when I wrote a dungeons and dragons damage formula, I just put the sections in one by one and tested them. Starting with the d20 roll

x = Math.floor(((Math.random() * 20) + 1) + ((a.atk - 10) / 2))If that returned a number aside from 0, and a random number at that, then I knew that part of the code was correct.  slowly I'd add in pieces and when I would get 0 constantly, I'd know exactly where the error was.

The problem most people come across when they try to work in any programming language, is that they try to do too much before testing their code.  It's beneficial to test your code every time you add something new.  Otherwise, you can be looking for that one out of place ; and take hours.

Of course, this doesn't account for errors that show up in earlier parts of the code because the new code broke it. 

my point is its not complicated to debug the damage formula because its just one area of code that is easy to edit into parts and test.  Its not like an entire plugin or script that is 500+ lines of code that you have to sift through with no error code to guide you.  
I don't have too much trouble debugging the damage formula.  Its a single section of code I need to debug, and I just write my formulas in Notepad++ and recheck things after I find the area that is incorrect.

The trick is not writing a super long and complicated damage formula.  For instance, when I wrote a dungeons and dragons damage formula, I just put the sections in one by one and tested them. Starting with the d20 roll

x = Math.floor(((Math.random() * 20) + 1) + ((a.atk - 10) / 2))If that returned a number aside from 0, and a random number at that, then I knew that part of the code was correct.  slowly I'd add in pieces and when I would get 0 constantly, I'd know exactly where the error was.

The problem most people come across when they try to work in any programming language, is that they try to do too much before testing their code.  It's beneficial to test your code every time you add something new.  Otherwise, you can be looking for that one out of place ; and take hours.

Of course, this doesn't account for errors that show up in earlier parts of the code because the new code broke it. 

my point is its not complicated to debug the damage formula because its just one area of code that is easy to edit into parts and test.  Its not like an entire plugin or script that is 500+ lines of code that you have to sift through with no error code to guide you.  
How about cases where you're a plugin developer, some users of some of your plugins reported a bug, and the root cause turned out to be some damage formulae written by some of them, after an extremely ridiculous amount of effort trying to debug the issues? I've seen some cases that are exactly this and I suspect some of my cases are actually this too(I've also encounter a case where an user really set the grd of a battler to be 0%) 🙂
Here's the thing though.  For the plugin error to be caused by the damage formula, it would mean the damage formula would try to reference something in the plugin and that either returned an error or nothing at all.  either it would crash or return 0 damage (pretty sure it'd just return 0 damage though.)

I guess if a plugin screwed with the damage flow, and you didn't pay attention to said plugin, then it might throw in an error as well.  Other than that, I can't see an error caused by a plugin being much more than the user not referencing the plugin properly in their damage formula.  

Barring all that though, my method still works the best.  Test the individual parts of the formula and get them working before moving on to the next part.  At each part, if there is an issue with calculating damage, look at the code and, if necessary given what you brought up about plugins, check your applicable plugins to see if you can find the error.  Sure, if you don't know a lot about javascript then looking at the code of the script might be a little intimidating, but just think logically about what you are trying to find and then do a quick scan for anything that would possibly fit your issue.  If you can't, then ask the author of the script, or the fine people here on this forum.

I'm not against a more detailed bug report for the damage formula.  If my damage formula told me what was causing the issue where it would save me a bit of leg work.  However, I don't particularly think its a hard job to debug.  

Now, RPG maker is meant for both newbie and advanced users, so for a quality of life / time saver, I can get behind a more detailed log.  It would make a tedious task a lot less tedious.
Here's the thing though.  For the plugin error to be caused by the damage formula, it would mean the damage formula would try to reference something in the plugin and that either returned an error or nothing at all.  either it would crash or return 0 damage (pretty sure it'd just return 0 damage though.)

I guess if a plugin screwed with the damage flow, and you didn't pay attention to said plugin, then it might throw in an error as well.  Other than that, I can't see an error caused by a plugin being much more than the user not referencing the plugin properly in their damage formula.  

Barring all that though, my method still works the best.  Test the individual parts of the formula and get them working before moving on to the next part.  At each part, if there is an issue with calculating damage, look at the code and, if necessary given what you brought up about plugins, check your applicable plugins to see if you can find the error.  Sure, if you don't know a lot about javascript then looking at the code of the script might be a little intimidating, but just think logically about what you are trying to find and then do a quick scan for anything that would possibly fit your issue.  If you can't, then ask the author of the script, or the fine people here on this forum.

I'm not against a more detailed bug report for the damage formula.  If my damage formula told me what was causing the issue where it would save me a bit of leg work.  However, I don't particularly think its a hard job to debug.  

Now, RPG maker is meant for both newbie and advanced users, so for a quality of life / time saver, I can get behind a more detailed log.  It would make a tedious task a lot less tedious.
While I agree on your practice, sometimes the reality isn't that nice 🙂

When the damage formula returns NaN and/or the grd of a target, which is guarding, is 0% when hit, the final hp/mp/tp of that target will be NaN.

Sometimes the situations are nice enough that the game will immediately crash in the same frame, letting the default RMMV error stacktrace to include Game_Action.prototype.evalDamageFormula and/or Game_Action.prototype.applyGuard.

But sometimes the game will crash in later frames, and it's entirely possible that the default RMMV error stacktrace to fail to log the root causes, as it only logs the stacktrace for the current frame:

Spoiler
SceneManager.update = function() { try { this.tickStart(); this.updateInputData(); this.updateMain(); this.tickEnd(); } catch (e) { this.catchException(e); }};
Code:
SceneManager.catchException = function(e) {    if (e instanceof Error) {        Graphics.printError(e.name, e.message);        console.error(e.stack);    } else {        Graphics.printError('UnknownError', e);    }    AudioManager.stopAll();    this.stop();};
Also, albeit much less likely, sometimes the stacktrace can be simply too long to be shown. I've encountered cases like this.

Of course, if at least some parts of the root causes are coming from some custom plugins, then their authors can at least meticulously check their codes to see if anything can be some of the causes, then fix them and check if anything changes.

Nevertheless, sometimes the errors actually have nothing to do with any custom plugin. For example:

Yanfly Core Engine - Error during Side View Battle(#8, #9, #11, #13, #14, #15)

Game always crashes in combat #23

While it's extremely ideal to be able to 100% ensure all damage formulae will always work, that's just unlikely the case on the RMMV community level in reality, given the number of RMMV users and the average number of different damage formulae per user. After all, no matter how exceptionally careful we're in general, we'll still occasionally make nontrivial mistakes without being aware of them before they bite us.

For many RMMV users, other than meticulously checking a damage formula right after touching it(and say, sometimes you might end up checking it 10+ times and still fail to realize the default RMMV battler has no matk and/or the default RMMV enemy has no level until you give your projects to others and the others point that out to you lol), they can only know some damage formulae have gone wrong when:

1. They return 0 where it shouldn't be possible(detecting this alone can be hard already)

2. They return NaN which propagates to be the hp/mp/tp value causing some errors seemingly completely unrelated to damage formulae to occur after an unknown number of frames causing the stacktrace to fail to log the cause, and they've given their projects to others and the others point that out to them

(Well, if I recall correctly, some guys have already made a topic stating that damage formulae should be closely inspecting upon facing the CanvasRenderingContext2D float parameter 3 is non-finite error, and this practice should somehow alleviate this situation)

What possibly makes things worse, is the below case:

http://fanblogs.jp/tabirpglab/category_34/

I'm extremely poor in reading Japanese, but it seems to me that using HP Recover in the damage formula alone(1st screenshot) can already cause the CanvasRenderingContext2D float parameter 3 is non-finite error, which shouldn't be even possible to begin with. If that's really the case, then it's almost certainly a bug in the default RMMV codebase.

On a side note: I'm still investigating on this although I haven't found anything meaningful nor useful yet 😀

In this case, my suggested modification to Game_Action.prototype.evalDamageFormula can either tell how the damage formula screwed up if it's the cause, or show the users that it isn't the cause if it indeed isn't.

Similar things can occur to having some battler's grd as 0%. I've encountered 1 user where he/she doesn't even know his/her project has 1 battler having 0 grd until he/she gave me the project and I explicitly pointed him/her out that battler.

On a side note: I've also found this: http://yanfly.moe/2015/11/07/plugin-updates-round-16/(Posted by Zeruchou in 2015-11-08 at 10:18 AM)

P.S.: As 1 of my custom plugins' still suffering from the CanvasRenderingContext2D float parameter 3 is non-finite error and I've run tons of tests to confirm that it's nothing to do with that plugin, I've given the below diagnose snippet to them. As I think there are still something unknown to me in the process of producing this error, I've also given the same snippet to some other users suffering from the same error:

Spoiler
Game_Action.prototype.makeDamageValue = function(target, critical) { // Rewrite var item = this.item(); console.log("subject", this.subject().name, "item", item.name, "target", target.name, "critical", critical); // Added var baseValue = this.evalDamageFormula(target); console.log("baseValue = this.evalDamageFormula(target)", baseValue); // Added var value = baseValue * this.calcElementRate(target); console.log("value = baseValue * this.calcElementRate(target)", value); // Added if (this.isPhysical()) { value *= target.pdr; console.log("value *= target.pdr", value); // Added } if (this.isMagical()) { value *= target.mdr; console.log("value *= target.mdr", value); // Added } if (baseValue < 0) { value *= target.rec; console.log("value *= target.rec", value); // Added } if (critical) { value = this.applyCritical(value); console.log("value = this.applyCritical(value)", value); // Added } value = this.applyVariance(value, item.damage.variance); console.log("value = this.applyVariance(value, item.damage.variance)", value); // Added value = this.applyGuard(value, target); console.log("value = this.applyGuard(value, target)", value); // Added value = Math.round(value); console.log("value = Math.round(value)", value); // Added return value;}; // Game_Action.prototype.makeDamageValueGame_Action.prototype.executeHpDamage = function(target, value) { // Rewrite if (this.isDrain()) { value = Math.min(target.hp, value); console.log("value = Math.min(target.hp, value)", value); // Added } this.makeSuccess(target); target.gainHp(-value); if (value > 0) { target.onDamage(value); } this.gainDrainedHp(value);}; // Game_Action.prototype.executeHpDamageGame_Action.prototype.executeMpDamage = function(target, value) { // Rewrite if (!this.isMpRecover()) { value = Math.min(target.mp, value); console.log("value = Math.min(target.mp, value)", value); // Added } if (value !== 0) { this.makeSuccess(target); } target.gainMp(-value); this.gainDrainedMp(value);}; // Game_Action.prototype.executeMpDamageGame_Action.prototype.itemEffectRecoverHp = function(target, effect) { // Rewrite var value = (target.mhp * effect.value1 + effect.value2) * target.rec; console.log("value = (target.mhp * effect.value1 + effect.value2) * target.rec", value); // Added if (this.isItem()) { value *= this.subject().pha; console.log("value *= this.subject().pha", value); // Added } value = Math.floor(value); console.log("value = Math.floor(value)", value); // Added if (value !== 0) { target.gainHp(value); this.makeSuccess(target); }}; // Game_Action.prototype.itemEffectRecoverHpGame_Action.prototype.itemEffectRecoverMp = function(target, effect) { // Rewrite var value = (target.mmp * effect.value1 + effect.value2) * target.rec; console.log("value = (target.mmp * effect.value1 + effect.value2) * target.rec", value); // Added if (this.isItem()) { value *= this.subject().pha; console.log("value *= this.subject().pha", value); // Added } value = Math.floor(value); console.log("value = Math.floor(value)", value); // Added if (value !== 0) { target.gainMp(value); this.makeSuccess(target); }}; // Game_Action.prototype.itemEffectRecoverHp
If my suggested version of Game_Action.prototype.evalDamageFormula and/or Game_Action.prototype.applyGuard is used instead, then I wouldn't have to give them the above snippet and wait for their logs, and they wouldn't have to use any such diagnose snippet to begin with, as it'd become crystal clear whether the damage formulae/0% grd can be the cause(if it isn't the case, then it's pretty sure that the default RMMV codebase indeed has bugs).

If the damage formula/0% grd is the cause, then my suggested version will immediately tell those users which damage formulae/battler caused the error, so they won't have to search(bear in mind there are projects having hundreds of different damage formulae/battlers having different grd).

If the damage formula/0% grd isn't the cause, then my suggested version will also immediately tell that, as no such error will be logged. Then the users can test which custom plugins caused the errors and inform their authors for that(they'll also immediately know that the damage formulae/0% grd isn't the cause so they don't have to waste their time there too), or report to the RMMV community about their cases with no custom plugin used and damage formulae/0% grd confirmed as innocent.

In short, I feel/think that both Game_Action.prototype.evalDamageFormula and Game_Action.prototype.applyGuard can be quite hard to debug, as they can drastically increase the cost to debug, which can scale quickly as the project scales, for both users and plugin developers.
Which is why I do agree, as a quality of life perk, that there should be a better system to debug the damage formula.  I don't personally need it as I test every little thing I change meticulously, but I'll admit that it would of made debugging my D&D damage formula a lot easier.  I'm just saying that people should make sure that they have a programmer's mentality when they go in and add plugins.  Test every new thing you add, and test it a lot.  See how it interacts with your old stuff, and if something does break, apply a little logic to fix it. 

Having an expanded debugging feature for the damage formula would make developer's lives easier, you've stated that well enough.   Looking over your example on the guard issue, there would of been a lot of time saved having those expanded features. Time saved is always a good thing.  I feel like we are both saying the same thing here, and perhaps in an update they can address and add in some expanded features to the damage evaluation.  

I'd like everyone to elevate the way they think when it comes to game design, especially the programming side of it, and have all the quality of life perks that make debugging not a tedious chore.  well, debugging will always be a tedious chore but we can make it less so with more expanded debugging features, especially on the damage evaluation.  Virtual high five

Original thread: https://forums.rpgmakerweb.com/threads/do-you-think-the-default-rmmv-damage-formula-evaluation-can-be-hard-to-debug.54312/