MZ Checking VisuStella Options Core Boolean

Hi folks,

I am trying to add an option to my game via VisuStella Options Core which will toggle some functionality in a separate plugin.

I have added an option via t Options Core that doesn't do anything on its own, it just gets set to true or false by toggling it in the options menu.

The idea is to wrap some of the code in a plugin inside of an if statement, which checks if the option is set to true or not.

The code I tried using in the other plugin is:

if(ConfigManager["chroma"]) {
<plugin code here>
}

("chroma" is the symbol for the option I added via Options Core).

As far as I can tell, the above should return "true" if the option with the symbol "chroma" has been toggled on? However, this does nothing.

Am I doing something wrong? Any help is much appreciated!

tl;dr: I need a script call to check if a particular option is on.
Hmmm, shouldn't the chroma at least be in quotation marks?
Yep!
  1. ConfigManager[chroma] = "get the ConfigManager property with name stored in a variable chroma".
  2. ConfigManager["chroma"] = "get the property of ConfigManager with name chroma".
  3. ConfigManager.chroma = identical to case 2.
You can't use case 3 if the property name has spaces etc.
Yep!
  1. ConfigManager[chroma] = "get the ConfigManager property with name stored in a variable chroma".
  2. ConfigManager["chroma"] = "get the property of ConfigManager with name chroma".
  3. ConfigManager.chroma = identical to case 2.
You can't use case 3 if the property name has spaces etc.

Thanks for the help! This worked for setting a variable to the config value for testing.

Unfortunately through, this still doesn't seem to work when used in the script of a plugin. I am wrapping part of a plugin script with:

Code:
if ConfigManager.chroma {
(do code)
}

But, this gives me the error "Unexpected Identifier" when I run the game (before the console even starts).
you forgot the parenthesis "if (ConfigManager.chroma) { /* code */ }"
you forgot the parenthesis "if (ConfigManager.chroma) { /* code */ }"

Thanks - this stopped the game from crashing when I tried to run it!

Yep!
  1. ConfigManager[chroma] = "get the ConfigManager property with name stored in a variable chroma".
  2. ConfigManager["chroma"] = "get the property of ConfigManager with name chroma".
  3. ConfigManager.chroma = identical to case 2.
You can't use case 3 if the property name has spaces etc.

Unfortunately, this isn't working when used in a plugin's code directly for some reason. If I run this in-game to get the value of ConfigManager.chroma, it returns "true", but if I use it in a plugin to wrap some code in a condition, that code just doesn't run no matter what.

Right now, this is the exact code I am using for this plugin:

Spoiler: CODE
Code:
if (ConfigManager.isLoaded) {
    if (ConfigManager["chroma"] == true) {

        const osc = Scene_Base.prototype.create;
        Scene_Base.prototype.create = function () {
            osc.call(this, arguments);
            this._chromaFilter = window._globalChromaFilter;
            if (this._chromaFilter) {
                if (!this.filters) this.filters = [];
                this.filters.push(this._chromaFilter);
            }
        }
        
        const osu = Scene_Base.prototype.update;
        Scene_Base.prototype.update = function () {
            osu.call(this, arguments);
            if (this._chromaFilter) {
                this._chromaFilter.uniforms.delta += pi60;
                this._chromaFilter.uniforms.view[0] = Graphics._width;
                this._chromaFilter.uniforms.view[1] = Graphics._height;
                if(this.constructor.name==`Scene_Map`) {
                    this._chromaFilter.uniforms.state = 1;
                this._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity*0.15;
            } else {
                    this._chromaFilter.uniforms.state = 0;
                this._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity;
            }
            }
        }
    }
}

I added the check for "ConfigManager.isLoaded" just to make sure it wasn't happening before the game loaded the configs or something, but that seems to be fine. If I wrap it just in that, it runs properly (configs are loaded). If I also wrap it in the ConfigManager.chroma condition, the same code stops loading, even though setting ConfigManager.chroma to a variable in game will confirm that it is true.

Running this in an event returns "true":
sdfsdfdfasf.JPG


