Skip to content
Store Dev
Last Updated

Advanced Integration

5. Stats · Achievements · Leaderboards

Stats, achievements, and leaderboards are features shown on the STOVE Store page. This chapter follows the Brick Smash code that saves a stat at game over and reads server values on the achievement, ranking, and stat screens, and explains how to use the five functions.

Initialization, termination, and the ownership check are covered in Chapter 2. Call every function in this chapter after Stove_Initialize() succeeds.

Concepts

  • Stat: A single value accumulated during play (e.g., the number of bricks broken), saved to and read from the STOVE server.
  • Achievement: An item whose completion depends on whether a stat value meets a target condition.
  • Leaderboard: A list that ranks users by a stat. It is fetched page by page.

Achievements and leaderboards are not updated in code. The game only updates stats with Stove_SetStat(), and the server evaluates achievements and rankings based on the settings registered in STOVE Studio. Therefore, Brick Smash calls only Stove_SetStat() at game over, and only fetches achievements and leaderboards when their screens are opened.

Register in STOVE Studio First

Register stats, achievements, and leaderboards in STOVE Studio first. Calls with unregistered IDs cannot return valid values. Brick Smash registers the following.

ItemRegistration Details
StatID MAX_BROKEN_BLOCKS, value operation MAX.
AchievementTwo achievements linked to the stat above: "First Brick Broken" (condition GTE 1) and "10 Bricks Broken" (condition GTE 10).
LeaderboardBased on the stat above.

The stat ID is kept in stat_id and the leaderboard ID in leaderboard_id of the configuration file, and the code reads them from there. A stat ID may contain only uppercase letters, digits, underscores, and hyphens ([A-Z0-9_-]).

ini
[gamesupport]
; Stat ID format: [A-Z0-9_-]
stat_id = MAX_BROKEN_BLOCKS
; Leaderboard identifier created in STOVE Studio
leaderboard_id = YOUR_LEADERBOARD_ID

This example is part of config/stove_config.example.ini.

Five Functions

All five functions are asynchronous. Results arrive as callbacks on the thread that calls Stove_RunCallback(). Create parameter objects with Stove_CreateParam() and call Destroy() after the call.

FunctionParameter Type ValueCallback TypeCallback Result
Stove_FetchStatk_EStoveGameSupportTypeKind_FetchStatParamOnGetStatCallbackIStoveStat
Stove_SetStatk_EStoveGameSupportTypeKind_SetStatParamOnSetStatCallbackIStoveSetStatOutcome
Stove_FetchAchievementk_EStoveGameSupportTypeKind_FetchAchievementParamOnGetAchievementCallbackIStoveAchievement
Stove_FetchAchievementsk_EStoveGameSupportTypeKind_FetchAchievementsParamOnGetAchievementsCallbackIStoveAchievementList
Stove_FetchRankingk_EStoveGameSupportTypeKind_FetchRankingParamOnGetRankingCallbackIStoveRanking

Structure of the Sample Game

Brick Smash keeps its SDK calls in one place, src/stove/StoveGameSupport.cpp. The header src/stove/StoveGameSupport.h exposes only four functions.

cpp
namespace StoveGameSupport
{
    void SetStat(const std::wstring& statId, int value, SetStatState* out);
    void FetchStat(const std::wstring& statId, StatState* out);
    void FetchAchievements(AchievementsState* out);
    void FetchRanking(const std::wstring& leaderboardId, RankingState* out);
}

Each function takes a pointer to the state struct that receives the result (out). This pointer is passed to the SDK as userData, and the callback gets it back with callbackResult->GetUserData() and fills in the values. Objects received by the callback become invalid when it ends, so values needed by the screen are copied inside the callback. The state structs are in src/StoveState.h, and status moves from Idle → Loading → Done or Error.

cpp
enum class AsyncStatus
{
    Idle,
    Loading,
    Done,
    Error,
};

The screen starts a call only once while status is Idle. Callbacks run inside Stove_RunCallback(), on the same thread as the screen code, so changing the state without locks is safe.

Parameters are created with StoveMakeParam<T>() from base_guard.h. The returned StoveGuard calls Destroy() when it goes out of scope.

Call Order

  1. When a value is final, such as at game over, send the stat value with Stove_SetStat().
  2. Check whether the value actually changed with IsUpdated() in the callback.
  3. When the stat screen opens, fetch the current value with Stove_FetchStat().
  4. When the achievement screen opens, fetch the list with Stove_FetchAchievements(). If only one is needed, use Stove_FetchAchievement().
  5. When the ranking screen opens, fetch the desired page with Stove_FetchRanking().

Saving a Stat (Stove_SetStat)

cpp
void Stove_SetStat(const IStoveSetStatParam* param, OnSetStatCallback onFinished, void* userData);
typedef void(__cdecl* OnSetStatCallback)(const IStoveCallbackResult* callbackResult, const IStoveSetStatOutcome* statOutcome);
SetterFormatDescription
SetStatsIdconst wchar_t*ID of the stat to change.
SetStatValueint32_tNew value to apply to the stat. The stat is set to this value; it is not added to the existing value.
Method (IStoveSetStatOutcome)Return TypeDescription
IsUpdated()booltrue if the stat value was actually updated.
GetCurrentValue()int32_tCurrent value after the update.
GetErrorMessage()const wchar_t*Message describing a problem during the update, if any.

The following is SetStat() in src/stove/StoveGameSupport.cpp.

cpp
void StoveGameSupport::SetStat(const std::wstring& statId, int value, SetStatState* out)
{
    auto param = StoveMakeParam<IStoveSetStatParam>();
    if (!param.IsValid())
        return;
    param->SetStatsId(statId.c_str()); // [A-Z0-9_-] format
    param->SetStatValue(value);        // It is changed to the specified value (it is not added to it).

    out->status = AsyncStatus::Loading;
    Stove_SetStat(param.Get(), OnSetStatFinished, out);
}

The callback is OnSetStatFinished() in the same file.

cpp
void __cdecl OnSetStatFinished(const IStoveCallbackResult* r, const IStoveSetStatOutcome* outcome)
{
    auto* st = Self<SetStatState>(r);
    if (!r->GetResult()->IsSuccessful())
    {
        st->status = AsyncStatus::Error;
        st->error = DescribeFailure(r);
        return;
    }
    // Even if the call is successful, the value may not change (e.g., a smaller value for the MAX stat). This is not an error.
    st->updated = outcome->IsUpdated();
    st->currentValue = outcome->GetCurrentValue();
    st->status = AsyncStatus::Done;
}

Self<T>() is a helper near the top of the same file that casts r->GetUserData() to T*.

At game over, src/ui/GameScreen.cpp calls this function. The call sits next to the code that switches the screen state to game over (AppScreen::GameOver), so it runs only once, at the moment of game over.

cpp
// If you just died, the game switches to "Game Over" + stats are recorded (once only)
if (game.IsGameOver())
{
    *ctx.current = AppScreen::GameOver;
    StoveGameSupport::SetStat(ctx.cfg->stat_id, game.score(), &ctx.state->setStat);
}

The stat uses the MAX value operation, so the value changes only when the number of bricks broken in this round is greater than the previous best. This one call makes the server evaluate achievements and update the leaderboard as well.

Decide whether the value actually changed with IsUpdated(), not the result code. Sending a smaller value to a MAX stat succeeds, but IsUpdated() is false. This is not an error.

Fetching a Stat (Stove_FetchStat)

