PlotsData.ts 2.85 KB
import { Chapter, Plot, ReadonlyPlot, SpecialPlotId } from "../model/PlotModel";
import { GameConfig } from "../../GameConfig";
import { delay } from "simba-utils";
import { ResUtils } from "../../common/utils/ResUtils";

let plotsIndex: { firstPlot: number, entries: { [key: number]: number } } = {
    firstPlot: -1,
    entries: {}
};

let chaptersData: { [key: number]: Chapter } = {};

const curPlotsData: { [key: number]: { [key: number]: ReadonlyPlot } } = {};

// Managed by PlotManager, do not call directly
export function initCustomPlots(plots: { [key: number]: ReadonlyPlot }) {
    if (curPlotsData[-100]) {
        console.error("initCustomPlots already called!");
        return;
    }
    curPlotsData[-100] = plots;
}

// Managed by PlotManager, do not call directly
export function addCustomPlotData(plot: ReadonlyPlot) {
    curPlotsData[-100][plot.id] = plot;
}

export function getPlotsIndex() {
    return plotsIndex;
}

const USE_CDN_PLOTS = false;


export async function getPlot(plotId: number) {
    if (plotId === undefined) return undefined;
    if (plotId <= SpecialPlotId.CustomPlotStart) {
        return curPlotsData[-100][plotId];
    }
    if (plotId < 0) {
        return { id: plotId } as Plot;
    }
    let chapterId = plotsIndex.entries[plotId];
    if (!curPlotsData[chapterId]) {
        curPlotsData[plotsIndex.entries[plotId]] = await retrievePlotsForChapter(chapterId);
    }
    return curPlotsData[chapterId][plotId];
}

async function retrievePlotsForChapter(chapterId: number) {
    while (1) {
        try {
            let res: any;
            if (USE_CDN_PLOTS) {
                let resStr = await GameConfig.cdnServer.get(`/plots/${chapterId}.json`, 5000, { "Cache-Control": "no-cache, no-store" }) as string;
                res = JSON.parse(resStr);
            } else {
                res = await ResUtils.loadRes<any>(`/plots/${chapterId}`, cc.JsonAsset);
            }
            return res;
        } catch (e) {
            console.error(e);
        }
    }
}

export function getChapter(chapterId: number) {
    return chaptersData[chapterId];
}

export async function initPlotsData() {
    while (true) {
        try {
            let res: any;
            if (USE_CDN_PLOTS) {
                let resStr = await GameConfig.cdnServer.get("/plots/index.json", 5000, { "Cache-Control": "no-cache, no-store" }) as string;
                res = JSON.parse(resStr);
            } else {
                res = await ResUtils.loadRes<any>("plots/index", cc.JsonAsset);
            }
            plotsIndex = res.plots;
            chaptersData = res.chapters;
            break;
        } catch (e) {
            console.error(e);
            await delay(1);
        }
    }
}

export function getChapters(): { [key: number]: Chapter } {
    return chaptersData;
}

export function getChapterPlots(chapterId: number) {
    return curPlotsData[chapterId];
}