And yet, the code in the plugin doesn't run when wrapped in the exact copy/pasted condition...
true to !== false or try === true (not ==) which is different.

both "!== false" (true) is the same as "=== true".

as I don't know the code or know what it should do,
you can try to test it with $gameSwitches.value(id).

if that works, than we can try something else.

also the parenthesis inside a conditional branch is not required.
true to !== false or try === true (not ==) which is different.

both "!== false" (true) is the same as "=== true".

as I don't know the code or know what it should do,
you can try to test it with $gameSwitches.value(id).

if that works, than we can try something else.

also the parenthesis inside a conditional branch is not required.

I've changed it to === true. Removing the parenthesis causes the game to crash (Unexpected Identifier).

This plugin runs from game launch (it applies a screen filter), so changing a switch to test will just crash the game as no save is loaded yet when it starts.

EDIT:
I tried running this code to test:
JavaScript:
console.log(`TEST1`);

if (ConfigManager.isLoaded) {
    console.log(`TEST2`);
}
    
if (ConfigManager["chroma"] === true) {
    console.log(`TEST3`);
}

TEST1 and TEST2 output to console, but TEST3 does not. When the map is loaded, my test event still confirms that ConfigManager["chroma"] is set to true.
don't use quoutes as that causes the indentifier issue.
forgot to say not use quotes.
Code:
if (ConfigManager.isLoaded) {
This checks "is the isLoaded property of ConfigManager truthy?". By default this will always be true, because a function is a truthy value.

To actually check if the config is loaded, you'd use this instead:
JavaScript:
if (ConfigManager.isLoaded()) {
The follow-up parentheses instruct the JS engine to evaluate the function and return its result. However, I don't think that will suffice in your case, since based on the code you shared it looks like you've basically wrapped the entire plugin in that statement. If so, the statement will be checked when the plugin loads...but the core scripts do not load the config until later.

Instead, you could add the condition to the plugin's methods (Scene_Base#create and #update). Or just remove the check entirely: if the config settings haven't been loaded yet then they should just hold default values, and by default the boot scene requires the config to be loaded before starting, so every scene after that should be OK in that respect.
This checks "is the isLoaded property of ConfigManager truthy?". By default this will always be true, because a function is a truthy value.

To actually check if the config is loaded, you'd use this instead:
JavaScript:
if (ConfigManager.isLoaded()) {
The follow-up parentheses instruct the JS engine to evaluate the function and return its result. However, I don't think that will suffice in your case, since based on the code you shared it looks like you've basically wrapped the entire plugin in that statement. If so, the statement will be checked when the plugin loads...but the core scripts do not load the config until later.

Instead, you could add the condition to the plugin's methods (Scene_Base#create and #update). Or just remove the check entirely: if the config settings haven't been loaded yet then they should just hold default values, and by default the boot scene requires the config to be loaded before starting, so every scene after that should be OK in that respect.

It does seem to be the case that the config manager is not actually loaded yet.

When I run:
JavaScript:
console.log(`TEST1`);

if (ConfigManager.isLoaded()) {
    console.log(`TEST2`);
}
    
if (ConfigManager["chroma"] === true) {
    console.log(`TEST3`);
}

It only prints TEST1 to the console log.

I am not wrapping the full plugin in the condition, just some code toward the end that actually applies the filter to the screen.

I'll post the full plugin here, since it is a free one:
Spoiler: Chroma Plugin
JavaScript:
/** /*:
 * @author TheUnpropro
 * @plugindesc A thing for a dude on the inter webs
 *
 * @target MZ
 *
 * @command Chrom
 * @text Chroma Level
 * @desc Sets the intensity of the chroma effect
 *
 * @arg value
 * @text Intensity
 * @type number
 * @decimals 2
 * @default 2
 * @desc Adjusts the intensity
 */
    (function () {
    const pi60 = Math.PI / 60;
    PluginManager.registerCommand('chroma_color', "Chrom", args => {
        args.value = parseFloat(args.value);
        window.__ChromaIntensConfig(args.value);
    });

    window.__ChromaIntensConfig = function (value) {
        try {
            const oldData = JSON.parse(localStorage.getItem('chroma_data'));
            oldData.intensity = value;
            oldData.view[0] = Graphics._width;
            oldData.view[1] = Graphics._height;
            window._globalChromaFilter.uniforms.view[0] = Graphics._width;
            window._globalChromaFilter.uniforms.view[1] = Graphics._height;
            window._globalChromaFilter.uniforms.intensity = value;

            SceneManager._scene._chromaFilter.uniforms.view = window._globalChromaFilter.uniforms.view;
            SceneManager._scene._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity;


            console.log(oldData);
            SceneManager._scene._writeChromaData(oldData);
        } catch (e) {
            throw e;
        }
    }

    async function FilterFragShader(frag, src) {
        try {
            let ret = await Promise.all(frag.match(/\/\*\@file:(.*?)\*\//gm).map(async (match) => {
                try {
                    const filename = match.replace('/*@file:', '').replace('*/', '').trim();
                    const fileContents = await fetch(`./data/filters/${src}/${filename}`).then(response => response.text());
                    return { match, replacement: fileContents };
                } catch (error) {
                    console.error(`Error loading file ${filename}:`, error);
                    return { match, replacement: "" }; // Return empty string if file loading fails
                }
            }));

            ret.forEach(({ match, replacement }) => {
                frag = frag.replace(match, replacement);
            });

        } catch (e) {
        }
        return frag;
    }
    async function checkCompile(src, vert, frag) {
        if (buildMode) {
            const path = require('path');
            const fs = require('fs');
            const corePath = `./data/filters/${src}/`;
            try {
                const flags = await fetch(`${corePath}/flags.json`).then(f => f.json());
                if (flags.compile.output_dir) {
                    try {
                        const mainPath = path.resolve(`${flags.compile.output_dir}/${src}`);
                        fs.mkdirSync(mainPath, { recursive: true });
                        if (flags.compile.vert) fs.writeFileSync(`${mainPath}/main.vert`, vert);
                        if (flags.compile.frag) fs.writeFileSync(`${mainPath}/main.frag`, frag);
                    } catch (e) {
                        throw e;
                    }
                }
            } catch (e) {
                console.log(`No flags.json file set`)
            }
        }
    }

    const buildMode = false;

    const __filterCache = {};
    async function loadFilter(src) {
        PIXI.settings.ROUND_PIXELS = true;
        return new Promise((resolve, reject) => {
            if (__filterCache[src]) resolve({ vert: __filterCache[src].vert, frag: __filterCache[src].frag })
            var frag = "";
            var vert = "";

            fetch(`/js/plugins/filters/${src}/main.vert`)
                .then(a => a.text())
                .then(_vert => {
                    vert = _vert;
                    return fetch(`/js/plugins/filters/${src}/main.frag`);
                })
                .then(a => a.text())
                .then(async _frag => {
                    frag = await FilterFragShader(_frag, src);

                    vert = `#version 300 es \nprecision highp float;\n${vert}`;
                    frag = `#version 300 es \nprecision highp float;\n${frag}`;


                    checkCompile(src, vert, frag);
                    resolve({ vert, frag });
                    __filterCache[src] = { vert, frag }
                })
                .catch(error => reject(error));
        });
    }

    const osb = Scene_Boot.prototype.initialize;

    Scene_Boot.prototype.initialize = function () {
        osb.call(this, arguments);

        (async () => {
            try {
                const data = await loadFilter('chroma');
                if (!data) {
                    throw new Error("Failed to load filter data");
                }
                const { vert, frag } = data;
                const _uniformData = this._getChromaData()

                const uniformBase =  {
                    delta: 0,
                    intensity: 2.25,
                    view: [Graphics._width, Graphics._height],
                    state: 1
                };
                const uniforms = _uniformData ?? uniformBase;
                for(let key in uniformBase) {
                    if(!uniforms[key]) uniforms[key] = uniformBase[key];
                }
                
                window._globalChromaFilter = new PIXI.Filter(vert, frag, uniforms);
                if (!_uniformData) this._writeChromaData(uniforms);
            } catch (error) {
                console.error("Error loading filter:", error);
            }
        })();
    };

    Scene_Base.prototype._getChromaData = function () {
        const data = localStorage.getItem('chroma_data');
        if (data) try {
            return JSON.parse(data);
        } catch (e) {
            return data;
        }
        return data;
    }

    Scene_Base.prototype._writeChromaData = function (data) {
        localStorage.setItem('chroma_data', JSON.stringify(data));
    }
    
    
//////WRAP IN CHROMA CONDITION

const osc = Scene_Base.prototype.create;
        Scene_Base.prototype.create = function () {
            osc.call(this, arguments);
            this._chromaFilter = window._globalChromaFilter;
            if (this._chromaFilter) {
                if (!this.filters) this.filters = [];
                this.filters.push(this._chromaFilter);
            }
        }
        
        const osu = Scene_Base.prototype.update;
        Scene_Base.prototype.update = function () {
            osu.call(this, arguments);
            if (this._chromaFilter) {
                this._chromaFilter.uniforms.delta += pi60;
                this._chromaFilter.uniforms.view[0] = Graphics._width;
                this._chromaFilter.uniforms.view[1] = Graphics._height;
                if(this.constructor.name==`Scene_Map`) {
                    this._chromaFilter.uniforms.state = 1;
                this._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity*0.15;
            } else {
                    this._chromaFilter.uniforms.state = 0;
                this._chromaFilter.uniforms.intensity = window._globalChromaFilter.uniforms.intensity;
            }
            }
        }
        
        
})();

Line 172 - end is the bit that I have been wrapping.

I am not too sure what you mean by adding Scene_Base#create and #update. I am no programmer (just poking around) so I am not too clear on where/how I would add that in. Even the exact part I am wrapping in a condition was just sort of a blind guess that worked to enable/disable the filter effect when removed or added back.

Would some kind of a wait loop also work? So maybe this part of the code could just wait until the config manager is loaded to apply the filter?
Would some kind of a wait loop also work?
It could be possible to apply those method patches later, once the boot scene starts, but that's not the goal here.

If you only check the setting once, on boot, then the plugin will only see that value for the entire session. With that setup, if you changed the setting mid-session, e.g. via the options menu, then you'd have to restart the game to see any difference.

So, you would need to add the check into any appropriate methods instead, e.g.
JavaScript:
        const osc = Scene_Base.prototype.create;     // store original method
        Scene_Base.prototype.create = function () {  // override
            osc.call(this, arguments);               // call original method
            if (!ConfigManager.chroma) return;       // stop here if setting is OFF
            this._chromaFilter = window._globalChromaFilter;
            if (this._chromaFilter) {
                if (!this.filters) this.filters = [];
                this.filters.push(this._chromaFilter);
            }
        }
That way it gets checked at runtime: if the setting is off, do not give this scene a chroma filter.

(I mentioned the update method as well earlier, but it looks like that shouldn't be necessary.)
It could be possible to apply those method patches later, once the boot scene starts, but that's not the goal here.

If you only check the setting once, on boot, then the plugin will only see that value for the entire session. With that setup, if you changed the setting mid-session, e.g. via the options menu, then you'd have to restart the game to see any difference.

So, you would need to add the check into any appropriate methods instead, e.g.
JavaScript:
        const osc = Scene_Base.prototype.create;     // store original method
        Scene_Base.prototype.create = function () {  // override
            osc.call(this, arguments);               // call original method
            if (!ConfigManager.chroma) return;       // stop here if setting is OFF
            this._chromaFilter = window._globalChromaFilter;
            if (this._chromaFilter) {
                if (!this.filters) this.filters = [];
                this.filters.push(this._chromaFilter);
            }
        }
That way it gets checked at runtime: if the setting is off, do not give this scene a chroma filter.

(I mentioned the update method as well earlier, but it looks like that shouldn't be necessary.)

Omg, this worked. Thank you so much for the help!

Learning a little more about all this JS stuff every day, haha. I had to google what a method even is.
Great, happy RPG Making~ 👋

Original thread: https://forums.rpgmakerweb.com/threads/checking-visustella-options-core-boolean.174678/