cpp
void Stove_FetchStat(const IStoveFetchStatParam* param, OnGetStatCallback onFinished, void* userData);
typedef void(__cdecl* OnGetStatCallback)(const IStoveCallbackResult* callbackResult, const IStoveStat* stat);
SetterFormatDescription
SetStatsIdconst wchar_t*ID of the stat to fetch. Contains only uppercase letters, digits, underscores, and hyphens.
Method (IStoveStat)Return TypeDescription
GetStatsFullId()const IStoveStatFullId*Full identification of the stat. Has GetGameId() and GetStatsId().
GetCurrentValue()int32_tCurrent value of the stat.
GetUpdatedAt()uint64_tTime of the last update, in Unix epoch milliseconds.

FetchStat() and its callback:

cpp
void StoveGameSupport::FetchStat(const std::wstring& statId, StatState* out)
{
    auto param = StoveMakeParam<IStoveFetchStatParam>();
    if (!param.IsValid())
        return;
    param->SetStatsId(statId.c_str());

    out->status = AsyncStatus::Loading;
    Stove_FetchStat(param.Get(), OnFetchStatFinished, out);
}
cpp
void __cdecl OnFetchStatFinished(const IStoveCallbackResult* r, const IStoveStat* stat)
{
    auto* st = Self<StatState>(r);
    if (!r->GetResult()->IsSuccessful())
    {
        st->status = AsyncStatus::Error;
        st->error = DescribeFailure(r);
        return;
    }
    st->currentValue = stat->GetCurrentValue();
    st->status = AsyncStatus::Done;
}

The stat screen in src/ui/ServiceScreens.cpp starts the query while status is Idle and draws the value once it is Done. The refresh button sets status back to Idle so that the next frame queries again.

cpp
void DrawStatsScreen(ScreenContext& ctx)
{
    StatState& st = ctx.state->stat;

    if (st.status == AsyncStatus::Idle)
        StoveGameSupport::FetchStat(ctx.cfg->stat_id, &st);

    bool back = DrawHeader("Stats");

    DrawLoadingOrError(st.status, st.error);
    if (st.status == AsyncStatus::Done)
    {
        ImGui::SetWindowFontScale(1.4f);
        ImGui::Text("Max blocks destroyed: %d", st.currentValue);
        ImGui::SetWindowFontScale(1.0f);

        if (ImGui::Button("Refresh"))
            st.status = AsyncStatus::Idle;
    }
    // (Back button handling omitted)
}

Fetching the Achievement List (Stove_FetchAchievements)

cpp
void Stove_FetchAchievements(const IStoveFetchAchievementsParam* param, OnGetAchievementsCallback onFinished, void* userData);
typedef void(__cdecl* OnGetAchievementsCallback)(const IStoveCallbackResult* callbackResult, const IStoveAchievementList* list);
SetterFormatDescription
SetPageSizeuint32_tNumber of achievements per page, 1 to 100. If not set or out of range, the whole list is returned at once.
SetAchievementIdconst wchar_t*Used only when fetching page by page. Leave it empty for the first page; for later pages, set the ID of the last achievement in the previously received list.
Method (IStoveAchievementList)Return TypeDescription
GetCount()uint32_tNumber of achievements received this time.
GetAt(uint32_t index)const IStoveAchievement*The achievement at index. nullptr if out of range.
GetTotalCount()uint32_tTotal number of achievements. Same as GetCount() when not fetched page by page.

Achievement information (IStoveAchievement) has the following values. The single-achievement function returns the same type.

MethodReturn TypeDescription
GetAchievementId()const wchar_t*Achievement ID.
GetName()const wchar_t*Localized achievement name.
GetDescription()const wchar_t*Localized achievement description.
GetDefaultImage()const wchar_t*URL of the image shown before completion.
GetAchievedImage()const wchar_t*URL of the image shown after completion.
GetValue()int32_tCurrent progress value of the achievement.
GetStatus()const wchar_t*Status. ONGOING (in progress) or ACHIEVED (completed).
GetCondition()const IStoveAchievementCondition*Completion condition. See the table below.
Method (IStoveAchievementCondition)Return TypeDescription
GetGoalValue()int32_tTarget value.
GetType()const wchar_t*How the target value is compared with the user's value. GTE (greater than or equal) or LTE (less than or equal).
GetValueOperation()const wchar_t*Value operation. One of DELTA_SUM (cumulative sum), REPLACE (replace), MAX (replace with the larger value), and MIN (replace with the smaller value).

Status and condition values arrive as strings, not enumerations. Compare them with wcscmp.

FetchAchievements() sets no values on the parameter, so it receives the whole list at once.

cpp
void StoveGameSupport::FetchAchievements(AchievementsState* out)
{
    // If you do not specify a page size, you will receive the entire list at once.
    auto param = StoveMakeParam<IStoveFetchAchievementsParam>();
    if (!param.IsValid())
        return;

    out->status = AsyncStatus::Loading;
    Stove_FetchAchievements(param.Get(), OnFetchAchievementsFinished, out);
}

The callback iterates over the list and copies the values needed by the screen as UTF-8 strings and integers. Completion is decided by comparing GetStatus() with wcscmp.

cpp
void __cdecl OnFetchAchievementsFinished(const IStoveCallbackResult* r, const IStoveAchievementList* list)
{
    auto* st = Self<AchievementsState>(r);
    if (!r->GetResult()->IsSuccessful())
    {
        st->status = AsyncStatus::Error;
        st->error = DescribeFailure(r);
        return;
    }
    st->items.clear();
    for (uint32_t i = 0; i < list->GetCount(); ++i)
    {
        const IStoveAchievement* a = list->GetAt(i);
        if (a == nullptr)
            continue;
        AchievementsState::Item item;
        item.name = WideToUtf8(a->GetName());
        item.description = WideToUtf8(a->GetDescription());
        item.achieved = (wcscmp(a->GetStatus(), L"ACHIEVED") == 0); // The status is returned as a string.
        item.value = a->GetValue();
        item.goal = a->GetCondition() ? a->GetCondition()->GetGoalValue() : 0;
        st->items.push_back(item);
    }
    st->status = AsyncStatus::Done;
}

DrawAchievementsScreen() in src/ui/ServiceScreens.cpp draws this list as "Achieved" or "In progress" with the progress value (value / goal). A refresh button sits at the bottom of the screen.

cpp
if (ImGui::Button("Refresh"))
    st.status = AsyncStatus::Idle;

If the achievement screen is opened right after game over, a newly completed achievement may not appear yet. Achievements are evaluated on the server and may not be reflected immediately, so a refresh button lets the user query again.

Fetching Page by Page

With many achievements, they can be fetched page by page. Brick Smash has only two achievements, so it does not use paging.

  1. For the first call, set only the page size, such as SetPageSize(20), and leave AchievementId empty.
  2. Copy GetAchievementId() of the last item in the list received by the callback into a game variable.
  3. For the next page, call again with the same page size and the ID from step 2.
  4. Stop when the number received so far reaches GetTotalCount().

Fetching One Achievement (Stove_FetchAchievement)

cpp
void Stove_FetchAchievement(const IStoveFetchAchievementParam* param, OnGetAchievementCallback onFinished, void* userData);
typedef void(__cdecl* OnGetAchievementCallback)(const IStoveCallbackResult* callbackResult, const IStoveAchievement* achievement);
SetterFormatDescription
SetAchievementIdconst wchar_t*ID of the achievement to fetch.

The IStoveAchievement delivered to the callback is the same as in the achievement list table above. The sample uses the list query. Use this function when only one achievement is needed, such as a screen that shows the progress of a single achievement.

Fetching Rankings (Stove_FetchRanking)

