MV Error reading from list?

Hey guys, other achievement systems that were available didn't suit my needs so I started making my own. I've run into an issue with one of my Window's lists though.

Long short, I am reading from an external JSON, everything works correctly, and I can pull information using "Khali.achievements.x", x replaced with .name, .id, etc. The menu opens, I can switch between selections, but I have 3 different games in one package. They load and are populated fine, but I need to update the achievement title, description, and icon which is above the selection window.

Here is the code:
Code:
Window_Achievements_Info.prototype.makeAchievementList = function () {
    this._list = [];
    for (var i = 1; i < Khali.achievements.length; i++) {
        if (Khali.achievements[i].game === game) {
            this.addAchievement(Khali.achievements[i]);
        }
    }
    console.log(this._list);
};
What it does: Checks for the game title to see if it matches, adds it to a separate list as an object.

When it works: Drawing the list of all of the achievement icons (it's setup like the old Xbox 360 achievement menu)

Where it doesn't work:
Code:
this.drawText(this._list[currentSelection - 1].game, x + this.iconPadding, y, this.contents.width, 'left');

If I add console.log(this._list), it will populate the array and show the appropriate information.
If I add console.log(this._list[0].game) immediately under this line, it will crash with error "Cannot read property 'game' of undefined.

I can understand it's trying to read a property that isn't defined. I don't understand how this._list populates the array with
Code:
0:
  game: "Game 1"
Why is it both defined, and undefined at the same time? How is that possible?

[edit]
It does exclusively work correctly when called from drawItem though.
Code:
Window_Achievements_Info.prototype.drawItem = function (index) {
    var rect = this.itemRect(index);
    this.drawFace(this._list[index].icon, 2, rect.x + this.textPadding(), rect.y + this.textPadding(), iconSizeMini, iconSizeMini);
};

I can enter this.drawText(this._list[index].name here and it will populate, but as soon as I try to call that from refresh(), or anywhere else for that matter, it claims it's undefined.

[edit2]
Got it.
you try to load add list with "i" = 1 , so 0 is undefined, so if you make that 0, it should work.
or remove "-1" from current selection. either way should work.
you try to load add list with "i" = 1 , so 0 is undefined, so if you make that 0, it should work.
or remove "-1" from current selection. either way should work.
I did end up getting this to work. I skipped the 0 integer on purpose because I wanted it to count 1 and up.

I did run into another problem though and decided to sidebar it. I was going to make a new topic, but if this one still bumps then I'll ask here.

I tried using ImageManager to load from a custom folder:
Code:
ImageManager.loadAchievement = function (filename, hue) {
    return this.loadBitmap('img/achievements/', filename, hue, true);
};

Window_Base.prototype.drawAchievementIcon = function (_filename, iconIndex, x, y) {
    var bitmap = ImageManager.loadAchievement(_filename);
    var pw = iconSize;
    var ph = iconSize;
    var sx = iconIndex % 16 * pw;
    var sy = Math.floor(iconIndex / 16) * ph;
    this.contents.blt(bitmap, sx, sy, pw, ph, x, y);
};

Window_Base.prototype.drawAchievementMiniIcon = function (_filename, iconIndex, x, y) {
    var bitmap = ImageManager.loadAchievement(_filename);
    var pw = iconSizeMini;
    var ph = iconSizeMini;
    var sx = iconIndex % 16 * pw;
    var sy = Math.floor(iconIndex / 16) * ph;
    this.contents.blt(bitmap, sx, sy, pw, ph, x, y);
};
It does work, but not consistently at all. I did some googling and if I understand correctly there's an issue with preloading images in RPG Maker MV, I'm wondering if there's a simple solution to this? It does load the images, but it comes with a few bugs:
• Inconsistent. Sometimes it doesn't load any images at all, I close and open the menu and everything loads correctly.
• I'm using global variables to turn achievements on and off. When achievements are off, they are black and white for now (using a separate grayscale image of the achievement icons) and when they are on they use a colored image. This is the function for that:
Code:
Window_Achievements_Info.prototype.drawItem = function (index) {
    var rect = this.itemRect(index);
    if ($gameVariables.value(201)[this.id] === 1) {
        this.drawAchievementMiniIcon('achievementsMini', this._list[index].icon, rect.x + this.textPadding(), rect.y + this.textPadding());
    }
    else {
        this.drawAchievementMiniIcon('achievementsMini-Locked', this._list[index].icon, rect.x + this.textPadding(), rect.y + this.textPadding());
    }
};

It draws the list, but my expectation was that it would check this variable for each one and choose the correct image accordingly. What it does is, if an achievement is unlocked and I highlight the unlocked one, it changes all of them to the colored ones, then if I highlight a locked one, it changes them all to the locked image. Game Variable 201 is an array, so I'm expecting it to check variable 201[1] for example, and if that is set to 1, draw the colored one, and check each individually. It just checks for the first one and stops there. I haven't actually found the DrawAllItems function yet though, I just assumed it was handled like a for loop. I haven't gone back to it yet, but perhaps I should just use a for loop instead.

[edit]
Ah, this is what it already does:
Code:
Window_Selectable.prototype.drawAllItems = function() {
    var topIndex = this.topIndex();
    for (var i = 0; i < this.maxPageItems(); i++) {
        var index = topIndex + i;
        if (index < this.maxItems()) {
            this.drawItem(index);
        }
    }
};

I feel like this should have worked. 🤣
you may need to loop that like:
JavaScript:
let icons = $gameVariables.value(201); // array

for (let i = 0; i < icons.length; i++) {
       let icon = icons[i];
       //other code for icons[i] (this.id)
}

but to make your code, you also can do something like this:
JavaScript:
Window_Achievements_Info.prototype.drawItem = function (index) {
    let rect = this.itemRect(index);
    let icon = $gameVariables.value(201)[this.id]
    this.drawAchievementMiniIcon((icon === 1 ? 'achievementsMini':'achievementsMini-Locked') , this._list[index].icon, rect.x + this.textPadding(), rect.y + this.textPadding());
};

just make sure that "this.id" is grabbed correctly so you have to loop over it first or safe-guard it.

there are some methods, but it depends on how your entire code it build and look like in game.

the drawAchiementIcon can also be one if you check for locked or unlocked so you have 2 in 1,
if your comfortable separately for control is that fine too, its just some tips. ^^
I think the solution is to use your function like this:

JavaScript:
var bitmap = ImageManager.loadAchievement(...);
bitmap.addLoadListener(() => this.refresh());

Or something along those lines – basically, make it force a refresh of your window once the image has finished loading.

The other alternative might be to use the ImageManager.reserveBitmap function. I don't know exactly how that's meant to be used though. I think you'd call it in your scene setup function for every image you need to load, but I'm not sure if you need to do some cleanup when the scene ends or what you should choose as a reservation ID.
you may need to loop that like:
JavaScript:
let icons = $gameVariables.value(201); // array

for (let i = 0; i < icons.length; i++) {
       let icon = icons[i];
       //other code for icons[i] (this.id)
}
I did figure this out, I'm not sure where I went wrong here, but using this.id was drawing the last value. I added a drawtext component to test this and discovered it would always draw the final value no matter what I changed it to. I reomved this.id and changed it to index, and now it displays the icons correctly.

I still can not for the life of me figure out how to preload the bitmaps though.I attempted Solar_Flare's suggestion and it just caused a crash stating it can't find the id of the image. Going to research reserve.

[edit]
I don't know, maybe I need to start over. This thing is just starting to annoy the hell out of me. If I were writing this in C# or C++, or even PHP, or whatever, it would work fine. I'm having the hardest time wrapping my head around why JS in this engine is so strict.

I can draw my info window from initialize and it works maybe 50% of the time. Sometimes it will draw all the information, sometimes it doesn't. Why? I don't know.

If I call this.refresh() from initialize, it crashes because of some definition that isn't defined, but it works just fine otherwise. If I try to define it where I think the issue is, nah. Still just crashes. I can not grasp how sometimes JS will agree that something exists, then just suddenly decide "You know what? In this instance, it doesn't."
I attempted Solar_Flare's suggestion
What was your exact code, and the exact error in the dev console?
What was your exact code, and the exact error in the dev console?
Exactly what you wrote, but it isn't the bitmap refresh causing the crash. It's calling refresh() that's crashing.

I'm pulling information from a json:
Code:
var Khali = Khali || {};
Khali.achievements = {};
Khali.achievements.version = "1.0";

Code:
Khali.loadDataFile = async (fileName, prop) => {
    const response = await fetch(`data/${fileName}.json`);
    const data = await response.json();
    Khali[prop] = data;
    console.log(Khali[prop]);
    console.log(Khali.achievements[1].name);
}
Khali.loadDataFile('Achievements', 'achievements');

I have this function to create the list:
Code:
Window_Achievements_Info.prototype.makeAchievementList = function () {
    this._list = [];
    for (var i = 1; i < Khali.achievements.length; i++) {
        if (Khali.achievements[i].game === game) {
            this.addAchievement(Khali.achievements[i]);
        }
    }
};

Then anytime I call information from this I just run this._list.value, whether that be .id, .name, .icon, etc. I call this.makeAchievementList() when the window is initialized, and it works as long as I open the window. If I call this.refresh(), or this._infoWindow.refresh() in initialize however, it's like it doesn't ever exist and crashes. Refresh is called anytime the cursor moves though, and works fine. It doesn't make any sense to me.

[edit]
Better yet, where the load listener expected to go?
I never use file listener, you can just preload with using Galv_ImageChange or load it on boot.
I have a preload function in my base, so you can see how I done that, so you can do the same.

on Scene_Boot works better than listener if you ask me.
also, instead of using JSON which I did on ULS (UniversalLevelSystem that draws backgrounds,
so it may work on your achievement way.

another way to avoid json is using a struct based, add the icon there, use the description,
and other things.

I use a automatic parser to make struct recursive, this way, you can control it easier.
so you can try through that, or create an achievement object inside the plugin.

MOG_FastTravelSystem (for MV) or MrTS backgrounds I believe or Nodes has the same thing.
even MUSH_Achievement has a similar build of XBOX version that also require to alter plugin
for achievement, but it doesn't update nicely, so you can see how they done it.
I never use file listener, you can just preload with using Galv_ImageChange or load it on boot.
I was hoping this would be my solution, but no success. It still has the same effect. Just broken. It will always fail to load the first time, and load the second time the scene opens. After awhile it seems like it just stops loading the JSON file too. I wanted to use the JSON to have all my stuff programmed in a nice clean easy list. It all works, it just works sometimes. This engine is the worst.

What I don't understand is, the files I'm trying to load are so extremely light weight. Can I just load them into memory permanently and never remove them or something?
Exactly what you wrote, but it isn't the bitmap refresh causing the crash. It's calling refresh() that's crashing.
That's not really enough information for me to guess what's going on. The code I wrote isn't even valid code (you have to substitute the ... with the correct parameters, which it sounds like you did).

My code was written under the assumption that you are in a function on some Window_XXX class. So, the full code would be something like this (but the below code uses non-existent names as an example, so it's not copy-pastable):
JavaScript:
Window_Achievement.prototype.something = function() {
    var bitmap = ImageManager.loadAchievement(...);
    bitmap.addLoadListener(() => this.refresh());
    // do other stuff with bitmap, like drawing it or whatever
};

If you pasted it into a different function, it's not guaranteed to work as-is. If you pasted it into a Scene_XXX.prototype.xyz function, replacing this.refresh() with this._someWindow.refresh() probably gets the same effect.

What I don't understand is, the files I'm trying to load are so extremely light weight. Can I just load them into memory permanently and never remove them or something?
I think there might be something for that…? Maybe check how the window skin is loaded and kept in memory? I bet it uses the reserve system.
I tried it in the info window initialization but it returns "cannot read property of 'id'" first, but this is because of issues I'm having with it reading from the JSON file.

If I move it to other locations it's a maximum call stack size exceeded error.

So I have a new question, because a lot of problems I seem to be having are stemming from reading from the JSON file in a timely manner, can I not create a global variable for this list? IE:
Code:
let achievementList = [];

But in JS, how do I create a function to read from the JSON immediately, and store this for anytime I need to refer to it? Without using a Window_X.prototype function?

[edit]
I did get the image preloader to work for the game list, I'm just struggling to get it to work for my achievement list now because of the timing it draws the list. I'm kind of rewriting a lot of it. I understand the timing in other programming languages, but I'm not understanding why JS will read one function before or simultaneously with another.

Is there a way to use addLoadListener with more than 1 image?

[edit2]
I got it! Everything works as intended now.
But in JS, how do I create a function to read from the JSON immediately, and store this for anytime I need to refer to it? Without using a Window_X.prototype function?
You can load a JSON file into a global variable like this:
JavaScript:
DataManager.loadDataFile('$dataAchievements', 'data/Achievements.json');
Normally you'd probably do this by aliasing loadDatabase:
JavaScript:
(function(old) {
    DataManager.loadDatabase = function() {
        old.call(this);
        this.loadDataFile('$dataAchievements', 'data/Achievements.json');
    };
})(DataManager.loadDatabase);

That'll load your achievements file into a global variable called $dataAchievements.
That'll load your achievements file into a global variable called $dataAchievements.
Sorry, I actually already was doing this right from the start. That did work, it was the nature of having to create separate lists for separate titles that had mixed me up. It all works now, I just discovered that reading from a global variable...will work...but might not be the most ideal thing.

I haven't looked into it yet, but is it possible for me to read and write variables to a save file? I really just need a list of bools for each achievement, but I'm wondering if it's possible to do this using the save interpreter in some way. I realize I could write to a JSON as well, but I feel like that will require me to read and overwrite constantly. I'm not sure that would be the best way to go about it?
The quickest way to add something to the save file is to put it in the $gameSystem variable. You could also override DataManager.makeSaveContents and DataManager.extractSaveContents.

Original thread: https://forums.rpgmakerweb.com/threads/error-reading-from-list.181064/