Skip to content

Instantly share code, notes, and snippets.

@r-lyeh
Created December 28, 2022 17:12

Revisions

  1. r-lyeh created this gist Dec 28, 2022.
    77 changes: 77 additions & 0 deletions snippets32.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,77 @@
    // useful code snippets gathered from the network (via phillip trudeau)

    static float euclidean_mod(float x, float y) { return x - floorf(x / y) * y; }
    static bool rect_is_onscreen(RECT rect) { return (MonitorFromRect(&rect, MONITOR_DEFAULTTONULL) != NULL); }
    static bool window_is_onscreen(HWND hwnd) { return (MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL) != NULL); }

    // Win32: Set the window icon for every window in your app (including MessageBox() calls and assertion failures) instead of just your primary window.
    static LRESULT set_window_icon_callback(int type, WPARAM wparam, LPARAM lparam) {
    if (type == HCBT_CREATEWND) {
    HANDLE instance_hdl = GetModuleHandleA(NULL);
    SendMessage((HWND)wparam, WM_SETICON, ICON_BIG , (LPARAM)LoadIconA(instance_hdl, MAKEINTRESOURCEA(IDI_ICON1)));
    SendMessage((HWND)wparam, WM_SETICON, ICON_SMALL, (LPARAM)LoadIconA(instance_hdl, MAKEINTRESOURCEA(IDI_ICON1)));
    }
    return CallNextHookEx(NULL, type, wparam, lparam);
    }
    static void set_all_window_icons() {
    SetWindowsHookEx(WH_CBT, set_window_icon_callback, NULL, GetCurrentThreadId());
    }

    bool console_belongs_to_self(void) {
    DWORD pid = 0;
    GetWindowThreadProcessId(GetConsoleWindow(), &pid);
    return pid == GetCurrentProcessId();
    }

    //NOTE: these calls are the closest i'm aware you can get to /SUBSYSTEM:CONSOLE
    // in a gui program while cleanly handling existing consoles (cmd.exe),
    // pipes (ninja) and no console (VS/RemedyBG; double-clicking the game).
    // the other option is to compile with /SUBSYSTEM:CONSOLE and call FreeConsole()
    // if no console is needed but it is amateur to flash a console for a second
    if (!AttachConsole(ATTACH_PARENT_PROCESS) && GetLastError() != ERROR_ACCESS_DENIED) assert(AllocConsole());
    printf("\n"); //print >= 1 byte to distinguish empty stdout from a redirected stdout (fgetpos() position <= 0)
    fpos_t pos = {};
    if (fgetpos(stdout, &pos) != 0 || pos <= 0) {
    assert(freopen("CONIN$" , "r", stdin ));
    assert(freopen("CONOUT$", "w", stderr));
    assert(freopen("CONOUT$", "w", stdout));
    }



    Win10: Get RDTSC interval in constant time, with slow Sleep() path for older versions of Windows
    double s_per_tsc = 3.33e-10;
    bool fast_path = false;
    HMODULE ntdll = LoadLibrary("ntdll.dll");
    if (ntdll) {
    void (*NtQuerySystemInformation)() = (void (*)())GetProcAddress(ntdll, "NtQuerySystemInformation");
    if (NtQuerySystemInformation) {
    uint64_t system_information;
    uint32_t out_size;
    int32_t result = ((int32_t __stdcall (*)(int32_t, void *, uint32_t, uint32_t *))NtQuerySystemInformation)(0xc5, &system_information, sizeof(system_information), &out_size);
    if (out_size == sizeof(system_information) && result >= 0) {
    volatile uint8_t* RtlpHypervisorSharedUserVa = (uint8_t *)system_information;

    // printf("tsc_freq: %7llu\n", (10000000ull << 32) / (*(uint64_t*)(RtlpHypervisorSharedUserVa + 0x08) >> 32));

    s_per_tsc = *(uint64_t*)(RtlpHypervisorSharedUserVa + 0x08) / 184467440737095516160000000.0;
    // printf("s_per_tsc: %.30f\n", s_per_tsc);

    fast_path = true;
    }

    }
    FreeLibrary(ntdll);
    }
    if (!fast_path) {
    LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency);
    LARGE_INTEGER qpc_begin; QueryPerformanceCounter(&qpc_begin);
    uint64_t tsc_begin = __rdtsc();
    Sleep(10);
    LARGE_INTEGER qpc_end; QueryPerformanceCounter(&qpc_end);
    uint64_t tsc_end = __rdtsc();
    s_per_tsc = ((double)(qpc_end.QuadPart - qpc_begin.QuadPart) / frequency.QuadPart) / (tsc_end - tsc_begin);
    }