cpp
void Stove_FetchRanking(const IStoveFetchRankingParam* rankParams, OnGetRankingCallback onFinished, void* userData);
typedef void(__cdecl* OnGetRankingCallback)(const IStoveCallbackResult* callbackResult, const IStoveRanking* ranking);
SetterFormatDescription
SetLeaderboardIdconst wchar_t*Leaderboard ID created in STOVE Studio.
SetPageIndexuint32_tPage number to fetch, starting at 1.
SetPageSizeuint32_tNumber of ranks per page, 1 to 50.
SetIncludeMyRankboolIf true, the first item of the result is always the signed-in user's own rank.
Method (IStoveRanking)Return TypeDescription
GetCount()uint32_tNumber of rank items on this page.
GetAt(uint32_t index)const IStoveRank*The rank item at index. nullptr if out of range.
GetTotalCount()uint32_tNumber of rank items across all pages.
Method (IStoveRank)Return TypeDescription
GetNickname()const wchar_t*User nickname.
GetProfileImage()const wchar_t*URL of the user's profile image.
GetScore()int32_tLeaderboard score.
GetRank()uint32_tCurrent rank.
cpp
void StoveGameSupport::FetchRanking(const std::wstring& leaderboardId, RankingState* out)
{
    auto param = StoveMakeParam<IStoveFetchRankingParam>();
    if (!param.IsValid())
        return;
    param->SetLeaderboardId(leaderboardId.c_str());
    param->SetPageIndex(1);        // Start at 1
    param->SetPageSize(20);        // 1 ~ 50
    param->SetIncludeMyRank(true); // The first item is always your own ranking

    out->status = AsyncStatus::Loading;
    Stove_FetchRanking(param.Get(), OnFetchRankingFinished, out);
}
cpp
void __cdecl OnFetchRankingFinished(const IStoveCallbackResult* r, const IStoveRanking* ranking)
{
    auto* st = Self<RankingState>(r);
    if (!r->GetResult()->IsSuccessful())
    {
        st->status = AsyncStatus::Error;
        st->error = DescribeFailure(r);
        return;
    }
    st->rows.clear();
    st->total = ranking->GetTotalCount();
    for (uint32_t i = 0; i < ranking->GetCount(); ++i)
    {
        const IStoveRank* rank = ranking->GetAt(i);
        if (rank == nullptr)
            continue;
        st->rows.push_back({ rank->GetRank(), WideToUtf8(rank->GetNickname()), rank->GetScore() });
    }
    st->status = AsyncStatus::Done;
}

DrawRankingScreen() in src/ui/ServiceScreens.cpp draws this list as a table of rank, nickname, and score, and shows the total count (st.total) at the top. Like the achievement screen, it queries only once while Idle and queries again with the refresh button.

cpp
if (st.status == AsyncStatus::Idle)
    StoveGameSupport::FetchRanking(ctx.cfg->leaderboard_id, &st);

Points to Note

Stat, achievement, and leaderboard IDs must exactly match the values registered in STOVE Studio. Stat IDs use the [A-Z0-9_-] format.

Decide whether the stat value changed with IsUpdated(). IsUpdated() being false is not an error.

The achievement status (GetStatus()) and conditions (GetType() · GetValueOperation()) are strings, not enumerations. Compare them using wcscmp.

With SetIncludeMyRank(true), the first item in the result is the signed-in user's own rank. Brick Smash does not treat the first item differently and draws it in the same table as the other ranks. To highlight the user's own rank, handle the item at i == 0 separately. The page size range is 1 to 50 for ranking queries and 1 to 100 for achievement list queries.

Achievements are evaluated by the server and may not be reflected immediately. Put a refresh button on the achievement screen so users can query again.

Objects received in callbacks (IStoveStat · IStoveAchievementList · IStoveRanking, etc.) become invalid when the callback ends. Do not keep the pointers; copy the needed values inside the callback.

6. Payment

Opens an in-game shop and sells products. This chapter follows the shop and inventory screens of Brick Smash to explain product queries, purchase, and inventory queries. Games without a shop can skip this chapter.

Initialization and termination are covered in Chapter 2. Call every function in this chapter after Stove_Initialize() succeeds.

Preparation

  1. Register the in-game shop in STOVE Studio to get the shop key.
  2. Register the categories and the products to sell in STOVE Studio. Until registration is complete, the query functions return an empty list. Brick Smash registers one test product for checking the shop screen.
  3. Set both SetShopKey and SetMainWndHandle on the initialization parameter. For the full initialization sequence, see Chapter 2.
  4. The SDK displays the payment window with WebView2, so the WebView2 runtime must be installed on the user's PC.

Brick Smash reads the shop key from shop_key in the configuration file (config/stove_config.ini). If this value is empty, the shop and inventory cannot be used.

ini
[stove]
; In-game shop key. If left empty, the payment feature is not initialized.
shop_key = YOUR_SHOP_KEY

Initialize() in src/stove/StoveSession.cpp uses payment, so it sets both the shop key and the main window handle.

cpp
// Since we're using payment, include both the shop key and the main window handle. If there is no payment, Stove_Initialize(nullptr) is sufficient.
param->SetShopKey(cfg_->shop_key.c_str());
param->SetMainWndHandle(hwnd_);

The main window handle is valid only after the window is created. Brick Smash initializes after creating the window, so it passes the handle as is.

Five Functions

FunctionWhat It DoesCallback Result
Stove_FetchShopCategoriesFetches the shop category list.IStoveShopCategoryList
Stove_FetchProductsFetches the product list by category and page.IStoveProductList
Stove_StartPurchaseStarts the purchase of one or more products.IStoveStartPurchaseOutcome + payment window closed callback
Stove_ConfirmPurchaseConfirms a started purchase.IStoveConfirmPurchaseOutcome
Stove_FetchInventoryFetches the user's purchase history (inventory).IStoveInventoryList

Brick Smash keeps its SDK calls in src/stove/StoveIAP.cpp. It exposes three functions, and because its payment flow is WithWebViewAndConfirmResult, it does not use Stove_ConfirmPurchase() or Stove_FetchShopCategories().

cpp
// In-game store. The SDK WebView displays the payment window and handles the process through confirmation (WithWebViewAndConfirmResult).
namespace StoveIAP
{
    void FetchProducts(ShopState* out);
    void StartPurchase(int64_t productId, double salePrice, ShopState* out);
    void FetchInventory(InventoryState* out);
}

This code is src/stove/StoveIAP.h. The state structs (ShopState · InventoryState) pass callback results to the screen in the same way as described in Chapter 5.

Call Order

  1. When the shop screen opens, fetch the product list with Stove_FetchProducts(). If category tabs are needed, fetch the categories first with Stove_FetchShopCategories().
  2. When the user selects a product, start the purchase with Stove_StartPurchase().
  3. Confirm the purchase according to the payment flow (Operation).
    • WithWebViewAndConfirmResult: The SDK displays the payment window and, when the payment succeeds, returns the result with confirmation already done through the Stove_StartPurchase() callback. The game does not call Stove_ConfirmPurchase().
    • Default · WithWebView: After the payment ends, the purchase is completed only when the game calls Stove_ConfirmPurchase() itself.
  4. Grant the products received in the confirmation result in the game.
  5. When the game starts and when the shop opens, fetch the purchase history with Stove_FetchInventory() and grant any items not yet granted.

This chapter is based on the simplest flow, WithWebViewAndConfirmResult, and the other flows are explained separately in Payment Flow.

Fetching Products (Stove_FetchProducts)

cpp
void Stove_FetchProducts(const IStoveFetchProductsParam* params, OnFetchProductsCallback onFinished, void* userData);
typedef void(__cdecl* OnFetchProductsCallback)(const IStoveCallbackResult* callbackResult, const IStoveProductList* list);
SetterFormatDescription
SetCategoryIdconst wchar_t*Category ID. If empty, products of all categories are returned.
SetPageIndexuint32_tPage number, starting at 1.
SetPageSizeuint32_tNumber of products per page.

The product (IStoveProduct) values mainly used for the shop screen and purchase requests are as follows.

MethodReturn TypeDescription
GetProductId()int64_tProduct ID. Passed in the purchase request.
GetInserviceItemId()const wchar_t*Game-side item ID linked to this product. Used to choose the item to grant.
GetProductName() · GetProductDescription()const wchar_t*Localized product name and description.
GetQuantity()int32_tNumber of items included in one purchase.
GetProductTypeCode()int32_tProduct type. An EStoveProductTypeCode value.
GetCurrencyCode()const wchar_t*Currency code (ISO 4217, e.g., KRW, USD).
GetPrice() · GetSalePrice()doubleList price and sale price used for payment processing. Both are the same when no discount applies.
GetStrDisplayPrice() · GetStrDisplaySalePrice()const wchar_t*Price strings formatted with the currency for display.
IsDiscounted()booltrue if currently discounted.
GetDiscountType() · GetDiscountTypeValue()int32_tDiscount type (percentage · fixed amount) and discount amount.
HasPurchased()booltrue if the user has purchased this product at least once.
GetPurchaseAvailabilityCode()int16_tPurchase availability. 1 is available, 2 is purchase limit exceeded, 3 is sold out, and 4 is already received. It assumes a purchase of one product, so the result can differ when two or more are requested together.
GetThumbnailUrl()const wchar_t*URL of the main image.

For the remaining values, such as discount period, sale period, and purchase limit policy, see IStoveProduct in the header.

The following is FetchProducts() in src/stove/StoveIAP.cpp.

cpp
void StoveIAP::FetchProducts(ShopState* out)
{
    auto param = StoveMakeParam<IStoveFetchProductsParam>();
    if (!param.IsValid())
        return;
    param->SetCategoryId(L""); // Clear to show all categories
    param->SetPageIndex(1);
    param->SetPageSize(20);

    out->status = AsyncStatus::Loading;
    Stove_FetchProducts(param.Get(), OnFetchProductsFinished, out);
}

The callback copies the values needed for the purchase request (product ID and sale price) and the values for display.

cpp
void __cdecl OnFetchProductsFinished(const IStoveCallbackResult* r, const IStoveProductList* list)
{
    auto* st = Self<ShopState>(r);
    if (!r->GetResult()->IsSuccessful())
    {
        st->status = AsyncStatus::Error;
        st->error = DescribeFailure(r);
        return;
    }
    st->products.clear();
    for (uint32_t i = 0; i < list->GetCount(); ++i)
    {
        const IStoveProduct* p = list->GetAt(i);
        if (p == nullptr)
            continue;
        ShopState::Product item;
        item.id = p->GetProductId();
        item.name = WideToUtf8(p->GetProductName());
        item.desc = WideToUtf8(p->GetProductDescription());
        item.priceStr = WideToUtf8(p->GetStrDisplaySalePrice()); // Display string with a currency format applied
        item.salePrice = p->GetSalePrice();                       // Forward the payment request as is
        item.purchased = p->HasPurchased();
        st->products.push_back(item);
    }
    st->status = AsyncStatus::Done;
}

Use GetStrDisplaySalePrice() to show the price on screen and GetSalePrice() to pass it in the purchase request. The two values serve different purposes.

Fetching Categories (Stove_FetchShopCategories)

Brick Smash does not split products into categories, so it does not use this function. Only the function signature and methods are introduced here for games that need shop tabs.

cpp
void Stove_FetchShopCategories(const IStoveTypeBase* param, OnFetchShopCategoriesCallback onFinished, void* userData);
typedef void(__cdecl* OnFetchShopCategoriesCallback)(const IStoveCallbackResult* callbackResult, const IStoveShopCategoryList* list);

Pass nullptr as the parameter. Iterate over the list (IStoveShopCategoryList) with GetCount() · GetAt(index).

Method (IStoveShopCategory)Return TypeDescription
GetCategoryId()const wchar_t*Category ID. Passed to the product query.
GetCategoryParentId()const wchar_t*Parent category ID. Empty string for a top-level category.
GetCategoryDisplayNo()int32_tDisplay order among categories at the same level.
GetCategoryName()const wchar_t*Localized category name.
GetCategoryDepth()int32_tDepth in the category tree. 0 at the top level.

Starting a Purchase (Stove_StartPurchase)

cpp
void Stove_StartPurchase(const IStoveStartPurchaseParam* params,
                         OnStartPurchaseCallback onFinished, OnIAPPopupDestroyCallback onDestroy,
                         void* userData1, void* userData2);
typedef void(__cdecl* OnStartPurchaseCallback)(const IStoveCallbackResult* callbackResult, const IStoveStartPurchaseOutcome* outcome);
typedef void(__cdecl* OnIAPPopupDestroyCallback)(const IStoveCallbackResult* callbackResult, const IStoveTypeBase* reserved);

It takes two callbacks. onFinished reports the purchase result, and onDestroy reports that every payment window opened by this call has closed. userData1 goes to onFinished, and userData2 goes to onDestroy. The second argument of onDestroy (reserved) is always nullptr.

The parameter is built from three kinds of objects.

ObjectType ValueSetterDescription
IStoveOrderProductParamk_EStoveIAPTypeKind_OrderProductParamSetProductId(int64_t) · SetSalePrice(double) · SetQuantity(int32_t)Order information for one product. Set the sale price to the GetSalePrice() value from the product query. The server uses it to verify the price.
IStovePurchaseParamk_EStoveIAPTypeKind_PurchaseParamSetOperation(int32_t) · SetWebViewMode(int32_t) · SetWebViewPosX · SetWebViewPosY · SetWebViewWidth · SetWebViewHeight (all int32_t, in pixels)Payment flow and payment window position and size. Position and size are used only when Operation is not Default.
IStoveStartPurchaseParamk_EStoveIAPTypeKind_StartPurchaseParamSetProducts(IStoveOrderProductParam**, uint32_t) · SetPurchaseParam(IStovePurchaseParam*) · SetServiceTxnNo(const wchar_t*) · SetExtraData(const wchar_t*)Bundles the two objects above. ServiceTxnNo (game-side transaction number) and ExtraData (usually a JSON string) are optional.

Set SetWebViewMode to k_EStoveWebViewMode_External (0, a window separate from the game window) or k_EStoveWebViewMode_Internal (1, a child window of the game's main window). If Internal is not available, the window opens as External.

IStoveStartPurchaseOutcome delivered to the callback has the following values.

MethodReturn TypeDescription
GetTxnMasterNo()int64_tPurchase transaction number. Passed to Stove_ConfirmPurchase().
GetTxnDetailNos() · GetTxnDetailNosCount()const int64_t* · uint32_tArray of per-product transaction detail numbers and its count.
GetPurchaseProgress()int32_tProgress status. With k_EStovePurchaseProgress_NeedPaymentWindow(1), the game must open the payment window itself; with k_EStovePurchaseProgress_NotNeedPaymentWindow(2), no payment window is needed.
GetTempPaymentUrl()const wchar_t*One-time payment URL. Provided when Operation is Default.
IsPurchased()booltrue if payment and confirmation succeeded with WithWebViewAndConfirmResult.
GetPurchasedProductCount() · GetPurchasedProductAt(i)uint32_t · const IStovePurchasedProduct*List of purchased products. Filled when payment succeeds with WithWebViewAndConfirmResult.
GetChargeInfoCount() · GetChargeInfoAt(i)uint32_t · const IStoveChargeInfo*List of payment methods used.
GetExtraData()const wchar_t*Returns the ExtraData set in the request as is.
IsPopupCreated()boolWhether this call created at least one payment window. Always check it, regardless of success or failure. If false, onDestroy is not delivered.

A purchased product (IStovePurchasedProduct) has GetTxnDetailNo() (transaction detail number) · GetProductId() · GetCategoryId() · GetTotalQuantity() · GetMemberQuantity() · GetGuidQuantity().

The following is StartPurchase() in src/stove/StoveIAP.cpp. It builds the three parameters and makes the call.

cpp
void StoveIAP::StartPurchase(int64_t productId, double salePrice, ShopState* out)
{
    // Assemble the three parameters. Since destroying the parent does not release the children, manage each one using StoveGuard.
    auto order = StoveMakeParam<IStoveOrderProductParam>();
    auto option = StoveMakeParam<IStovePurchaseParam>();
    auto param = StoveMakeParam<IStoveStartPurchaseParam>();
    if (!order.IsValid() || !option.IsValid() || !param.IsValid())
        return;

    order->SetProductId(productId);
    order->SetSalePrice(salePrice); // The value received from the product lookup, exactly as is. The server checks for price discrepancies.
    order->SetQuantity(1);

    option->SetOperation(k_EStovePurchaseOperation_WithWebViewAndConfirmResult);
    option->SetWebViewMode(k_EStoveWebViewMode_Internal); // Child window of the game window
    option->SetWebViewPosX(50);  // Since all values are 0 immediately after creation, be sure to include them.
    option->SetWebViewPosY(50);
    option->SetWebViewWidth(800);
    option->SetWebViewHeight(600);

    IStoveOrderProductParam* orders[] = { order.Get() };
    param->SetProducts(orders, 1);
    param->SetPurchaseParam(option.Get());

    out->purchaseStatus = AsyncStatus::Loading;
    out->purchaseError.clear();
    out->popupOpen = true;
    // userData1 → onFinished, userData2 → onDestroy
    Stove_StartPurchase(param.Get(), OnStartPurchaseFinished, OnPurchasePopupDestroyed, out, out);
    // Since the SDK copies the necessary values before returning them, it is safe to free `param`, `option`, and `order` here.
}

Three points to note in this code:

  • Calling Destroy() on the parent (IStoveStartPurchaseParam) does not release the child objects passed with SetProducts · SetPurchaseParam. That is why each of the three is managed by its own StoveGuard. When Stove_StartPurchase() returns, the SDK has already copied the values it needs, so releasing all three at the end of the function is safe.
  • The payment window position and size (WebViewPosX · WebViewPosY · WebViewWidth · WebViewHeight) are all 0 right after the parameter is created. Without values, a window of size 0 is created. Choose them to fit the game's screen resolution.
  • The same out is passed as userData1 and userData2 because both callbacks use the same state (ShopState).

The following is the purchase result callback OnStartPurchaseFinished(). It distinguishes three cases: payment and confirmation completed (IsPurchased()), the call succeeded but nothing was purchased, and the call failed.

cpp
// Payment + Confirmation Result. In `WithWebViewAndConfirmResult`, this occurs after confirmation is complete.
void __cdecl OnStartPurchaseFinished(const IStoveCallbackResult* r, const IStoveStartPurchaseOutcome* outcome)
{
    auto* st = Self<ShopState>(r);
    if (r->GetResult()->IsSuccessful() && outcome->IsPurchased())
    {
        // Duplicate payments are prevented based on the transaction detail number (GetPurchasedProductAt(i)->GetTxnDetailNo()).
        st->justPurchased = true;
        st->purchaseStatus = AsyncStatus::Done;
        st->status = AsyncStatus::Idle; // Reread the product list and update the `HasPurchased` field.
    }
    else if (r->GetResult()->IsSuccessful())
    {
        // The request was successful, but the purchase was not finalized (e.g., if the window was closed without completing payment).
        st->purchaseStatus = AsyncStatus::Idle;
    }
    else
    {
        st->purchaseStatus = AsyncStatus::Error;
        st->purchaseError = DescribeFailure(r);
    }

    // If the payment window isn't created, `onDestroy` won't be called, so we'll clean up here.
    if (!outcome->IsPopupCreated())
        st->popupOpen = false;
}

When every payment window has closed, OnPurchasePopupDestroyed() is called. It clears popupOpen so that the purchase button can be pressed again.

cpp
// This event occurs when all payment windows opened by this call have been closed.
void __cdecl OnPurchasePopupDestroyed(const IStoveCallbackResult* r, const IStoveTypeBase* /*reserved*/)
{
    Self<ShopState>(r)->popupOpen = false;
}

If IsPopupCreated() is false, onDestroy is not delivered for this call. This is the case where the call failed before a payment window was created. For this reason, OnStartPurchaseFinished() clears popupOpen itself at the very end. Without it, the purchase button stays disabled forever.

Payment Flow

The value set with IStovePurchaseParam::SetOperation decides who displays the payment window and who confirms the purchase.

ValuePayment WindowPurchase ConfirmationWhen onFinished Arrives
k_EStovePurchaseOperation_Default(0)The SDK does not display it. The game opens the payment page itself with the one-time URL from GetTempPaymentUrl().The game calls Stove_ConfirmPurchase().When the payment URL is ready
k_EStovePurchaseOperation_WithWebView(1)The SDK displays the payment window.The game calls Stove_ConfirmPurchase().Immediately after opening the payment window
k_EStovePurchaseOperation_WithWebViewAndConfirmResult(2)The SDK displays the payment window.When the payment succeeds, the SDK also confirms the purchase.When confirmation is complete. If the window is closed before the payment is completed, the callback reports a failure.

Brick Smash uses WithWebViewAndConfirmResult, so it does not call Stove_ConfirmPurchase(). It is the simplest flow and is recommended for a first integration.

  • A purchase started with Default · WithWebView is not complete until the game calls Stove_ConfirmPurchase(), even if the payment was finished in the payment window. With WithWebView, call confirmation after onDestroy reports that the payment window closed, and use IsConfirmed() of the confirmation result to decide whether the payment actually went through.
  • If the total price of the products is 0, the purchase completes immediately without a payment window, regardless of Operation. In this case, GetPurchaseProgress() is NotNeedPaymentWindow(2). In the Default flow, always opening the payment URL without checking this value causes incorrect behavior.
  • When a 0-priced product is purchased with WithWebViewAndConfirmResult, IsPurchased() is true in the Stove_StartPurchase() callback. Confirmation is already done, so do not call Stove_ConfirmPurchase().

Confirming a Purchase (Stove_ConfirmPurchase)

cpp
void Stove_ConfirmPurchase(const IStoveConfirmPurchaseParam* param, OnConfirmPurchaseCallback onFinished, void* userData);
typedef void(__cdecl* OnConfirmPurchaseCallback)(const IStoveCallbackResult* callbackResult, const IStoveConfirmPurchaseOutcome* outcome);

Confirms a purchase whose Operation is not WithWebViewAndConfirmResult.

SetterFormatDescription
SetTxnMasterNoint64_tThe GetTxnMasterNo() value from the Stove_StartPurchase() result.
Method (IStoveConfirmPurchaseOutcome)Return TypeDescription
IsConfirmed()booltrue if the purchase was confirmed.
GetPurchasedProductCount() · GetPurchasedProductAt(i)uint32_t · const IStovePurchasedProduct*List of purchased products.
GetChargeInfoCount() · GetChargeInfoAt(i)uint32_t · const IStoveChargeInfo*List of payment methods used.

A payment method (IStoveChargeInfo) has GetChargeType() (2 coupon, 98 STOVE Cash, 99 points, other values are external payment methods) · GetChargeTypeName() · GetChargeDeductVal() · GetChargeDisplayDeductVal().

The code below is a flow that the sample game does not have. It is a short example that confirms a purchase started with WithWebView after the payment window closes. Copy GetTxnMasterNo() in the purchase start callback, and confirm with the code below in onDestroy. GrantItemOnce() is a placeholder function that the SDK does not provide. The game must implement its own grant function that prevents duplicate grants by the transaction detail number.

cpp
// This is the value I copied from GetTxnMasterNo() in the purchase start callback.
static int64_t g_pendingTxnMasterNo = 0;

void __cdecl OnConfirmPurchaseFinished(const IStoveCallbackResult* callbackResult, const IStoveConfirmPurchaseOutcome* outcome)
{
    if (callbackResult->GetResult()->IsSuccessful() && outcome->IsConfirmed())
    {
        for (uint32_t i = 0; i < outcome->GetPurchasedProductCount(); ++i)
        {
            const IStovePurchasedProduct* purchased = outcome->GetPurchasedProductAt(i);
            if (purchased == nullptr)
                continue;
            // This is a virtual function. It checks whether payment has already been made using the transaction ID before processing the payment.
            GrantItemOnce(purchased->GetTxnDetailNo(), purchased->GetProductId(), purchased->GetTotalQuantity());
        }
    }
    // Even if the call is successful, if IsConfirmed() returns false, the purchase is considered unconfirmed, so payment will not be made.
}

// Call this after the payment window closes (onDestroy).
auto param = StoveMakeParam<IStoveConfirmPurchaseParam>();
if (param.IsValid())
{
    param->SetTxnMasterNo(g_pendingTxnMasterNo);
    Stove_ConfirmPurchase(param.Get(), OnConfirmPurchaseFinished, nullptr);
}

Call success (IsSuccessful()) and confirmation (IsConfirmed()) are separate. Even when the call succeeds, if IsConfirmed() is false, the purchase is not confirmed, so do not grant the item.

Fetching the Inventory (Stove_FetchInventory)

cpp
void Stove_FetchInventory(const IStoveTypeBase* param, OnFetchInventoryCallback onFinished, void* userData);
typedef void(__cdecl* OnFetchInventoryCallback)(const IStoveCallbackResult* callbackResult, const IStoveInventoryList* list);

Fetches the signed-in user's purchase history (inventory). Pass nullptr as the parameter and iterate over the list with GetCount() · GetAt(index).

Method (IStoveInventoryItem)Return TypeDescription
GetTxnMasterNo()int64_tPurchase transaction number.
GetTxnDetailNo()int64_tPer-product transaction detail number. Used as the key to prevent duplicate grants.
GetProductId()int64_tProduct ID.
GetInserviceItemId()const wchar_t*Game-side item ID.
GetProductName()const wchar_t*Localized product name.
GetQuantity()int32_tPurchased quantity.
GetThumbnailUrl()const wchar_t*URL of the main image.

The following is FetchInventory() in src/stove/StoveIAP.cpp. No parameter is needed, so it passes nullptr.

cpp
void StoveIAP::FetchInventory(InventoryState* out)
{
    out->status = AsyncStatus::Loading;
    Stove_FetchInventory(nullptr, OnFetchInventoryFinished, out);
}

The callback copies the transaction detail number, product name, and quantity of each item.

cpp
void __cdecl OnFetchInventoryFinished(const IStoveCallbackResult* r, const IStoveInventoryList* list)
{
    auto* st = Self<InventoryState>(r);
    if (!r->GetResult()->IsSuccessful())
    {
        st->status = AsyncStatus::Error;
        st->error = DescribeFailure(r);
        return;
    }
    st->items.clear();
    for (uint32_t i = 0; i < list->GetCount(); ++i)
    {
        const IStoveInventoryItem* item = list->GetAt(i);
        if (item == nullptr)
            continue;
        st->items.push_back({ item->GetTxnDetailNo(), WideToUtf8(item->GetProductName()), item->GetQuantity() });
    }
    st->status = AsyncStatus::Done;
}

The inventory screen of Brick Smash (DrawInventoryScreen()) shows the product name, quantity, and transaction detail number of each item as is.

cpp
for (const auto& it : st.items)
    ImGui::Text("%s  x%d  (transaction detail no. %lld)", it.name.c_str(), it.quantity,
                static_cast<long long>(it.txnDetailNo));

If the client exits unexpectedly or the network drops, a purchase can be complete while the item has not been granted. A game that actually grants items should fetch the inventory when the game starts and when the shop opens, find items not yet granted by GetTxnDetailNo(), and finish granting them.

Shop Screen

DrawShopScreen() in src/ui/ServiceScreens.cpp does not attempt any call when the shop key is empty and only shows a message.

cpp
if (ctx.cfg->shop_key.empty())
{
    if (DrawHeader("Shop"))
        *ctx.current = AppScreen::Menu;
    ImGui::TextUnformatted("shop_key is not set. Please check config/stove_config.ini.");
    return;
}

The purchase button is disabled while a payment window is open or a purchase is in progress, so pressing the same product repeatedly cannot stack payment windows. Products already purchased (HasPurchased()) show a message instead of the button.

cpp
if (p.purchased)
{
    ImGui::TextColored(ImVec4(1, 0.7f, 0.3f, 1), "Already purchased");
}
else
{
    bool busy = st.popupOpen || st.purchaseStatus == AsyncStatus::Loading;
    ImGui::BeginDisabled(busy);
    if (ImGui::Button("Buy"))
    {
        st.justPurchased = false;
        StoveIAP::StartPurchase(p.id, p.salePrice, &st);
    }
    ImGui::EndDisabled();
}

When the purchase completes (justPurchased), the screen shows a banner at the top and fetches the product list again to update HasPurchased(). The product list is fetched again because OnStartPurchaseFinished() resets status to Idle. The next time the shop screen is drawn, it sees Idle and calls FetchProducts() again.

cpp
// "Purchase Complete" Banner (Top)
if (st.justPurchased)
{
    ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.15f, 0.45f, 0.2f, 1.0f));
    ImGui::BeginChild("buy_banner", ImVec2(0, 32), true);
    ImGui::TextColored(ImVec4(0.7f, 1.0f, 0.7f, 1.0f), "Item purchased!");
    ImGui::EndChild();
    ImGui::PopStyleColor();
}

Points to Note

If the SDK was initialized without a shop key, the functions in this chapter do not work. Check that both SetShopKey and SetMainWndHandle are set on the initialization parameter.

When the SDK displays the payment window (WithWebView · WithWebViewAndConfirmResult), the game's full-screen mode is restricted. The payment window does not appear in Exclusive Fullscreen, so use Borderless Windowed Fullscreen.

To close all payment windows at once, use Stove_CloseAllPopups(). It is a synchronous function that returns IStoveResult*, so check the result and then call Destroy().

Product, purchase, and inventory objects and arrays (including GetTxnDetailNos()) received in callbacks become invalid when the callback ends. Copy the needed values inside the callback. Callbacks run on the thread that called Stove_RunCallback(), so copying into a state struct as Brick Smash does lets the screen code read the values safely.

When granting items, always check by transaction detail number (TxnDetailNo) whether they were already granted. The same transaction can appear twice, in the purchase callback and in the inventory query.

If the confirmation callback fails or IsConfirmed() is false, do not grant the item; fetch the unconfirmed purchase again with Stove_FetchInventory() and handle it.

Prices and currency codes can differ per user. Show prices with formatted strings such as GetStrDisplaySalePrice(), and pass the GetSalePrice() value as is in purchase requests.

7. Game Time Limits in Vietnam

Under Vietnamese law, games serving Vietnam must show an age rating and over-immersion notices on screen. This chapter follows the Brick Smash code that receives the notifications and draws overlays, and explains how to use the two functions.

The Korean shutdown and over-immersion notifications are covered in Chapter 4. For initialization and termination, see Chapter 2.

What to Integrate

Services in Vietnam must integrate both the age rating display and the over-immersion notification.

FunctionTargetWhen the Callback ArrivesCallback Info
Stove_VietnamAgeRatingNotificationUsers in VietnamWhen the age rating overlay must be shown or hiddenIStoveVietnamAgeRatingInfo
Stove_VietnamOverimmersionNotificationUsers in VietnamAt regular intervals (including immediately after the game starts)IStoveVietnamOverimmersionInfo

Both are functions that register a callback to receive notifications. After one call, the SDK sends the callback as many times as needed. The SDK does not use the first argument, so pass nullptr.

cpp
void Stove_VietnamAgeRatingNotification(const IStoveTypeBase* param, OnVietnamAgeRatingNotificationCallback onFinished, void* userData);
void Stove_VietnamOverimmersionNotification(const IStoveTypeBase* param, OnVietnamOverimmersionNotificationCallback onFinished, void* userData);
typedef void(__cdecl* OnVietnamAgeRatingNotificationCallback)(const IStoveCallbackResult* callbackResult, const IStoveVietnamAgeRatingInfo* ageRatingInfo);
typedef void(__cdecl* OnVietnamOverimmersionNotificationCallback)(const IStoveCallbackResult* callbackResult, const IStoveVietnamOverimmersionInfo* overimmersionInfo);

Both functions are Vietnam-only. If the country determined from the connection IP is not Vietnam, they fail with NotSupportedCountry(31). This failure is normal. Do not show it as an error to users in other countries; ignore it silently.

Call Order

  1. Once the window exists and Stove_Initialize() succeeds, the screen can be drawn, so call each of the two functions once right away.
  2. Each time a callback arrives in Stove_RunCallback() of the game loop, copy the delivered information into game variables.
  3. The rendering code draws the overlays from the copied values.
  4. The game counts down the display time every frame and hides overlays whose time is up.

Register the two Vietnam functions after the screen can be drawn. The over-immersion notification also arrives once right after the game starts (0 minutes elapsed), so registering earlier means the first notice cannot be shown. Brick Smash initializes after creating the window, so it registers them directly in Initialize().

The following is the end of Initialize() in src/stove/StoveSession.cpp. After the two Korean notifications (shutdown · over-immersion), it registers the two Vietnam notifications.

cpp
// 3) Register a regulatory notification callback. Once registered, the SDK will send a callback whenever necessary.
Stove_ShutdownNotification(nullptr, OnShutdownNotificationFinished, this);
Stove_OverImmersionNotification(nullptr, OnOverImmersionNotificationFinished, this);
// The two Vietnamese notifications must be registered after the point at which the screen can be drawn. Since this example initializes the window after creating it, the notifications are registered here.
Stove_VietnamAgeRatingNotification(nullptr, OnVietnamAgeRatingNotificationFinished, this);
Stove_VietnamOverimmersionNotification(nullptr, OnVietnamOverimmersionNotificationFinished, this);

this of StoveSession is passed as userData, and the callbacks near the top of the same file retrieve the pointer and forward to OnVietnamAgeRating() and OnVietnamOverimmersion().

cpp
void __cdecl OnVietnamAgeRatingNotificationFinished(const IStoveCallbackResult* r, const IStoveVietnamAgeRatingInfo* info)
{
    Self(r)->OnVietnamAgeRating(r, info);
}
void __cdecl OnVietnamOverimmersionNotificationFinished(const IStoveCallbackResult* r, const IStoveVietnamOverimmersionInfo* info)
{
    Self(r)->OnVietnamOverimmersion(r, info);
}

Overlay Mode (EStoveOverlayMode)

Both notifications report how to handle the overlay through GetOverlayMode(). The value is an EStoveOverlayMode.

ValueNameMeaning
0k_EStoveOverlayMode_ShowShow the overlay. For the over-immersion notification, it means the timer has started, so nothing needs to be shown yet.
1k_EStoveOverlayMode_HideHide the overlay.
2k_EStoveOverlayMode_ExpandedShow the overlay expanded. Sent with the over-immersion notification.

The age rating notification decides visibility with Show and Hide, and the over-immersion notification is shown expanded on Expanded and hidden on Hide.

Overlay Appearance

Both notifications also send values that define the overlay's appearance.

ValueDescription
Theme (GetOverlayType())0 is Black: white text on a dark background, RGB(33,33,33). 1 is White: black text on a white background, RGB(255,255,255). The default is White.
Scale (GetOverlayScale())0.0 to 1.0.
Opacity (GetOverlayOpacity())0.0 to 1.0.
Position (GetDisplayPositionX() · GetDisplayPositionY())Ratios from the left and top of the screen, each 0.0 to 1.0.

The position is a ratio of the screen size rather than pixels, so the same value works when the resolution changes.

Age Rating Notification (Stove_VietnamAgeRatingNotification)

Keeps the game's age rating on screen. The game itself draws the overlay.

Method (IStoveVietnamAgeRatingInfo)Return TypeDescription
GetOverlayMode()int32_tOverlay mode. Show on Show(0), hide on Hide(1).
GetOverlayType()int32_tTheme. 0 is Black, 1 is White.
GetOverlayScale()floatOverlay scale, 0.0 to 1.0.
GetOverlayOpacity()floatOverlay opacity, 0.0 to 1.0.
GetAgeRating()int32_tGame age rating. 0 is all ages, and 12 · 16 · 18 mean that age and older.
GetMsg()const wchar_t*Age rating notice message.
GetDisplayPositionX()floatX coordinate of the display position, 0.0 to 1.0 from the left of the screen.
GetDisplayPositionY()floatY coordinate of the display position, 0.0 to 1.0 from the top of the screen.
GetLanguage()const wchar_t*Language code used to choose the font (e.g., ko, en, vi, zh-cn).

The overlay is drawn outside the callback, so a struct to hold copies of the values is needed. This is AgeRatingOverlay in src/stove/StoveSession.h.

cpp
// Vietnam Age Rating Overlay. Since it is drawn outside the callback, the value is copied and stored.
struct AgeRatingOverlay
{
    bool visible = false;
    int32_t type = 1;          // 0 Black, 1 White
    float scale = 1.0f;
    float opacity = 1.0f;
    int32_t ageRating = 0;
    std::string message;
    float posX = 0.0f;
    float posY = 0.0f;
};

OnVietnamAgeRating() in src/stove/StoveSession.cpp copies the values in the callback. A failure result can mean the user is not in Vietnam, so it returns silently.

cpp
void StoveSession::OnVietnamAgeRating(const IStoveCallbackResult* r, const IStoveVietnamAgeRatingInfo* info)
{
    // For Vietnam only. Users in other countries will receive a "NotSupportedCountry (31)" error, which is normal.
    if (!r->GetResult()->IsSuccessful())
        return;

    ageRating_.visible = (info->GetOverlayMode() == k_EStoveOverlayMode_Show);
    ageRating_.type = info->GetOverlayType();
    ageRating_.scale = info->GetOverlayScale();
    ageRating_.opacity = info->GetOverlayOpacity();
    ageRating_.ageRating = info->GetAgeRating();
    ageRating_.message = WideToUtf8(info->GetMsg());
    ageRating_.posX = info->GetDisplayPositionX();
    ageRating_.posY = info->GetDisplayPositionY();
}

visible becomes true only on Show. When Hide arrives, it becomes false and the overlay disappears. There is no code that hides it on a timer.

The age rating overlay stays visible by default. The game does not hide it on its own until Hide arrives.

Over-Immersion Notification (Stove_VietnamOverimmersionNotification)

The following values come in addition to those of the age rating notification.

Method (IStoveVietnamOverimmersionInfo)Return TypeDescription
GetOverlayMode()int32_tOverlay mode. Show(0) means the timer has started and nothing needs to be shown yet, Expanded(2) means show the overlay expanded, and Hide(1) means hide it.
GetOverlayType() · GetOverlayScale() · GetOverlayOpacity() · GetAgeRating()Same as the age rating infoSame meaning as the methods of the same name in the age rating info.
GetMsg()const wchar_t*Over-immersion warning message.
GetStyledMsg()const wchar_t*Warning message with formatting tags such as bold and color (e.g., <b>, <color=#RRGGBBAA>). Use this value if the UI can render formatted text; otherwise, use GetMsg().
GetElapsedMinutes()int32_tTime spent playing, in minutes.
GetExposureTime()int32_tMessage display time, in seconds. Hide the overlay after this time.
GetExpandAnimationTime()floatDuration of the animation that expands the overlay when it changes from Show to Expanded, in seconds.
GetDisplayPositionX() · GetDisplayPositionY()floatDisplay position, 0.0 to 1.0 from the left and top of the screen.
GetLanguage()const wchar_t*Language code used to choose the font.

OverimmersionOverlay in src/stove/StoveSession.h additionally holds the remaining display time (secondsLeft).

cpp
// Vietnam Immersion Overlay.
struct OverimmersionOverlay
{
    bool visible = false;
    int32_t type = 1;
    float scale = 1.0f;
    float opacity = 1.0f;
    std::string message;
    float secondsLeft = 0.0f;
    float posX = 0.0f;
    float posY = 0.0f;
};

OnVietnamOverimmersion() handles three cases based on the overlay mode.

cpp
void StoveSession::OnVietnamOverimmersion(const IStoveCallbackResult* r, const IStoveVietnamOverimmersionInfo* info)
{
    if (!r->GetResult()->IsSuccessful())
        return;

    int32_t mode = info->GetOverlayMode();
    if (mode == k_EStoveOverlayMode_Expanded)
    {
        // Display it when expanded, and hide it when the exposure time has elapsed.
        overimmersion_.visible = true;
        overimmersion_.type = info->GetOverlayType();
        overimmersion_.scale = info->GetOverlayScale();
        overimmersion_.opacity = info->GetOverlayOpacity();
        overimmersion_.message = WideToUtf8(info->GetMsg()); // If you can draw formatted text, use GetStyledMsg()
        overimmersion_.secondsLeft = static_cast<float>(info->GetExposureTime());
        overimmersion_.posX = info->GetDisplayPositionX();
        overimmersion_.posY = info->GetDisplayPositionY();
    }
    else if (mode == k_EStoveOverlayMode_Hide)
    {
        overimmersion_.visible = false;
    }
    // "Show" means the timer has started, so it is not displayed yet.
}

Brick Smash draws with ImGui text, which cannot interpret formatting tags, so it uses GetMsg(). A UI that can render formatted text can use GetStyledMsg() to show the text with bold and color applied.

Counting Down the Display Time

An overlay shown with Expanded is hidden after GetExposureTime() seconds. The SDK only provides the exposure time as a value, so the game counts down the remaining time itself. Brick Smash decreases secondsLeft by the frame's elapsed time (dt) in Pump(), right after calling Stove_RunCallback(). This Pump() is in src/stove/StoveSession.cpp, and the game loop in src/main.cpp calls it every frame.

cpp
void StoveSession::Pump(float dt)
{
    // All asynchronous callbacks are executed within this call, on this thread.
    Stove_RunCallback();

    if (notice_.secondsLeft > 0.0f && !notice_.blocksGame)
        notice_.secondsLeft -= dt;
    if (overimmersion_.visible && (overimmersion_.secondsLeft -= dt) <= 0.0f)
        overimmersion_.visible = false;
}

notice_ holds the Korean shutdown and over-immersion notices and is explained in Chapter 4. The part relevant here is the last two lines that count down overimmersion_. The age rating overlay has no time limit and stays until Hide arrives.

Drawing the Overlays

DrawBadge() in src/ui/RegulationOverlay.cpp is the drawing function shared by both overlays. It computes coordinates by multiplying the position ratios by the screen size and picks the background and text colors from the theme.

cpp
// Draw a text box at the screen ratio coordinates (0.0–1.0, relative to the left/top).
// Type 0: Dark background (33, 33, 33) + white text / Type 1: White background + black text
void DrawBadge(const char* text, int type, float scale, float opacity, float posX, float posY)
{
    ImDrawList* dl = ImGui::GetForegroundDrawList();
    ImVec2 screen = ImGui::GetIO().DisplaySize;
    float fontSize = ImGui::GetFontSize() * scale;
    ImVec2 sz = ImGui::GetFont()->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, text);
    const float pad = 8.0f * scale;
    ImVec2 p0(screen.x * posX, screen.y * posY);
    ImVec2 p1(p0.x + sz.x + pad * 2, p0.y + sz.y + pad * 2);

    int a = static_cast<int>(opacity * 255.0f);
    ImU32 bg = type == 0 ? IM_COL32(33, 33, 33, a) : IM_COL32(255, 255, 255, a);
    ImU32 fg = type == 0 ? IM_COL32(255, 255, 255, a) : IM_COL32(0, 0, 0, a);
    dl->AddRectFilled(p0, p1, bg);
    dl->AddRect(p0, p1, fg);
    dl->AddText(ImGui::GetFont(), fontSize, ImVec2(p0.x + pad, p0.y + pad), fg, text);
}

It draws with GetForegroundDrawList(), so it always appears above the game UI. DrawRegulationOverlays() checks visible of both overlays every frame and draws them. The age rating shows the GetAgeRating() value with + appended (e.g., 18+), and the over-immersion overlay shows the text from the SDK as is.

cpp
const AgeRatingOverlay& a = session.ageRating();
if (a.visible)
{
    std::string text = std::to_string(a.ageRating) + "+";
    DrawBadge(text.c_str(), a.type, a.scale, a.opacity, a.posX, a.posY);
}

const OverimmersionOverlay& o = session.overimmersion();
if (o.visible)
    DrawBadge(o.message.c_str(), o.type, o.scale, o.opacity, o.posX, o.posY);

Points to Note

Games serving Vietnam must integrate both the age rating display and the over-immersion notification. Integrating only one is not allowed.

Register both functions only once. After registration, the SDK sends callbacks as many times as needed. Do not register again on each callback.

Users outside Vietnam receive a NotSupportedCountry(31) failure. This is normal, so do not show an error window or block the game.

Register them after the screen can be drawn. The over-immersion notification also arrives right after the game starts (0 minutes elapsed).

The game does not hide the age rating overlay on its own until Hide arrives. The over-immersion overlay is hidden after GetExposureTime() elapses, and immediately when Hide arrives.

Use the overlay text from the SDK (GetMsg() or GetStyledMsg()) as is. The game does not change it or write its own.

Info objects received in callbacks become invalid when the callback ends. Copy the values needed to draw the overlays inside the callback, as Brick Smash does.

For questions about the age rating display criteria, contact technical support.

If you get stuck during integration, contact technical support.

Email : store.support@smilegate.com