<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[More Deeper Rendering &amp; C++ Programming Language - Medium]]></title>
        <description><![CDATA[It covers the theory behind building render pipes using low-level graphics APIs, including DirectX, as well as the standards of the C++ programming language, invisible behavior, hardware-related behavior, and exceptions in specific situations. - Medium]]></description>
        <link>https://medium.com/more-deeper-c-programming-language?source=rss----bb2aacb21981---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>More Deeper Rendering &amp;amp; C++ Programming Language - Medium</title>
            <link>https://medium.com/more-deeper-c-programming-language?source=rss----bb2aacb21981---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:46:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/more-deeper-c-programming-language" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create basic windows native application with Win32 API — 1. WNDCLASS]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/create-basic-windows-native-application-with-win32-api-1-wndclass-32932dd7675d?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/32932dd7675d</guid>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[directx-12]]></category>
            <category><![CDATA[winapi]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 05:21:54 GMT</pubDate>
            <atom:updated>2026-04-29T05:21:56.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create basic windows native application with Win32 API — 1. WNDCLASS</h3><h3>Introduction.</h3><p>Continuing from the previous ‘<a href="https://medium.com/@lioie6478/create-basic-windows-native-application-with-win32-api-0-winmain-wwinmain-15bf31259695">WinMain &amp; wWinMain</a>’ section, we will learn about the composition and meaning of WNDCLASS’s member variables and their internal operations.</p><h3>WNDCLASS.</h3><p>The first thing to do within `WinMain` is to create a `WNDCLASS` structure and fill it with its contents.</p><p>`WNDCLASS` is defined as follows:</p><pre>typedef struct tagWNDCLASSA {<br>    UINT        style;<br>    WNDPROC     lpfnWndProc;<br>    int         cbClsExtra;<br>    int         cbWndExtra;<br>    HINSTANCE   hInstance;<br>    HICON       hIcon;<br>    HCURSOR     hCursor;<br>    HBRUSH      hbrBackground;<br>    LPCSTR      lpszMenuName;<br>    LPCSTR      lpszClassName;<br>} WNDCLASSA, *PWNDCLASSA, NEAR *NPWNDCLASSA, FAR *LPWNDCLASSA;<br>typedef struct tagWNDCLASSW {<br>    UINT        style;<br>    WNDPROC     lpfnWndProc;<br>    int         cbClsExtra;<br>    int         cbWndExtra;<br>    HINSTANCE   hInstance;<br>    HICON       hIcon;<br>    HCURSOR     hCursor;<br>    HBRUSH      hbrBackground;<br>    LPCWSTR     lpszMenuName;<br>    LPCWSTR     lpszClassName;<br>} WNDCLASSW, *PWNDCLASSW, NEAR *NPWNDCLASSW, FAR *LPWNDCLASSW;<br><br>#ifdef UNICODE<br>typedef WNDCLASSW WNDCLASS;<br>typedef PWNDCLASSW PWNDCLASS;<br>typedef NPWNDCLASSW NPWNDCLASS;<br>typedef LPWNDCLASSW LPWNDCLASS;<br>#else<br>typedef WNDCLASSA WNDCLASS;<br>typedef PWNDCLASSA PWNDCLASS;<br>typedef NPWNDCLASSA NPWNDCLASS;<br>typedef LPWNDCLASSA LPWNDCLASS;<br>#endif // UNICODE</pre><p>WNDCLASS, like other Win32 API elements, is defined as A and W versions. Version A is based on ANSI encoding, and version W is based on Unicode encoding.</p><h4>UINT style</h4><p>`style` specifies the style of the window to be displayed.</p><p>`style` specifies a style as a bit flag, and its list is defined as follows:</p><pre>/*<br> * Class styles<br> */<br>#define CS_VREDRAW          0x0001<br>#define CS_HREDRAW          0x0002<br>#define CS_DBLCLKS          0x0008<br>#define CS_OWNDC            0x0020<br>#define CS_CLASSDC          0x0040<br>#define CS_PARENTDC         0x0080<br>#define CS_NOCLOSE          0x0200<br>#define CS_SAVEBITS         0x0800<br>#define CS_BYTEALIGNCLIENT  0x1000<br>#define CS_BYTEALIGNWINDOW  0x2000<br>#define CS_GLOBALCLASS      0x4000<br><br>#define CS_IME              0x00010000<br>#if(_WIN32_WINNT &gt;= 0x0501)<br>#define CS_DROPSHADOW       0x00020000<br>#endif /* _WIN32_WINNT &gt;= 0x0501 */</pre><p>For detailed descriptions of each style, please see the following resources:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/winmsg/window-class-styles">Window Class Styles (Winuser.h) - Win32 apps</a></p><p>However, I’d like to point out `CS_IME` and `CS_DROPSHADOW`:</p><ul><li>`CS_IME` is intended for companies that have their own Input Method Editors and is intentionally omitted from the MSDN style documentation. In other words, `CS_IME` is not typically used.</li><li>`CS_DROPSHADOW` is only defined if `#if(_WIN32_WINNT &gt;= 0x0501)` is satisfied. `_WIN32_WINNT` is a means of specifying the supported Windows version. For more information, please refer to the resources below.</li></ul><p><a href="https://learn.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt?view=msvc-170">Update WINVER and _WIN32_WINNT</a></p><h4>WNDPROC lpfnWndProc</h4><p>WNDPROC is defined as follows:</p><pre>typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);</pre><p>In other words, it’s a callback function pointer that returns an `LRESULT` value and takes `HWND`, `UINT`, `WPARAM`, and `LPARAM` as parameters.</p><p>First, `LRESULT` is defined as follows:</p><pre>typedef LONG_PTR LRESULT;<br><br>#if defined(_WIN64)<br>    typedef __int64 LONG_PTR, *PLONG_PTR;<br>#else<br>    typedef _W64 long LONG_PTR, *PLONG_PTR;<br>#endif</pre><p>That is, it is a simple 64-bit integer.</p><p>`CALLBACK` is defined as follows:</p><pre>#define CALLBACK __stdcall</pre><p>In other words, just like `WINAPI` above, it’s ultimately interpreted as `__stdcall`, specifying the calling convention. However, `CALLBACK` also uniquely signifies that the function is a callback function, meaning that its call isn’t explicitly specified in the code, but rather triggered by events or other events.</p><p>The parameters are explained in detail later in this article.</p><p>In the full source code at the top, `lpfnWndProc` uses a custom function called `WndMsgProc`:</p><pre>LRESULT CALLBACK WndMsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)<br>{<br>    return DefWindowProc(hwnd, msg, wParam, lParam);<br>}</pre><p>The above example calls `DefWindowProc` without any special handling, which means it’s the default event handler function.</p><p>If you want to learn more about DefWindowProc, please see the following resources:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-defwindowproca">DefWindowProcA function (winuser.h) - Win32 apps</a></p><h4>int cbClsExtra</h4><p>This is the additional byte size allocated after `WNDCLASS`. This space can literally be used as a buffer.</p><p>If you want to access this space, use `GetClassLongPtr` and `SetClassLongPtr`:</p><pre>WINUSERAPI<br>ULONG_PTR<br>WINAPI<br>GetClassLongPtrA(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex);<br>    <br>WINUSERAPI<br>ULONG_PTR<br>WINAPI<br>GetClassLongPtrW(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex);<br>    <br>#ifdef UNICODE<br>#define GetClassLongPtr  GetClassLongPtrW<br>#else<br>#define GetClassLongPtr  GetClassLongPtrA<br>#endif // !UNICODE<br><br><br>WINUSERAPI<br>ULONG_PTR<br>WINAPI<br>SetClassLongPtrA(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex,<br>    _In_ LONG_PTR dwNewLong);<br>    <br>WINUSERAPI<br>ULONG_PTR<br>WINAPI<br>SetClassLongPtrW(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex,<br>    _In_ LONG_PTR dwNewLong);<br>    <br>#ifdef UNICODE<br>#define SetClassLongPtr  SetClassLongPtrW<br>#else<br>#define SetClassLongPtr  SetClassLongPtrA<br>#endif // !UNICODE</pre><p>`GetClassLongPtr` takes a simple parameter: the `HWND` value returned by `CreateWindow` and the index of the location to be accessed.</p><p>The return type is `ULONG_PTR`, which is simply a `typedef` of `unsigned __int64`.</p><p>`SetClassLongPtr` takes an `HWND`, the index of the location to be accessed, and the `ULONG_PTR` value to be set.</p><p>The return type is `ULONG_PTR`, and the following values ​​are returned:</p><p>- If no value was previously set, 0 is returned.<br>- If a previously set value was found, that value is returned.<br>- If the access attempt fails, 0 is returned. To obtain related error information, call `GetLastError`.</p><p>An example usage example is as follows:</p><pre>wndclass.cbClsExtra = sizeof(ULONG_PTR) * 2;<br><br>SetClassLongPtr(hWnd, 0, 501); // 윈도우 클래스 공간에 502 기록<br>SetClassLongPtr(hWnd2, 0, 601); // 윈도우 클래스 공간에 602 기록<br><br>ULONG_PTR v3 = ::GetClassLongPtr(hWnd, 0);  // v3 == 602<br>ULONG_PTR v4 = ::GetClassLongPtr(hWnd2, 0); // v4 == 602<br><br>ULONG_PTR v1 = GetWindowLongPtr(hWnd, 0); // v1 == 501<br>ULONG_PTR v2 = GetWindowLongPtr(hWnd2, 0); // v2 == 601<br>ULONG_PTR v3 = GetWindowLongPtr(hWnd, sizeof(ULONG_PTR)); // v3 == 502<br>ULONG_PTR v4 = GetWindowLongPtr(hWnd2, sizeof(ULONG_PTR)); // v4 == 602</pre><p>As you can see from the example above, that extra space can be used in a sort of array-like sense.</p><h4>int cbWndExtra</h4><p>This is the additional bytes allocated after the window. This area can be used as a buffer, similar to `cbClsExtra`.</p><p>Note that `cbClsExtra` uses `ULONG_PTR`, while `cbWndExtra` uses `LONG_PTR`.</p><p>To access this space, use `GetWindowLongPtr` and `SetWindowLongPtr`:</p><pre>WINUSERAPI<br>LONG_PTR<br>WINAPI<br>GetWindowLongPtrA(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex);<br>    <br>WINUSERAPI<br>LONG_PTR<br>WINAPI<br>GetWindowLongPtrW(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex);<br>    <br>#ifdef UNICODE<br>#define GetWindowLongPtr  GetWindowLongPtrW<br>#else<br>#define GetWindowLongPtr  GetWindowLongPtrA<br>#endif // !UNICODE<br><br><br>WINUSERAPI<br>LONG_PTR<br>WINAPI<br>SetWindowLongPtrA(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex,<br>    _In_ LONG_PTR dwNewLong);<br>    <br>WINUSERAPI<br>LONG_PTR<br>WINAPI<br>SetWindowLongPtrW(<br>    _In_ HWND hWnd,<br>    _In_ int nIndex,<br>    _In_ LONG_PTR dwNewLong);<br>    <br>#ifdef UNICODE<br>#define SetWindowLongPtr  SetWindowLongPtrW<br>#else<br>#define SetWindowLongPtr  SetWindowLongPtrA<br>#endif // !UNICODE</pre><p>`GetWindowLongPtr` accepts the same parameters as `GetClassLongPtr`.<br>Its return type is `LONG_PTR`, which is simply a `typedef` of `__int64`.</p><p>`SetWindowLongPtr` accepts the parameters: `HWND`, the index of the location to access, and the `LONG_PTR` value to set.</p><p>Its return type is `LONG_PTR`, and the following values ​​are returned:</p><p>- If no value was previously set, 0 is returned.<br>- If a previously set value was found, that value is returned.<br>- If the access attempt fails, 0 is returned. To obtain related error information, call `GetLastError`.</p><p>An example usage example is as follows:</p><pre>wndclass.cbWndExtra = sizeof(LONG_PTR) * 2;<br><br>SetWindowLongPtr(hWnd, 0, 501);<br>SetWindowLongPtr(hWnd2, 0, 601);<br>SetWindowLongPtr(hWnd, sizeof(LONG_PTR), 502);<br>SetWindowLongPtr(hWnd2, sizeof(LONG_PTR), 602);<br><br>LONG_PTR v1 = GetWindowLongPtr(hWnd, 0); // v1 == 501<br>LONG_PTR v2 = GetWindowLongPtr(hWnd2, 0); // v2 == 601<br>LONG_PTR v3 = GetWindowLongPtr(hWnd, sizeof(LONG_PTR)); // v3 == 502<br>LONG_PTR v4 = GetWindowLongPtr(hWnd2, sizeof(LONG_PTR)); // v4 == 602</pre><p>If you want to use GetLastError to check the success of each SetWindowLongPtr call, you can do this:</p><pre>DWORD error = 0;<br>TCHAR* buffer = nullptr;<br><br>SetLastError(0);<br>SetWindowLongPtr(hWnd, 0, 501);<br>if (error = GetLastError() != 0)<br>{<br> FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,<br>  nullptr,<br>  example_error,<br>  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),<br>  buffer,<br>  0,<br>  nullptr);<br>  <br>  MessageBox(0, buffer, 0, 0);<br>}<br>LocalFree(buffer)</pre><p>`SetClassLongPtr` can be used in a similar manner.</p><p>If you’d like to learn more about `GetLastError`, `SetLastError`, `FormatMessage`, and system error codes, please refer to the following resources:</p><ul><li><a href="https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror">GetLastError function (errhandlingapi.h) - Win32 apps</a></li><li><a href="https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-setlasterror">SetLastError function (errhandlingapi.h) - Win32 apps</a></li><li><a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessage">FormatMessage function (winbase.h) - Win32 apps</a></li><li><a href="https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes?redirectedfrom=MSDN">Tutorial - Debug system error codes - Win32 apps</a></li></ul><h4>HINSTANCE hInstance</h4><p>Points to an instance handle containing the window procedure for the given `WNDCLASS` instance.</p><p>In many cases, you can simply pass the `hInstance` parameter of `WinMain`.</p><h4>HICON hIcon</h4><p>`hIcon` is used to store the icon displayed in the upper-left corner of a window.</p><p>`HICON` is defined as follows:</p><pre>DECLARE_HANDLE(HICON);</pre><p>That is, it is defined through the DECLARE_HANDLE macro, like the previous HINSTANCE, and its extension is as follows:</p><pre>struct HICON__ {<br>    int unused;<br>}; typedef struct HICON__* HICON</pre><p>Typically, hIcon is specified via the LoadIcon macro as follows:</p><pre>wndclass.hIcon = LoadIcon(hInstance, IDI_APPLICATION);</pre><p>At this time, LoadIcon is defined as follows:</p><pre>WINUSERAPI<br>HICON<br>WINAPI<br>LoadIconA(<br>    _In_opt_ HINSTANCE hInstance,<br>    _In_ LPCSTR lpIconName);<br>    <br>WINUSERAPI<br>HICON<br>WINAPI<br>LoadIconW(<br>    _In_opt_ HINSTANCE hInstance,<br>    _In_ LPCWSTR lpIconName);<br>    <br>#ifdef UNICODE<br>#define LoadIcon  LoadIconW<br>#else<br>#define LoadIcon  LoadIconA<br>#endif // !UNICODE</pre><p>That is, you pass a handle to the window where you want to display the icon (`HINSTANCE`) and a string representing the target icon, `lpIconName`.</p><p>In the example above, `IDI_APPLICATION` was passed. A similar built-in icon is as follows:</p><pre>#ifndef NOICONS<br><br>/*<br> * Standard Icon IDs<br> */<br>#ifdef RC_INVOKED<br>#define IDI_APPLICATION     32512<br>#define IDI_HAND            32513<br>#define IDI_QUESTION        32514<br>#define IDI_EXCLAMATION     32515<br>#define IDI_ASTERISK        32516<br>#if(WINVER &gt;= 0x0400)<br>#define IDI_WINLOGO         32517<br>#endif /* WINVER &gt;= 0x0400 */<br>#if(WINVER &gt;= 0x0600)<br>#define IDI_SHIELD          32518<br>#endif /* WINVER &gt;= 0x0600 */<br>#else<br>#define IDI_APPLICATION     MAKEINTRESOURCE(32512)<br>#define IDI_HAND            MAKEINTRESOURCE(32513)<br>#define IDI_QUESTION        MAKEINTRESOURCE(32514)<br>#define IDI_EXCLAMATION     MAKEINTRESOURCE(32515)<br>#define IDI_ASTERISK        MAKEINTRESOURCE(32516)<br>#if(WINVER &gt;= 0x0400)<br>#define IDI_WINLOGO         MAKEINTRESOURCE(32517)<br>#endif /* WINVER &gt;= 0x0400 */<br>#if(WINVER &gt;= 0x0600)<br>#define IDI_SHIELD          MAKEINTRESOURCE(32518)<br>#endif /* WINVER &gt;= 0x0600 */<br>#endif /* RC_INVOKED */<br><br>#if(WINVER &gt;= 0x0400)<br>#define IDI_WARNING     IDI_EXCLAMATION<br>#define IDI_ERROR       IDI_HAND<br>#define IDI_INFORMATION IDI_ASTERISK<br>#endif /* WINVER &gt;= 0x0400 */<br><br><br>#endif /* !NOICONS */<br><br>...<br><br>#define IS_INTRESOURCE(_r) ((((ULONG_PTR)(_r)) &gt;&gt; 16) == 0)<br>#define MAKEINTRESOURCEA(i) ((LPSTR)((ULONG_PTR)((WORD)(i))))<br>#define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i))))<br>#ifdef UNICODE<br>#define MAKEINTRESOURCE  MAKEINTRESOURCEW<br>#else<br>#define MAKEINTRESOURCE  MAKEINTRESOURCEA<br>#endif // !UNICODE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*JdfxwiMTtRUdFMfkPW5Uqg.png" /></figure><p>For more detailed information, please refer to the following resources:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/menurc/about-icons">About Icons - Win32 apps</a></p><h4>HCURSOR hCursor</h4><p>`hCursor` specifies the cursor icon to display when the cursor enters the window area.</p><p>`HCURSOR` is defined as follows:</p><pre>#ifndef _MAC<br>typedef HICON HCURSOR;      /* HICONs &amp; HCURSORs are polymorphic */<br>#else<br>DECLARE_HANDLE(HCURSOR);    /* HICONs &amp; HCURSORs are not polymorphic */<br>#endif</pre><p>When initializing the hCursor of an actual WNDCLASS instance, you use the LoadCursor macro as follows:</p><pre>wndclass.hCursor = LoadCursor(hInstance, IDC_ARROW);</pre><p>At this time, LoadCursor is defined as follows:</p><pre>WINUSERAPI<br>HCURSOR<br>WINAPI<br>LoadCursorA(<br>    _In_opt_ HINSTANCE hInstance,<br>    _In_ LPCSTR lpCursorName);<br>    <br>WINUSERAPI<br>HCURSOR<br>WINAPI<br>LoadCursorW(<br>    _In_opt_ HINSTANCE hInstance,<br>    _In_ LPCWSTR lpCursorName);<br>    <br>#ifdef UNICODE<br>#define LoadCursor  LoadCursorW<br>#else<br>#define LoadCursor  LoadCursorA<br>#endif // !UNICODE</pre><p>As with `LoadIcon`, the `HINSTANCE` parameter of `LoadCursor` passes the handle of the window associated with the cursor settings and the name of the cursor to use.</p><p>The example above uses `IDC_ARROW`, but similar built-in cursors include:</p><pre>/*<br> * Standard Cursor IDs<br> */<br>#define IDC_ARROW           MAKEINTRESOURCE(32512)<br>#define IDC_IBEAM           MAKEINTRESOURCE(32513)<br>#define IDC_WAIT            MAKEINTRESOURCE(32514)<br>#define IDC_CROSS           MAKEINTRESOURCE(32515)<br>#define IDC_UPARROW         MAKEINTRESOURCE(32516)<br>#define IDC_SIZE            MAKEINTRESOURCE(32640)  /* OBSOLETE: use IDC_SIZEALL */<br>#define IDC_ICON            MAKEINTRESOURCE(32641)  /* OBSOLETE: use IDC_ARROW */<br>#define IDC_SIZENWSE        MAKEINTRESOURCE(32642)<br>#define IDC_SIZENESW        MAKEINTRESOURCE(32643)<br>#define IDC_SIZEWE          MAKEINTRESOURCE(32644)<br>#define IDC_SIZENS          MAKEINTRESOURCE(32645)<br>#define IDC_SIZEALL         MAKEINTRESOURCE(32646)<br>#define IDC_NO              MAKEINTRESOURCE(32648) /*not in win3.1 */<br>#if(WINVER &gt;= 0x0500)<br>#define IDC_HAND            MAKEINTRESOURCE(32649)<br>#endif /* WINVER &gt;= 0x0500 */<br>#define IDC_APPSTARTING     MAKEINTRESOURCE(32650) /*not in win3.1 */<br>#if(WINVER &gt;= 0x0400)<br>#define IDC_HELP            MAKEINTRESOURCE(32651)<br>#endif /* WINVER &gt;= 0x0400 */<br><br>#if(WINVER &gt;= 0x0606)<br>#define IDC_PIN            MAKEINTRESOURCE(32671)<br>#define IDC_PERSON         MAKEINTRESOURCE(32672)<br>#endif /* WINVER &gt;= 0x0606 */</pre><p>For more detailed information, please refer to the following resources:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors">About Cursors - Win32 apps</a></p><h4>HBRUSH hbrBackground</h4><p>`hbrBackground` specifies the brush to use when painting the background, and its type is `HBRUSH`.</p><p>`HBRUSH` is defined as follows:</p><pre>DECLARE_HANDLE(HBRUSH);</pre><p>This soon expands to:</p><pre>struct HBRUSH__ {<br>    int unused;<br>}; typedef struct HBRUSH__* HBRUSH</pre><p>In other words, `HBRUSH`, like `HINSTANCE` or `HICON`, internally holds only a single integer.</p><p>In the example above, `HBRUSH` is retrieved as follows:</p><pre>wndclass.hbrBackground = static_cast&lt;HBRUSH&gt;(GetStockObject(WHITE_BRUSH));</pre><p>GetStockObject is used to retrieve one of the previously reserved resources. The stock types are as follows:</p><pre>/* Stock Logical Objects */<br>#define WHITE_BRUSH         0<br>#define LTGRAY_BRUSH        1<br>#define GRAY_BRUSH          2<br>#define DKGRAY_BRUSH        3<br>#define BLACK_BRUSH         4<br>#define NULL_BRUSH          5<br>#define HOLLOW_BRUSH        NULL_BRUSH<br>#define WHITE_PEN           6<br>#define BLACK_PEN           7<br>#define NULL_PEN            8<br>#define OEM_FIXED_FONT      10<br>#define ANSI_FIXED_FONT     11<br>#define ANSI_VAR_FONT       12<br>#define SYSTEM_FONT         13<br>#define DEVICE_DEFAULT_FONT 14<br>#define DEFAULT_PALETTE     15<br>#define SYSTEM_FIXED_FONT   16<br><br>#if(WINVER &gt;= 0x0400)<br>#define DEFAULT_GUI_FONT    17<br>#endif /* WINVER &gt;= 0x0400 */</pre><p>If you want to learn more about stocks, see the following resources:</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getstockobject">GetStockObject function (wingdi.h) - Win32 apps</a></p><h4>LPCSTR lpszMenuName or LPCWSTR lpszMenuName</h4><p>lpszMenuName is used when creating a menu bar at the top of the window, but since it is not generally used in applications that utilize DirectX, we will leave it as 0 and skip it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*M6vyoXYvcdy9r9XR7jf7tw.png" /></figure><h4>LPCSTR lpszClassName or LPCWSTR lpszClassName</h4><p>`lpszClassName` specifies the name of the window to be created using the `WNDCLASS` instance.</p><p>Later, when creating a window using `CreateWindow`, the `lpszClassName` string is compared to the original, so care must be taken to avoid typos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32932dd7675d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/create-basic-windows-native-application-with-win32-api-1-wndclass-32932dd7675d">Create basic windows native application with Win32 API — 1. WNDCLASS</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create basic windows native application with Win32 API — 0. WinMain & wWinMain]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/create-basic-windows-native-application-with-win32-api-0-winmain-wwinmain-15bf31259695?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/15bf31259695</guid>
            <category><![CDATA[winapi]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[directx-12]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 05:21:45 GMT</pubDate>
            <atom:updated>2026-04-29T05:21:46.935Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create basic windows native application with Win32 API — 0. WinMain &amp; wWinMain</h3><h3>Introduction.</h3><p>There are various options for building a rendering pipeline that operates in a Windows environment. One such option is based on the Win32 API.</p><p>While we will now build a rendering pipeline directly using low-level graphics APIs, from DirectX to Vulkan, and implement various techniques, we will first examine how to implement an application using the Win32 API as a foundation.</p><h3>Full Source Code.</h3><p>First, here’s the full source code:</p><pre>#include &lt;Windows.h&gt;<br><br><br>LRESULT CALLBACK WndMsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);<br>int Run();<br><br>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevIntance, PSTR pCmdLine, int nShowCmd)<br>{<br>    WNDCLASS wndclass;<br>    wndclass.style = CS_HREDRAW | CS_VREDRAW;<br>    wndclass.hInstance = hInstance;<br>    wndclass.lpfnWndProc = WndMsgProc;<br>    wndclass.cbClsExtra = 0;<br>    wndclass.cbWndExtra = 0;<br>    wndclass.lpszClassName = L&quot;WinAppTest&quot;;<br>    wndclass.hCursor = LoadCursor(hInstance, IDC_ARROW);<br>    wndclass.hIcon = LoadIcon(hInstance, IDI_APPLICATION);<br>    wndclass.hbrBackground = static_cast&lt;HBRUSH&gt;(GetStockObject(WHITE_BRUSH));<br>    wndclass.lpszMenuName = 0;<br><br>    if (!RegisterClass(&amp;wndclass))<br>    {<br>        MessageBox(0, L&quot;Fail to Registering Class&quot;, 0, 0);<br>        return 0;<br>    }<br><br>    HWND hwnd = CreateWindow(L&quot;WinAppTest&quot;, L&quot;Test&quot;, WS_OVERLAPPEDWINDOW, 0, 0, 500, 300, 0, 0, hInstance, 0);<br>    if (hwnd == 0)<br>    {<br>        MessageBox(0, L&quot;Fail to Creating Window&quot;, 0, 0);<br>        return 0;<br>    }<br><br>    ShowWindow(hwnd, nShowCmd);<br>    UpdateWindow(hwnd);<br><br>    return Run();<br>}<br><br>LRESULT CALLBACK WndMsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)<br>{<br>    return DefWindowProc(hwnd, msg, wParam, lParam);<br>}<br>int Run()<br>{<br>    MSG msg{ 0 };<br><br>    BOOL bRet = 1;<br>    while (bRet = GetMessage(&amp;msg, 0, 0, 0) != 0)<br>    {<br>        if (bRet == -1)<br>        {<br>            MessageBox(0, L&quot;Win Quit&quot;, 0, 0);<br>            break;<br>        }<br>        else<br>        {<br>            TranslateMessage(&amp;msg);<br>            DispatchMessage(&amp;msg);<br>        }<br>    }<br><br>    return (int)msg.wParam;<br>}</pre><h3>Windows.h.</h3><p>To use the Win32 API, you must first include `Windows.h`.</p><p>`Windows.h` contains the basic elements for using the Win32 API. It is also required to specify program entry points specific to the Win32 API, such as `WinMain` and `wWinMain`, that go beyond the various standard C++ functions.</p><h3>WinMain or wWinMain.</h3><p>As mentioned earlier, programs built using the `Win32 API` enter the program through `WinMain` or `wWinMain`, rather than through the `main` function as defined by the C++ standard.</p><p>The signatures of `WinMain` and `wWinMain` are defined as follows:</p><pre>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nCmdShow);<br>int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow);</pre><h4>WINAPI</h4><p>In MSDN, WINAPI is defined as follows:</p><blockquote><em>The calling convention for system functions.</em></blockquote><blockquote><em>This type is declared in WinDef.h as follows:</em></blockquote><blockquote><em>#define WINAPI __stdcall</em></blockquote><blockquote><strong><em>CALLBACK</em></strong><em>, </em><strong><em>WINAPI</em></strong><em>, and </em><strong><em>APIENTRY</em></strong><em> are all used to define functions with the __stdcall calling convention. Most functions in the Windows API are declared using </em><strong><em>WINAPI</em></strong><em>. You may wish to use </em><strong><em>CALLBACK</em></strong><em> for the callback functions that you implement to help identify the function as a callback function.</em></blockquote><p>As explained above, WINAPI is defined as follows:</p><pre>#define WINAPI __stdcall</pre><p>In other words, `WINAPI` is an alias for `__stdcall`.</p><p>`__stdcall` specifies the parameter initialization order for functions with the keyword and defines the calling convention at compile time.</p><p>The C++ standard itself does not specify the initialization order for functions with two or more parameters. Therefore, each compiler manufacturer determines the order. Microsoft’s Visual C++ defines this order using keywords like `__stdcall`.</p><p>Internally, `__stdcall` initializes function parameters in the same way as `__cdecl`, with the only significant difference being the calling convention.</p><p>Additionally, when building a system using the `Win32 API`, not all functions are marked with keywords like `WINAPI`, `__stdcall`, or `__cdecl`, but compilation is still successful. This is because the compiler automatically adds `__stdcall` or `__cdecl`.</p><p>For more information, please refer to the following resources:</p><ul><li><a href="https://learn.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-170">__stdcall</a></li><li><a href="https://learn.microsoft.com/en-us/cpp/cpp/cdecl?view=msvc-170">__cdecl</a></li></ul><h4>HINSTANCE hInstance</h4><p>`hinstance` contains a handle to the current program.</p><p>`HINSTANCE` itself is defined as follows:</p><pre>DECLARE_HANDLE(HINSTANCE);</pre><p>Additionally, the definition of HINSTANCE is extended by the DECLARE_HANDLE macro, and DECLARE_HANDLE is defined as follows:</p><pre>#define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name</pre><p>The form of the HINSTANCE that is actually defined through this extension is as follows:</p><pre>struct HINSTANCE__ {<br>    int unused;<br>}; typedef struct HINSTANCE__* HINSTANCE</pre><p>Essentially, `HINSTANCE` is a pointer to an `HINSTANCE__` object, which contains only a single integer member variable. Windows uses this integer value to identify the process.</p><p>However, the `HINSTANCE` type itself is defined as follows on MSDN:</p><blockquote><em>A handle to an instance. This is the base address of the module in memory.</em></blockquote><blockquote><strong><em>HMODULE</em></strong><em> and </em><strong><em>HINSTANCE</em></strong><em> are the same today, but represented different things in 16-bit Windows.</em></blockquote><blockquote><em>This type is declared in </em><em>WinDef.h as follows:</em></blockquote><blockquote><em>typedef HANDLE HINSTANCE;</em></blockquote><p>In fact, if you look at the contents of WinDef.h or minwindef.h, you can see that it is defined as follows:</p><pre>typedef HINSTANCE HMODULE;      /* HMODULEs can be used in place of HINSTANCEs */</pre><p>That is, as MSDN says, unless you are building for a 16-bit environment target, there is no major problem in thinking of HINSTANCE as equivalent to HMODULE.</p><h4>HINSTANCE hPrevInstance</h4><p>hPrevInstance is a parameter that was used in 16-bit Windows, but is now obsolete. It is always initialized to 0 on non-16-bit Windows.</p><h4>PSTR lpCmdLine or PWSTR pCmdLine</h4><p>The difference between `WInMain` and `wWinMain` is whether the command-line argument parameter is an ANSI string or a Unicode string.</p><p>This is the only difference in the signatures of `WInMain` and `wWInMain`. `PSTR` and `PWSTR` are defined as follows:</p><pre>typedef _Null_terminated_ CHAR *NPSTR, *LPSTR, *PSTR;<br>typedef _Null_terminated_ PSTR *PZPSTR;<br>typedef _Null_terminated_ CONST PSTR *PCZPSTR;<br><br>typedef _Null_terminated_ WCHAR *NWPSTR, *LPWSTR, *PWSTR;<br>typedef _Null_terminated_ PWSTR *PZPWSTR;<br>typedef _Null_terminated_ CONST PWSTR *PCZPWSTR;</pre><p>Therefore, `PSTR` and `PWSTR` are pointers to `CHAR` and `WCHAR`, respectively, and can therefore be considered traditional C-style strings.</p><p>`CHAR` and `WCHAR` are defined as follows:</p><pre>typedef char CHAR;<br>typedef wchar_t WCHAR;</pre><p>_Null_terminated_ specifies that the string must end with a null, i.e., ‘\0’.</p><h4>int nCmdShow</h4><p>nCmdShow contains commands that specify how the program should be displayed, the complete list of which is as follows:</p><pre>/*<br> * ShowWindow() Commands<br> */<br>#define SW_HIDE             0<br>#define SW_SHOWNORMAL       1<br>#define SW_NORMAL           1<br>#define SW_SHOWMINIMIZED    2<br>#define SW_SHOWMAXIMIZED    3<br>#define SW_MAXIMIZE         3<br>#define SW_SHOWNOACTIVATE   4<br>#define SW_SHOW             5<br>#define SW_MINIMIZE         6<br>#define SW_SHOWMINNOACTIVE  7<br>#define SW_SHOWNA           8<br>#define SW_RESTORE          9<br>#define SW_SHOWDEFAULT      10<br>#define SW_FORCEMINIMIZE    11<br>#define SW_MAX              11<br><br><br>/*<br> * Old ShowWindow() Commands<br> */<br>#define HIDE_WINDOW         0<br>#define SHOW_OPENWINDOW     1<br>#define SHOW_ICONWINDOW     2<br>#define SHOW_FULLSCREEN     3<br>#define SHOW_OPENNOACTIVATE 4</pre><p>The path through which the value of `nCmdShow` is determined is as follows:</p><ol><li>Program execution request: The Windows user requests the OS to execute the program.</li><li>`STARTUPINFO` creation: `STARTUPINFO` is created.</li><li>`CreateProcess` execution: The OS creates a process for the program using `CreateProcess`.</li><li>Passing `nCmdShow` to `WinMain` or `wWinMain`: `WinMain` receives `nCmdShow` as `SW_SHOWDEFAULT`.</li><li>`nCmdShow` is then passed to `ShowWindow`: Since `SW_SHOWDEFAULT` is used, the `wShowWindow` member variable of `STARTUPINFO`, created for `CreateProcess`, is used.</li></ol><p>To understand the above process more intuitively, it would be helpful to look at the following example code, which is closer to the OS’s perspective:</p><pre>// From https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa<br><br>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;tchar.h&gt;<br><br>void _tmain( int argc, TCHAR *argv[] )<br>{<br>    STARTUPINFO si;<br>    PROCESS_INFORMATION pi;<br><br>    ZeroMemory( &amp;si, sizeof(si) );<br>    si.cb = sizeof(si);<br>    ZeroMemory( &amp;pi, sizeof(pi) );<br><br>    if( argc != 2 )<br>    {<br>        printf(&quot;Usage: %s [cmdline]\n&quot;, argv[0]);<br>        return;<br>    }<br><br>    // Start the child process. <br>    if( !CreateProcess( NULL,   // No module name (use command line)<br>        argv[1],        // Command line<br>        NULL,           // Process handle not inheritable<br>        NULL,           // Thread handle not inheritable<br>        FALSE,          // Set handle inheritance to FALSE<br>        0,              // No creation flags<br>        NULL,           // Use parent&#39;s environment block<br>        NULL,           // Use parent&#39;s starting directory <br>        &amp;si,            // Pointer to STARTUPINFO structure<br>        &amp;pi )           // Pointer to PROCESS_INFORMATION structure<br>    ) <br>    {<br>        printf( &quot;CreateProcess failed (%d).\n&quot;, GetLastError() );<br>        return;<br>    }<br><br>    // Wait until child process exits.<br>    WaitForSingleObject( pi.hProcess, INFINITE );<br><br>    // Close process and thread handles. <br>    CloseHandle( pi.hProcess );<br>    CloseHandle( pi.hThread );<br>}</pre><p>For example, let’s say we want to run a program, `A.exe`, via `PowerShell.exe` on Windows.</p><p>First, PowerShell, as the parent process, will create `STARTUPINFO` using the code above and call `CreateProcess`.</p><p>At this point, it will also populate internal members of `STARTUPINFO`, specifically `wShowWindow`. The exact display command value in `wShowWindow` will depend on the path through which `A.exe` is executed (`SW_SHOWMINIMIZED` for minimal execution, `SW_NORMAL` for normal execution).</p><p>Then, `CreateProcess` will create a child process corresponding to `A.exe` and provide parameters to an entry point function, such as `WinMain`.</p><p>At this point, `nCmdShow` will typically be `SW_SHOWDEFAULT`.</p><p>When calling `ShowWindow` within `WinMain`, `nCmdShow` is typically passed, or `SW_SHOWDEFAULT` here.</p><p>In such cases, the window is created based on the value set in `wShowWindow` of `STARTUPINFO` passed by the parent process to `CreateProcess`.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bf31259695" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/create-basic-windows-native-application-with-win32-api-0-winmain-wwinmain-15bf31259695">Create basic windows native application with Win32 API — 0. WinMain &amp; wWinMain</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BRDF PBR — 2. Disney Model]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/brdf-pbr-2-disney-model-9a300ad16c3d?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a300ad16c3d</guid>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[brdf]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 05:21:17 GMT</pubDate>
            <atom:updated>2026-04-29T05:21:19.055Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>BRDF Explorer</strong></h3><p>Various model combinations exist within BRDF.</p><p>For example, the representative Oren-Nayer model utilizes a combination of the Gaussian NDF and the V-cavity Geometry Function. However, since the Oren-Nayer model aims to calculate only diffuse based purely on the geometric shape of the surface, it is widely used in combination with the Schlick Fresnel Function.</p><p>However, the Disney model, which is used universally today, differs in its design concept. Based on results obtained from analyzing the MERL Database, it was discovered that even the Fresnel Function, previously used to calculate specularity, had the potential to contain diffuse. Consequently, the Fresnel Function was split into two versions — specular and diffuse — and the roles of the NDF and Geometry Function differed slightly from their traditional applications.</p><p>Thus, only these two models differ in their design philosophy, and they differ in which functions are used for each term and how they are utilized. For this reason, it would take a considerable amount of time to investigate and directly implement all historically widely used BRDF models to analyze the interaction between light and materials and to select a model suitable for this major research. This is not realistic in the environment of major research, where results must be produced within one year.</p><p>The tool called BRDF Explorer shown in Figure 1, introduced in “<a href="https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf">Physically Based Shading at Disney</a>” contributed by Brent Burley of Walt Disney Animation Studios to SIGGRAPH 2012, was expected to be very useful in such situations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zQOxlwjJaiXfBH2cu2o8A.png" /><figcaption>[Figure 1] Disney BRDF Explorer</figcaption></figure><p>BRDF Explorer was an in-house tool used by Disney to analyze models created based on the MERL BRDF Database when they were researching BRDF PBR as a new lighting model for the production of their latest film, *Rapunzel*.</p><p>However, upon investigation, it was found that the <a href="https://github.com/wdas/brdf">original repository</a> currently on GitHub is configured for Unix, making it difficult to build easily on Windows. Consequently, after searching separately, I discovered a service where a developer named Patapom (Figure 2) had migrated BRDF Explorer to a web version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJJOPN34k-UiYXL9cL00tQ.png" /><figcaption>[Figure 2] <a href="https://patapom.com/topics/WebGL/BRDF/">Patapom’s BRDF Explorer</a></figcaption></figure><p>The main functions of Patapom’s BRDF Explorer (hereinafter referred to as BRDF Explorer) are as shown in Table 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1Sbp3AUinRtHpnVTCOF6Q.png" /><figcaption>&lt;Table 1&gt; Key Features of BRDF Explorer</figcaption></figure><p>One of the drawbacks of BRDF Explorer is that it does not properly support Disney models. Previously, for some reason, it applied an Ad-hoc model created by Patapom instead of a Disney model. To properly analyze Disney models, it was modified to force the application of Disney models by overriding the file list shown in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgNlzFIfc2nVVLLzzZobVw.png" /><figcaption>[Figure 3] List of BRDF Explorer Override files for applying the Disney model</figcaption></figure><p>The overridden files can be installed from the following:</p><ul><li><a href="https://drive.google.com/file/d/1vXjLah4j30mBz3sA80FSzov1JIsdTRJP/view?usp=sharing">https://drive.google.com/file/d/1vXjLah4j30mBz3sA80FSzov1JIsdTRJP/view?usp=sharing</a></li></ul><h4><strong>Image Slice</strong></h4><p>Image Slice is a good tool for visually checking whether a model has Specular Peak, Fresnel Peak, Diffuse Color, and Grazing Retro-Reflection characteristics. Image Slice can be seen in detail in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6Nok3f_ZR9bpzRGSxq9Cw.png" /><figcaption>[Figure 4] Image Slice</figcaption></figure><p>To view an image slice, you must understand the concepts of half angle (Theta h) and difference angle (Theta d).</p><ul><li>Theta h represents the angle between the Normal Vector and the Half Vector. In other words, the closer the value is to 0, the smoother the surface; the closer it is to 90, the rougher the surface.</li><li>Theta d represents the angle between the Light Incident Vector and the Half Vector. In other words, the closer the value is to 0, the more the light strikes head-on; the closer it is to 90, the more it grazes the surface.</li></ul><p>Specular Peak is a phenomenon in which light strikes a smooth surface and bounces off sharply in one direction like a mirror. This creates strong and distinct highlights (bright spots). Specular Peak appears at points where Thera h is close to 0, which corresponds to the situation where (n=h).</p><p>The Fresnel Peak is a shape in which reflectance increases rapidly to nearly 100% at the Grazing Angle, where light passes just grazes the surface.</p><p>Diffuse is diffuse reflection and the basic color of the surface; it assumes the phenomenon where light penetrates into the interior of an object, scatters, and then exits. Therefore, Diffuse refers to a broad and even distribution of reflectance observed at ordinary angles rather than extreme angles.</p><p>Grazing Retro-Reflection is a phenomenon in which, although Fresnel Peaks should generally occur in the direction of specular reflection, light instead returns in the direction of the Light Incident when the surface is rough. A Thera d close to 0 degrees means that the camera and the light are in nearly the same position, and a Theta h close to 90 degrees means that the camera is looking toward the edge of the object.</p><p>At first glance, the condition that Theta h is close to 90 degrees seems to assume a situation that cannot exist, but it becomes easier to understand if interpreted in detail.</p><p>The fact that Theta h is close to 90 means that n and h are close to a right angle. In this case, h is a vector representing the midpoint between l and v. In other words, this situation can be said to assume a situation where the inner product of l and v is close to 1. This is because if the inner product of the two were close to -1 (usually assuming a normalized state for l and v), the magnitude of h would ultimately become 0.</p><p>Since the surface assumed by BRDF PBR is a microfacet, it is possible for m on the microfacet to face in a completely different direction from n. If light interacts with m, in some cases, as shown in Figure 5, there may be a situation where light reflected from the surface returns to the light source, and this is a situation where the inner product of l and v approaches 1.</p><p>The NDF determines how much light the ms on the surface reflect at a specific angle, and this is assumed to be h. This is why the NDF ultimately represents the surface roughness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsPEDiZgPcmL78CtDysclg.png" /><figcaption>[Figure 5] Retro-Reflection</figcaption></figure><p>Considering the points mentioned above, we can easily predict what surface characteristics a material will exhibit under certain conditions simply by looking at its image slice.</p><h4><strong>MERL BRDF Database</strong></h4><p>The MERL BRDF Database is a dataset analyzing the surface properties of 100 real-world materials, published in 2003 by researchers including Matthew Brand of Mitsubishi Electric Research Laboratories in conjunction with “<a href="https://www.merl.com/publications/docs/TR2003-83.pdf">A Data-Driven Reflectance Model.</a>” Figure 6 shows image slices of the data included in the MERL Database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpBX6z7D989AzFT0ue43LA.png" /><figcaption>[Figure 6] Image Slice Set of MERL BRDF Database</figcaption></figure><p>The MERL BRDF Database is a widely cited resource across the field of computer graphics and has been referenced in the following representative works:</p><ul><li>“Physically Based Shading at Disney”, SIGGRAPH 2012</li><li>“Background: Physics and Math of Shading”, SIGGRAPH 2013</li><li>“Moving Frostbite to Physically Based Rendering 3.0”, SIGGRAPH 2014</li><li>Pearl Abyss, “3D Rendering in Black Desert Online”, IGC 2017</li></ul><h3><strong>BRDF Models</strong></h3><p>The BRDF model refers to which combination of function types will be applied to F(l, h), G(l, v, h), and D(h) of the BRDF PBR formula in Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgvksYYUCqy0QHvals3hlA.png" /><figcaption>[Figure 7] BRDF PBR Formula</figcaption></figure><h4><strong>Lambert Blinn-Phong</strong></h4><p>Lambert and Blinn-Phong are traditional shading techniques that were introduced before the concept of PBR began to emerge in earnest. Therefore, they generally do not follow the BRDF PBR of Figure 7.</p><p>This is because Lambert and Blinn-Phong are structurally very simple models that consider only l, n, and r.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*IBQv2i0dcBuHYvDgqOlgTA.png" /><figcaption>[Figure 8] Lambert Shading</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*CAfvLwCeb8Zu4bDSysmsvg.png" /><figcaption>[Figure 9] Blinn-Phong Shading</figcaption></figure><p>Lambert in Figure 8 calculates the degree of light diffusion by applying a cosine to l and n.</p><p>Blinn-Phong in Figure 9 is slightly more complex; first, r is calculated for n in relation to l. Then, a cosine is applied to v and r, and the degree of light specularity is calculated by raising the values ​​to an appropriate power to obtain sharper highlights.</p><p>However, when applying this to BRDF PBR, the sum of the Lambert function corresponding to Diffuse and the Blinn-Phong function corresponding to Specular is used as F(l, h).</p><p>This can be summarized into a formula as shown in Figure 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ni5dozjkXqOpkTH6c-ZRkA.png" /><figcaption>[Figure 10] Lambert-Blinn-Phong model formula</figcaption></figure><p>When checking the Lambert Blinn-Phong model in BRDF Explorer, it is as shown in Figure 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYx71LUR5ZISDMTJwAdCSw.png" /><figcaption>[Figure 11] Lambert-Blinn-Phong model verified in BRDF Explorer</figcaption></figure><h4><strong>Oren-Nayar Blinn-Phong</strong></h4><p>In “Moving Frostbite to Physically Based Rendering 3.0,” it is stated that Oren-Nayar, which handles Diffuse, is generally used together with Schlick, which handles Specular, but due to the limitations of the features provided by BRDF Explorer, it is analyzed in combination with Blinn-Phong.</p><p>The Oren-Nayar formula is as shown in Figure 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5f4mJO8KSz2XJg6R6MfoQw.png" /><figcaption>[Figure 12] <a href="https://en.wikipedia.org/wiki/Oren%E2%80%93Nayar_reflectance_model">Oren-Nayar Shading</a></figcaption></figure><p>As can be seen from the formula, Oren-Nayar takes into account surface roughness unlike Lambert, and as shown in Figure 13, the brightness of the reflected light according to the angle is more similar to reality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*HFz77xahtEQD16tlq7IHEQ.png" /><figcaption>[Figure 13] Comparison of Lambert and Oren-Nayar</figcaption></figure><p>The reason why Oren-Nayar is more suitable for PBR can be understood in more detail by looking at the BRDF Explorer screen in Figure 14.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*196ec1Jrst88_-fSSGLepw.png" /><figcaption>[Figure 14] Oren-Nayar Blinn-Phong model verified in BRDF Explorer</figcaption></figure><p>Looking at the Image Slice in Figure 14, you can see that Grazing Retro-Reflection occurs in the bottom right corner. Of course, it is not as realistic as the Grazing Retro-Reflection of the actual object in Figure 6, but it can be considered an improved result compared to Lambert in Figure 11, where it did not appear at all.</p><h4><strong>Disney</strong></h4><p>The Disney model was designed under the following principles:</p><ul><li>It focuses on intuitive parameter configuration rather than strictly adhering to physical principles.</li><li>It should consist of as few parameters as possible.</li><li>Each parameter should be configured within the range of 0 to 1.</li><li>However, if it makes sense, each parameter must allow values ​​outside this range.</li><li>All parameter combinations must guarantee a reasonable possible result.</li></ul><p>The parameter configuration provided by the Disney model in principle is shown in Table 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*7pVf2YXuv70aNKbwf87Xfw.png" /><figcaption>&lt;Table 2&gt; Parameter Configuration of the Disney Model (Names in parentheses correspond to parameter names in BRDF Explorer)</figcaption></figure><p>Figure 15 is a visualization of Table 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8MbZHnGqWWErL9X4h-nsg.png" /><figcaption>[Figure 15] Disney model parameter visualization data</figcaption></figure><p>Since BRDF Explorer is designed to test only the core parts of the Disney Model, it does not support all parameters in Table 2. The gray rows in Table 2 indicate the parameters supported by BRDF Explorer, and Figure 16 shows the parameter configuration of BRDF Explorer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*MbwSNW6lna5BLixjbDihMA.png" /><figcaption>[Figure 16] Disney model parameter configuration in BRDF Explorer</figcaption></figure><p>The combination of functions used in the Disney model is as shown in Table 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYcE7B0GSiCOBvEsck6p4A.png" /><figcaption>&lt;Table 3&gt; Function combinations of the Disney model</figcaption></figure><p>First, Disney Fresnel’s formula looks like Figure 17.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wErSm0t4_clhqdgSVS3Jqg.png" /><figcaption>[Figure 17] Disney Fresnel Shading</figcaption></figure><p>Generally, PBR aims to preserve energy conservation. In other words, it ensures that the amount of light reflected does not exceed the energy imparted by the light source.</p><p>However, Disney researchers discovered that traditional Lambert always resulted in dark edges on objects, and while Oren-Nayar was slightly better, it still lacked grazing retro-reflection compared to actual measurement data from the MERL BRDF Database.</p><p>Therefore, instead of strictly adhering to the laws of physics, Disney created an empirical model based on MERL’s observational data and the artist’s intuition, which is the function shown in Figure 15.</p><p>The key point is that the FD90 part determines the minimum/maximum reflectance achievable at the edges (90 degrees) of an object. This means that the Grazing Retro-Reflection value is amplified from 0.5 to 2.5 times depending on the roughness. This can be seen in Figure 17, where the Image Slice changes as the Roughness changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eu0zpRvlHOuNcNNEqQcLWA.png" /><figcaption>[Figure 17] Image Slices of the Disney Diffuse Function according to Roughness</figcaption></figure><p>The simulation of this in BRDF Explorer is shown in Figure 18.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRQ-87klo-ad27sRlcxCog.png" /><figcaption>[Figure 18] Disney model verified in BRDF Explorer</figcaption></figure><p>Looking at the Image Slice in Figure 18, it can be seen that it is closer to the Image Slice in Figure 6 (MERL BRDF Database) than to the Image Slices in Figure 11 (Lambert) or Figure 14 (Oren-Nayar). Even when looking at the Teapot rendering in the IBL environment shown in the upper right corner of Figure 18, one can see that the Grazing Retro-Reflection is clearly visible.</p><p>Of course, the Disney model also has its limitations.</p><p>For example, the Disney model cannot cover cases where the Reflection Lobe shape is skewed toward the Light Incident side due to the surface characteristics of the material. However, in the case of the alumina-exide in Figure 19, which is a metal with prominent sharp specular but exhibits a rough surface, the Disney model covers it well to some extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*0L14iiGyOG3abqVc7KuiTQ.png" /><figcaption>[Figure 19] Comparison of Reflection Lobes between Disney and alumina-exide</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*P22X8QptEuHp81Wds9aUfw.png" /><figcaption>[Figure 20] Comparison of Reflection Lobes of Disney and red-plastic</figcaption></figure><p>Figure 20 shows an example of red-plastic reproduced using Disney. Red-plastic is a non-conductive material with a moderately rough surface; therefore, retro-reflection (in this case, Fresnel peaks) occurs in the l-direction at relatively wide angles. Additionally, due to its roughness, weak grazing retro-reflection also appears.</p><p>However, while Disney can simulate this somewhat similarly at the image slice level, it is not possible at the accurate reflection lobe level. This is due to the inherent limitations of the Disney Fresnel Function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a300ad16c3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/brdf-pbr-2-disney-model-9a300ad16c3d">BRDF PBR — 2. Disney Model</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BRDF(Bidirectional Reflectance Distribution Function) PBR(Physically Based Rendering) — 1.]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/brdf-pbr-1-fresnel-function-077b3e50a751?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/077b3e50a751</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[brdf]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 02:26:24 GMT</pubDate>
            <atom:updated>2026-04-08T12:13:27.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>BRDF(Bidirectional Reflectance Distribution Function) PBR(Physically Based Rendering) — 1. Fresnel Function</h3><h3><strong>1. Fresnel Function</strong></h3><p>The Fresnel Function is a function that calculates the refraction of light on an ideal optically flat surface.</p><p>There are two factors that affect the Fresnel Function:<br>- Incoming Angle<br>- Refractive Index of the Material</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNa-UzO1WBSY65LJGuKDGQ.png" /><figcaption>[Figure 1] Schlick Fresnel model</figcaption></figure><p>Figure 1 shows the function of the Schlick Fresnel model, a representative Fresnel function. The parameters consist of , , and .</p><p>represents the refractive characteristic index as shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6bvcEUkf1dwNvmkMJ3Dxg.png" /><figcaption>[Figure 2] F0 values ​​of various materials</figcaption></figure><p>Various real-world materials have different refractive indices. However, since it is not realistic to reflect all of these values ​​in 3D simulations, a few representative materials are selectively chosen and utilized; Figure 2 is an example of this.</p><p>The refractive index of each material represents ‘how much the surface reflects’ for each primary color: Red, Green, and Blue.</p><p>To understand the meaning of the values, apply F0 to the function in Figure 1, and when the angles from 0 to 45 degrees are marked in green, from 45 degrees to 75 degrees in yellow, and above that in red, the surface of the object is as shown in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTnDwzteb-zAQs9fv6CfNQ.png" /><figcaption>[Figure 3] Example of applying Schlick Fresnel to v and n</figcaption></figure><p>Figure 3 is an example of applying Schlick Fresnel to v, the View Vector (from the camera to the object surface), and n, the object surface normal vector, to determine the characteristics of the function and F0.</p><p>Looking at the graph on the left side of Figure 3, the value of all materials behaves almost like a constant function from approximately 0 to 45 degrees. However, from 45 to 75 degrees, the value begins to change significantly, and after 75 degrees, it rapidly approaches 1.</p><p>If we look at this together with the central figure in Figure 3, the closer the angle of incidence between the light and the object surface (corresponding to the Angle of incidence in Figure 4) is to 0 degrees, the more perpendicularly the light approaches the object, and the closer it is to 90 degrees, the more it passes by the object surface at an angle, brushing against it.</p><p>However, you can notice something strange in the graph on the left side of Figure 3: all light is fully reflected only when the angle of incidence is 90 degrees. In refraction, there are concepts of critical angle and total internal reflection, as shown in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*r_p2I_meHtDn0SmbPgC0iQ.png" /><figcaption>[Figure 4] Critical angle and total internal reflection</figcaption></figure><p>Total internal reflection refers to the phenomenon where, when the angle of incidence exceeds a certain angle, light enters the interior of an object from that point onward without being refracted and is entirely reflected from the surface.</p><p>Total internal reflection occurs when light approaches a material of lower density from a medium of higher density. However, the environment assumed by Schlick Fresnel involves light entering a material of higher density (an object) from a low-density environment (air), so total internal reflection does not occur. This is why a graph like the one on the left side of Figure 3 was obtained.</p><p>In addition, the concept of Specular Color is associated with the Fresnel Function. Looking at Figure 2, iron reflects 0.56 units of Red, 0.57 units of Green, and 0.58 units of Blue directly from its surface in the Linear region. If this is applied to the Schlick-Fresnel, iron first reflects approximately 0.5 units of light from its surface, and the remainder enters the interior of the iron. In Figure 5, iron is represented by a gray line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7kdY0-SEImgJGbXqVE4ZQ.png" /><figcaption>[Figure 5] Details of Schlick Fresnel reflectance graphs for each material</figcaption></figure><p>In most cases, the light that reaches our eyes after reflecting off the surface of an object we observe is relatively closer to 0 degrees than to 90 degrees. In particular, since the reflectance is close to a constant from 0 to 45 degrees, light reflected from the object’s surface reaches the eyes, and because this is a model that calculates the refraction rule for each color channel of Schlick-Fresnel RGB, this can also be interpreted as color.</p><p>In other words, F0 also refers to a part of the color of the object’s surface. This color is called Specular Color, meaning it is a color expressed through direct reflection of light (Specular Light).</p><p>Of course, in BRDF PBR, the color of an object’s surface is determined by a combination of Specular Color, Diffuse Color, and Albedo. However, as mentioned in the <a href="https://medium.com/more-deeper-c-programming-language/brdf-pbr-0-basic-68d4732bbeda">previous post</a>, since diffuse light does not exist for metal objects which are conductors, determining the correct F0 that determines Specular Color is important. Diffuse Color corresponds to Sub-Surface Reflection, and generally, a Lambertian model as shown in Figure 6 is applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*kIsHBLM0IY1d8Hbi.gif" /><figcaption>[Figure 6] Lambertian model</figcaption></figure><p>The Lambertian model is generally expressed as B = (L * N)CI. L is the light direction vector, and N is the surface normal vector. Additionally, C represents the diffuse color, and I represents the light intensity. Interpreting the formula, it means that the brightness is more intense as light approaches the surface perpendicularly, and decreases as it approaches perpendicularly. In this process, the diffuse color becomes embedded in the surface brightness.</p><p>In this case, assuming that L and N are each normalized, the inner product of the two vectors is equivalent to the Cosine operation.</p><p>In Unity, which is widely used in the industry, F0 is used as shown in Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*dW9HYralzJ3YxFY1DWMLGw.png" /><figcaption>[Figure 7] Inspector screen of Standard Material applying BRDF PBR in Unity</figcaption></figure><p>Unity’s official manual for interpreting Figure 7 is as shown in Figure 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_YytugvmWD1X7kLsbcQYQ.png" /><figcaption>[Figure 8] Unity Standard Shader Albedo, Metallic, Smoothness Manual</figcaption></figure><p>Unity follows the Metallic-Roughness workflow, so it calculates Specular Color and Diffuse Color by substituting them as shown in Table 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r97I_xdv6gf3nh6WIruksg.png" /><figcaption>&lt;Table 1&gt; Relationship between Metallic-Roughness Workflow and Specular Color, Diffuse Color</figcaption></figure><p>In Figure 3, we previously examined an example of applying the Schlick Fresnel to v and n to understand the Fresnel Function. However, in practice, as shown in the example in Figure 9, l and h are used instead of v and n. This is obvious because using v implies that the position of the light source is the same as the position of the camera, which is a situation not generally assumed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPKcMZk_01_MUK-p2EJGdQ.png" /><figcaption>[Figure 9] Example of applying Schlick Fresnel to l and h</figcaption></figure><p>l represents the vector from the light source to the object surface. h represents the surface normal vector, similar to n. However, while n represents the true normal vector at each point on the object surface, h points to the midpoint between l and v.</p><p>The reason for doing this is that the surface assumed by BRDF PBR is a microfacet, which is macroscopically smooth but microscopically rough, and the normals for each curvature (the normal at the microfacet level is denoted as m) face in different directions. However, for light to strike the surface and be captured by the camera, the condition (m = h) must be satisfied.</p><p>This h is calculated solely by l and v, and becomes a vector completely different from n depending on the position of the camera or light source (n != h).</p><p>To summarize, the moment when n and h coincide is the moment when m and h coincide, and when viewed from the camera position and the light source position at that moment, the Specular Hilight appears brightest on the surface of the object as shown in Figure 9.</p><p>If this is applied to an actual Fresnel function, it is organized as shown in Figure 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaIXsaMSmfTsmUYvmzfXDg.png" /><figcaption>[Figure 10] Schlick Fresnel for l and h</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=077b3e50a751" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/brdf-pbr-1-fresnel-function-077b3e50a751">BRDF(Bidirectional Reflectance Distribution Function) PBR(Physically Based Rendering) — 1.</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BRDF(Bidirectional Reflectance Distribution Function) PBR(Physically Based Rendering) — 0. Basic]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/brdf-pbr-0-basic-68d4732bbeda?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/68d4732bbeda</guid>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[brdf]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 03:40:47 GMT</pubDate>
            <atom:updated>2026-04-08T12:13:12.094Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. BRDF (Bidirectional Reflectance Distribution Function) PBR (Physically Based Rendering) data investigation</h3><p>The purpose of PBR is to compute photorealistic light and surface reflections based on physics on 3D programs. However, due to these characteristics, PBR is expensive and is a burdensome technology for applications requiring real-time high-performance computing, such as games.</p><p>The factors considered in PBR are as follows:<br>- Subsurface Scattering<br>- Fresnel degree of the medium</p><p>First, subsurface scattering refers to the phenomenon where, when light comes into contact with an object, some of it is immediately reflected, while others penetrate into the object and cause scattering within. The form of scattering that occurs inside an object due to subsurface scattering is related to whether the object is a conductor. Figure 1 illustrates the actual interaction between light and conductors and insulators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3TQi1BFpQpW361STetc0Q.png" /><figcaption>[Figure 1] Interaction of light between conductors (left) and insulators (right)</figcaption></figure><h4>1.1. When Subsurface Scattering is applied to a conductor</h4><p>In the case of conductors, the free electrons inside immediately absorb the energy of light that enters the object. Therefore, in the case of a perfect conductor, only pure direct reflected light exists.</p><h4>1.2. When Subsurface Scattering is applied to an insulator</h4><p>In the case of insulators, light interacts with internal atoms and bends, resulting in a mixture of light trapped inside and light escaping back to the outside of the object. Consequently, in the case of insulators, in addition to specular light, diffuse light that passes through the object and bounces back exists. Figure 2 illustrates the distinction between specular and diffuse light in the interaction between an insulator and light.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxEmSkbOQZvbx6B9Mzhz8Q.png" /><figcaption>[Figure 2] Direct reflection and diffuse reflection</figcaption></figure><h4>1.3. The relationship between light operations and pixels</h4><p>Figure 3 shows a simplified model of the interaction between light and objects shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBuzHlU7Df0DVrKJJUnMAw.png" /><figcaption>[Figure 3] Interaction between a simplified object and light. (Top left) When the pixel size is larger than the range of light traveling through the object, (Top right) in this case, it is acceptable to assume that all direct and diffuse reflections occur at the point where the light meets the object. (Bottom) However, when the pixel size is smaller than the range of light traveling through the object, simplification is impossible.</figcaption></figure><p>Since BRDF PBR is ultimately intended for use in 3D applications, the relationship between light calculations and the final pixel must be considered.</p><p>If the range of light moving inside an object is larger than the size of a single pixel, as shown in the top left of Figure 3, the actual location where diffuse light penetrates the surface may differ. However, since this occurs on a scale smaller than a single pixel, these subtle positional differences can be ignored, and calculations can be performed based on the point where the light first meets the object without affecting the result.</p><p>However, if the range of light moving inside an object is smaller than the size of a single pixel, as shown in the bottom of Figure 3, the light calculation applied to that pixel affects other pixels as well, making it difficult to perform a simplified approach.</p><p>In many cases, realistic processing for scenarios like the bottom of Figure 3 entails significant computation. Therefore, if a more lightweight lighting is implemented, a simplified model is applied in all cases, whereas if realistic lighting is implemented, models are applied separately for each case.</p><h4>1.4. <strong>Microfacet</strong></h4><p>BRDF PBR is based on Microfacet theory.</p><p>The basic assumptions of microfacets are as follows:<br>- Surface inhomogeneities are smaller than the observable scale<br>- However, surface inhomogeneities are larger than the scale at which visible light interacts sufficiently</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1ta6i3wzzDtwkXatHOm8g.png" /><figcaption>[Figure 4] Shadows at the microfacet level (left), light calculations ignored (center), and light paths in reality (right)</figcaption></figure><p>Generally, BRDF PBR assumes only a single reflection of light. In reality, even in environments where light can be seen through multiple reflections as shown on the right side of Figure 4, if it cannot be seen through a single reflection, it is ignored to reduce computational complexity. Reflecting multiple light reflections exists as a different technique called Ray-Tracing.</p><h4>1.5. BRDF PBR formula</h4><p>BRDF is a technique used to overcome the cost burden of PBR and is widely used in applications that must process tens to hundreds of frames per second, such as actual games. Therefore, the formula in Figure 5 also takes lightweighting into significant consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*BSiypGfhgL7NHp0JYmNWOw.png" /><figcaption>[Figure 5] BRDF PBR Formula</figcaption></figure><p>f(l,v) takes l (Light Direction) and v (View Direction) at a microfacet scale and calculates the brightness at that location.</p><p>The main components constituting the formula consist of F(l, h), G(l, v, h), D(h), and 4(n*l)(n*v). The parameters l, v, h, and n used can be seen in Figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLlQS-5X-om2QdLyfE6e2w.png" /><figcaption>[Figure 6] Components of BRDF PBR operation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iAVL84UxuXNGI1pF2CByA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d4732bbeda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/brdf-pbr-0-basic-68d4732bbeda">BRDF(Bidirectional Reflectance Distribution Function) PBR(Physically Based Rendering) — 0. Basic</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ — Basic of function overload]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/c-basic-of-function-overload-97463be11f80?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/97463be11f80</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[basics-of-programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[overload]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 11:06:21 GMT</pubDate>
            <atom:updated>2024-07-09T11:11:06.945Z</atom:updated>
            <content:encoded><![CDATA[<h3>C++ — Basic of function overload</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*dv5C_63vxqv8aLbmxvekQA.png" /></figure><h3>What is function overload</h3><p>Function overload refers to overwriting without any commonality other than the name of the function</p><p>This concept can be confused with function override, which refers to the derivation class redefining the virtual function of the underlying class</p><h3>Overload Resolution</h3><p>If it turns out to be one of the overloaded functions when the function is called, the following procedure must be used to determine which of all overload functions is most appropriate: This is called overload resolution</p><ul><li>An exact match was found.</li><li>A trivial conversion was performed.</li><li>An integral promotion was performed.</li><li>A standard conversion to the desired argument type exists.</li><li>A user-defined conversion (either a conversion operator or a constructor) to the desired argument type exists.</li><li>Arguments represented by an ellipsis were found.</li></ul><p>If more than one match is found at the highest level where the match is found, the call is judged to be ambiguous and is not compiled</p><p>If you would like to learn more about trivial conversion and integral promotion, please refer to the following link:</p><ul><li><a href="https://learn.microsoft.com/cpp/cpp/function-overloading?view=msvc-170#:~:text=after%20the%20table.-,Trivial%20conversions,-Expand%20table&amp;wt.mc_id=studentamb_385375">Function Overloading</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/function-overloading?view=msvc-170#:~:text=Match%20using%20promotions.%20Any,match%20using%20standard%20conversions&amp;wt.mc_id=studentamb_385375">Function Overloading</a></li></ul><p>A brief description of each of the trivial conversion and integral promotion is as follows:</p><p><strong>trivial conversion</strong> — with array name as pointer, function name as pointer to function, and T as constT</p><p><strong>integral promotion</strong> — from bol to int, char to int, short to int, signed integer to unsigned integer</p><h3>Overload and Return Type</h3><p>The return type of the function is not considered in the overload resolution</p><h3>Overload and Valid Scope</h3><p>Overload occurs between members of the overload set</p><p>This means that a function of a single effective range, i.e., a function declared in a non-namespace effective range, is not overloaded</p><pre>void f(int)<br>{<br>    std::cout &lt;&lt; &quot;f(int)&quot; &lt;&lt; std::endl;<br>}<br>namespace Sample<br>{<br>    void f(double)<br>    {<br>        std::cout &lt;&lt; &quot;f(double)&quot; &lt;&lt; std::endl;<br>    }<br>    void Test()<br>    {<br>        f(1); // calls f(double)<br>    }<br>}</pre><p>In other words, the concept of function overload does not apply in the case of the above example</p><h3>Materials recommended to read</h3><ul><li><a href="https://learn.microsoft.com/cpp/cpp/functions-cpp?view=msvc-170&amp;wt.mc_id=studentamb_385375">Functions (C++)</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/function-overloading?view=msvc-170&amp;wt.mc_id=studentamb_385375">Function Overloading</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/functions-with-variable-argument-lists-cpp?view=msvc-170&amp;wt.mc_id=studentamb_385375">Functions with Variable Argument Lists (C++)</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/argument-dependent-name-koenig-lookup-on-functions?view=msvc-170&amp;wt.mc_id=studentamb_385375">Argument-Dependent Name (Koenig) Lookup on Functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97463be11f80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/c-basic-of-function-overload-97463be11f80">C++ — Basic of function overload</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you need to know more deeper about programming languages]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/why-you-need-to-know-more-deeper-about-programming-languages-ef8d437522c7?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/ef8d437522c7</guid>
            <category><![CDATA[deeper]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[why]]></category>
            <category><![CDATA[know]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 19:26:03 GMT</pubDate>
            <atom:updated>2024-07-09T11:12:37.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why you need to know more about programming languages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSfzmaMPdzsz0-zsOM667w.png" /></figure><p>After all, the operation of a program is just a continuation of reading or changing the value of a memory or auxiliary storage device. However, by putting a little restriction on it, the rules are set and controlled</p><p>Even the things we call programs, when eventually executed by the OS, are simply receiving a certain amount of memory space available as a process and manipulating the values of memory within that area<br>However, it will not be easy to create an assembly using a few registers, which are tools that programmers can use to manipulate memory at the process level, to identify various factors to consider, including all processors, memory size, number and size of registers</p><p>Therefore, we leave it to the compiler to handle these assemblies, and we organize programs by addressing the concept of abstracted, more imaginable, and manageable variables rather than dealing with registers, which are direct hands and feet when manipulating memory</p><p>In other words, the tool we deal with is technically part of the memory chunk reserved for the process, and by specifying a name identifier, it makes it more convenient for people to think about problems by allowing them to refer to identifiers instead of directly to memory at the programmer level</p><p>The publication in which this article is written is about C++, so I will explain it with examples based on C++</p><p>Value is a broad concept that deals with a lot of things, and to put it simply, a variable is just a subset of values. And expression refers to a statement that calculates these values as operands and various custom operators, including “Built-In Operator”, as operators</p><p>Next, [1.4. Value Category], but to explain the feeling a little bit earlier, if you look closely at the relationship between values, variables, and expressions defined in the C++ standard, the definition of values and expressions itself is a little more complex and difficult to understand compared to the standard of variable parts</p><p>For example, when we’re dealing with variables, unless we’re writing a very sensitive code, we’ve only got to care about general technical issues, such as type, identifier, casting, algorithm, architecture, etc. In other words, the concept of what we see as superficial in the code itself is very intuitive, and even the transformation (typically type casting) between those concepts is defined with a little explanation and understandable rules</p><p>However, it does not feel intuitive that the transformation between the values responsible for the inner behavior of the apparent code and the detailed concepts and concepts of the expression</p><p>Of course, the precise standard definition of these detailed values and expressions tends to be information for compiler makers or producers, but knowing the concept and behavior of these detailed terms can help a lot with debugging and optimization</p><p>For example, the following are the cases:</p><pre>int main()<br>{<br>    int arr[] = {, 0, 1, 2};<br><br>    return 0;<br>}</pre><p>Let’s say there is a code like this. If you want to compile it, the compiler returns the following error message:</p><pre>error: expected primary-expression before &#39;,&#39; token<br>   11 | int arr[] = {, 0, 1, 2};<br>      |              ^</pre><p>To solve the problem, of course, you can google it simply, but to quickly solve the problem with your pure knowledge, you need to know the terms in the error message first</p><p>In other words, the error message given by the compiler in this situation suggests that there should be a primary-expression before the ‘,’ token, and to understand this sentence, you need to know the term primary-expression among the categories of expressions defined in the C++ standard</p><p>There is another example</p><pre>#include &lt;iostream&gt;<br><br>int main()<br>{<br>    int num = 0;<br>    int&amp;&amp; rf_1 = num++;    // Fine<br>    //int&amp;&amp; rf_2 = ++num;  // Error : Cannot bind rValue references to lValue<br><br>    return 0;<br>}</pre><p>Let’s say there’s a code like this. It’s a very simple matter of incremental operators. You see a Declarator called ‘&amp;&amp;’, which you’ll see in [2. Memory, Pointers and Reference], but just to put it simply, it’s the Declarator used to create a reference variable that references rValue. To understand these codes properly when faced, and to write them, you’ll need to know about prValue, glValue, rValue, xValue, and lValue among the categories of values defined in the C++ standard, and you’ll also need to know about the transformation rules between the categories of these values</p><p>Of course, C++ deals with simple variables, i.e., objects, and there are many things that can be these objects beyond just variables, such as structures, enumeration, classes, and functions. However, since these must eventually include variables, which are the most basic elements, you will be able to gain a deeper understanding of C++ by first knowing the values of variables and the behavior of expressions, and then moving on to the values and expressions related to each concept in future rounds</p><p>And this fact is not limited to C++; it is also true of C#, Python, Java, and Rust. Therefore, in many ways, it will be good to examine and study deeply when learning any programming language</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8d437522c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/why-you-need-to-know-more-deeper-about-programming-languages-ef8d437522c7">Why you need to know more deeper about programming languages</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ — Tips for applying inline in Visual Studio]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/c-tips-for-applying-inline-in-visual-studio-f74e700528ae?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/f74e700528ae</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[inline-functions]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 16:31:49 GMT</pubDate>
            <atom:updated>2024-07-09T11:18:12.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>C++ — Tips for applying inline in Visual Studio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*85MeZTkrxSwGJHMs1CLryQ.png" /></figure><h3>Select an inline function</h3><p>In the case of MSVC, the function to be expanded in-line is selected through the following process</p><ol><li><strong>Check Build Options</strong></li><li><strong>Navigating functions for which inline extension is requested</strong></li><li><strong>Perform cost-benefit analysis</strong></li></ol><p>A closer look at each step is as follows:</p><h4>1. Check Build Options</h4><p><strong>1.1. inline function extension options:</strong></p><ul><li>Request to inline expansion : <em>/Ob{1/2/3}</em></li><li>Request to ban inline expansion : <em>/Ob0</em></li></ul><p><strong>1.2. Optimization options:</strong></p><ul><li>Request to inline expansion : <em>/O{1/2/x}</em> = Apply <em>/Ob2</em></li><li>Request to ban inline expansion : <em>/Od</em></li></ul><h4>2. Navigating functions for which inline extension is requested</h4><p><strong>2.1. Specifier</strong></p><ul><li>Request to inline expansion : <em>inline, _inline, __inline, _forceinline, __forceinline</em></li><li>Request to ban inline expansion : <em>__declspec(noinline)</em></li></ul><p><strong>2.2. Attribute</strong></p><ul><li>Request to inline expansion : <em>[[msvc::forceinline]], [[msvc::forceinline_calls]]</em></li><li>Request to ban inline expansion : <em>[[msvc::noinline]], [[msvc::noinline_calls]]</em></li></ul><p><strong>2.3. Pragma</strong></p><ul><li>Request to inline expansion : <em>#pragma auto_inline(on), #pragma inline_recursion(on)</em></li><li>Request to ban inline expansion : <em>#pragma auto_inline(off), #pragma inline_recursion(off)</em></li></ul><p>Compilers cannot apply inline extensions to functions in the following cases:</p><ul><li>If a function or function caller is compiled into /Ob0</li><li>If a function or function caller uses different types of exception handling</li><li>If the function contains variable argument lists</li><li>If it is not compiled as /Ox, /O1 or /O2</li><li>If the function is recursive and ‘#pragma inline_recursion(on)’ is not set at the same time</li><li>If the function is a virtual function and polymorphism is applied</li><li>When a call is made through a function pointer pointing to a function</li><li>‘naked’, ‘__declspec(noinline)’ specifier declared together</li></ul><p>If the compiler is unable to extend the function declared ‘__forceinline’ in-line, it generates a Level 1 alert, except as follows:</p><ul><li>Compiled to /Od or /Ob0</li><li>It is defined in a library or other type of external source</li></ul><p>The recursive function can only apply the inline extension to the depth specified in ‘#pragmaline_depth’ (up to 255), beyond which the recursive function call is treated as a call to the function instance<br>Whether the inline extension is applied to the recursive function or not is controlled by ‘#pragma inline_recursion’</p><p>As a side note, the constructor is implicitly the subject of an inline extension</p><h4><strong>3. Perform cost-benefit analysis</strong></h4><p>In general, it is expected that online expansion can lead to the following performance improvements:</p><ul><li>Call function (including parameters that place and forward the address of the object in the stack)</li><li>Preserving the caller’s Stack Frame</li><li>Set up a new stack frame</li><li>Return value communication</li><li>Restore previous stack frames</li><li>Return</li><li>Reduce object file Size</li><li>Reduce the number of virtual memory paging</li><li>Reduce instruction</li><li>Increase instruction cache hit rate</li></ul><p>However, online expansion is expected to cause the following performance degradation if abused:</p><ul><li>Increase object file size</li><li>Increase the number of virtual memory paging</li><li>Decrease instruction cache hit rate</li></ul><p>Most of these performance improvements/decreases will be skewed to either side at the assembly level, when the code made for the body of the function inline is shorter than the code made for the typical function call</p><p>Cost-benefit analysis takes the above factors into account comprehensively through static analysis and applies the inline extension to the function only when the corresponding inline extension is expected to cause performance improvement</p><h4>Summury of select an inline function</h4><p>‘inline’ and ‘__inline’ specifier ask the compiler to insert a copy of the body of the function at each location where the function is called. The key here is that this is just a request, so the compiler can ignore the request as much as possible, and the function being inline does not completely decompose the function itself, but rather uses a copy of the body of the function, so the original function itself remains the same</p><p>For MSVC, inline expansion only accepts inline requests when it is deemed to be a cost-benefit through cost-benefit analysis</p><p>Of course, if you don’t like this cost-benefit analysis of MSVC, you can ignore the cost-benefit analysis process with ‘__forceinline’ specifier<br>However, even if the cost-benefit analysis process is skipped, it is not necessarily guaranteed that inline expansion will be applied</p><p>And none of those functions can be inline when the /clr compilation option is applied on MSVC<br>In addition, ‘_inline’ and ‘_forceinline’ are synonymous with ‘__inline’ and ‘__forceinline’, respectively, unless you specify the compiler option /Za (do not use language extensions) for compatibility with earlier versions</p><h3>Apply inline extension</h3><p>Once the application of the inline extension is confirmed, the inline extension is applied slightly differently depending on whether the function is a recursive function</p><p>If a function whose inline extension is confirmed is not a recursive function, a copy of the body of the function is inserted into the calling position of the function</p><p>However, if the function confirmed to apply the inline extension is a recursive function, the inline extension can only be applied to a certain depth according to ‘#pragma inline_depth( [n])’ and beyond that, a typical function call is applied<br>The default value for ‘#pragmaline_depth([n])’ is 16, and n can be set from 0 to 255<br>That is, if there is a recursive call beyond inline_depth, the inline extension may be applied as follows:</p><pre>inline int GetFac(const int n)<br>{<br>    return (n &gt; 2) ? n * GetFac(n - 1) : n;<br>}</pre><p>If there is “GetFac(int)” as in the code above, and “GetFac(6)” is called, there is a possibility that it will be handled as follows:</p><h4>If the recursive depth within the function is less than or equal to line_depth</h4><p>In this case, instead of calling the function of “GetFac(6)”, there is a possibility that the calculated “720” will be inserted in Compile Time</p><h4>If the recursive depth within the function is greater than line_depth</h4><p>In this case, instead of calling the function of “GetFac(6), there is a possibility that the result calculated in Compile Time, such as “6 * GetFac(5)”, is only almost halfway calculated</p><h3>Materials recommended to read</h3><ul><li><a href="https://learn.microsoft.com/cpp/cpp/inline-functions-cpp?view=msvc-170&amp;wt.mc_id=studentamb_385375">Inline Functions (C++)</a></li><li><a href="https://learn.microsoft.com/cpp/build/reference/ob-inline-function-expansion?view=msvc-170&amp;wt.mc_id=studentamb_385375">/Ob (Inline Function Expansion)</a></li><li><a href="https://learn.microsoft.com/cpp/build/reference/ox-full-optimization?view=msvc-170&amp;wt.mc_id=studentamb_385375">/Ox (Enable Most Speed Optimizations)</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/attributes?view=msvc-170#:~:text=must%20manage%20manually.-,%5B%5Bmsvc%3A%3Aforceinline%5D%5D,-When%20placed%20before&amp;wt.mc_id=studentamb_385375">Attributes in C++</a></li><li><a href="https://learn.microsoft.com/cpp/preprocessor/auto-inline?view=msvc-170&amp;wt.mc_id=studentamb_385375">auto_inline pragma</a></li><li><a href="https://learn.microsoft.com/cpp/preprocessor/inline-recursion?view=msvc-170&amp;wt.mc_id=studentamb_385375">inline_recursion pragma</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/functions-with-variable-argument-lists-cpp?view=msvc-170&amp;wt.mc_id=studentamb_385375">Functions with Variable Argument Lists (C++)</a></li><li><a href="https://devblogs.microsoft.com/oldnewthing/20180625-00/?p=99085?wt.mc_id=studentamb_385375">The cost/benefit analysis of comparing before an assignment - The Old New Thing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f74e700528ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/c-tips-for-applying-inline-in-visual-studio-f74e700528ae">C++ — Tips for applying inline in Visual Studio</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ — Choice for Function Performance Optimization, inline]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/c-choice-for-function-performance-optimization-inline-768bf2a6ca2c?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/768bf2a6ca2c</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[inline-functions]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 15:41:46 GMT</pubDate>
            <atom:updated>2024-07-09T11:16:54.072Z</atom:updated>
            <content:encoded><![CDATA[<h3>C++ — Choice for Function Performance Optimization, inline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*g6kKNS9jRGQqxpUOerDg7g.png" /></figure><h3>What is inline</h3><p>An inline specifier is a word that tells the compiler that a function needs to save the function code once and then try to generate the inline call code rather than call it through a conventional function call mechanism</p><p>At this time, whether a function is an inline function exists in both implicit and explicit ways</p><h3>Advantages and disadvantages of the inline function</h3><p>Let’s look back on what usually happens when you call a function</p><p>First, you must save information about the context of the code you’ve been running before proceeding to another function’s code when you call a function. Only then can you complete all the codes you want to call and return to continue with what you were doing before.<br>As a result, we store information about the context that we were running in the existing function’s Stack Frame. This Stack Frame corresponds to a Stack, which is commonly referred to as Call-Stack, and it can be called differently depending on the operating system. Simply put, a function that has been executed will generate one Stack Frame corresponding to it</p><p>Once you’ve saved the previous context, you’re now starting to read the code for the new function that was called. Naturally, a new Stack Frame will be created, and at a lower level, Jump Instruction will have to be done when you move from one function to another. Depending on what situation that function is in, you might need to pay more. For example, let’s say that the child class took the overloaded virtual functions from the parent class and overridden them. Calling that function will require the process of overloading resolution and the process of deciding whether to call the parent class or child class functions from Virtual-Table</p><p>After processing the called function, it’s time to return to the previous function. You’ll need to remove the Stack Frame of the called function, read the Stack Frame data of the previous function, and return the various registers to the previous situation. This shift of context is called Context-Switch, a process that is briefly described in this post, but is actually more expensive than you can imagine</p><p>In this way, the typical function calls are often performed in the invisible beyond our imagination. This is a cost, which poses a risk of performance and, in the worst case, exceptional exceptions, including the very famous Stackoverflow</p><p>The inline function is one of the optimization techniques to overcome the shortcomings mentioned above. The idea of the inline function is very simple. The large cost described above is essentially incurred to ‘call’ a function. To avoid this, inline pastes the contents of the function you want to call at all to the location where you called it. This eliminates all the necessary processing to call the function. Of course, the result is that it can take a little longer to compile, but it can improve runtime performance</p><h3>Implicict inline</h3><p>In the case of an implicit inline function, if the declaration of the class includes even the complete definition of the function, the function is implicitly designated as an inline function candidate</p><pre>class Person<br>{<br>private:<br>    int m_age;<br><br>public:<br>    int GetAge() const { return m_age; }<br>};</pre><p>For the above example code, Person::GetAge() does not explicitly declare the inline specifier, but it is designated as a candidate for the inline function because the declaration part of the Person class contains a complete definition with the declaration of the method</p><p>Note that it has only become a ‘candidate’ of the inline function and can actually be inline only if all the conditions that can be inline are met additionally</p><h3>Explicit inline</h3><p>In the case of explicit inline functions, if the inline specifier is declared in all functions, it is designated as a candidate for the inline function</p><pre>inline int GetUID(const std::string&amp; name);</pre><p>If an inline specifier is explicitly declared, as in the example code above, the function is designated as a candidate for the inline function</p><p>It is important to note that, as mentioned in implicit inline, it has only become a ‘candidate’ of the inline function and can actually be inline if all the conditions that can be inline are met additionally</p><h3>Conditions for a function to actually be inlined</h3><p>A simple rule in which a function is designated as a candidate for an inline function is as above</p><p>However, for a function nominated for an inline function to actually be inline, that function must satisfy some additional conditions<br>To sum up the conditions, ‘<strong>the slightest complex function will never be inline</strong>’</p><ul><li>The content of the function should not contain a loop, and if it does, it should not be complicated</li><li>It should not take the form of a recursive function, and if it is a recursive function, it should be a shallow recursive function</li><li>Virtual function call (polymorphic) format not taken</li><li>Only one body of a function definition must exist</li><li>All compilation units must be declared in the same way</li></ul><p>In a way, these are very simple conditions. Of course, these conditions may not always apply because they are compiler-dependent</p><p>However, even if a function is designated as an inline candidate and satisfies the above conditions, there may be cases where it is not actually possible even if it is convinced that it must be inline unconditionally</p><pre>inline int GetUID(const std::string&amp; name);<br><br>int (*GetUIDPtr)(const std::string&amp; name) = GetUID;<br><br>void Sample()<br>{<br>    std::string name{&quot;John&quot;};<br><br>    GetUID(name);<br><br>    GetUIDPtr(name);<br>}</pre><p>Suppose that in the above example code, “inline int GetUID(conststd:string&amp;name)” is definitely an inline function<br>In that case, “GetUID(name);” is definitely inline, but “GetUIDPtr(name)” is definitely not inline</p><p>The difference is simple: functions called through a function pointer that takes the address of an inline function are not inline<br>The reason is also very simple if you think about it a little bit, but an inline function is to paste the body of a function into the part where the function is called. In other words, the form of the function disappears, and only the body remains. But how can a function pointer get a function pointer when there is only the body</p><p>It might be naive to see this result and think that you just have to make sure that you are not the only one calling through the function pointer of the inline function.<br>This is because, among the vast mechanisms and libraries of C++, there are more things that a user-defined function points to and processes with a function pointer regardless of whether it is an inline function or not</p><p>Also, the caveat when inline is that debugging can become difficult<br>Obviously I’d like to break down the calling part of a function and debug it, but if the calling of that function is inline, how on earth do you break down a function that doesn’t even exist in the end?</p><h3>Conclusion</h3><p>inline is very useful, but the available situations are limited, and its disadvantages are relatively clear. However, if you use it well, it is clearly a good optimization technique. Please try to optimize your program through a lot of research and practice</p><p>If you want to know more about tips on using inline in a visual studio environment, I recommend you to read one of my posts, the following:</p><p><a href="https://medium.com/more-deeper-c-programming-language/c-tips-for-applying-inline-in-visual-studio-f74e700528ae">C++ — Tips for applying inline in Visual Studio</a></p><h3>Materials recommended to read</h3><ul><li><a href="https://learn.microsoft.com/cpp/cpp/inline-functions-cpp?view=msvc-170&amp;wt.mc_id=studentamb_385375">Inline Functions (C++)</a></li><li><a href="https://learn.microsoft.com/cpp/build/reference/ob-inline-function-expansion?view=msvc-170&amp;wt.mc_id=studentamb_385375">/Ob (Inline Function Expansion)</a></li><li><a href="https://learn.microsoft.com/cpp/build/reference/ox-full-optimization?view=msvc-170&amp;wt.mc_id=studentamb_385375">/Ox (Enable Most Speed Optimizations)</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/attributes?view=msvc-170#:~:text=must%20manage%20manually.-,%5B%5Bmsvc%3A%3Aforceinline%5D%5D,-When%20placed%20before&amp;wt.mc_id=studentamb_385375">Attributes in C++</a></li><li><a href="https://learn.microsoft.com/cpp/preprocessor/auto-inline?view=msvc-170&amp;wt.mc_id=studentamb_385375">auto_inline pragma</a></li><li><a href="https://learn.microsoft.com/cpp/preprocessor/inline-recursion?view=msvc-170&amp;wt.mc_id=studentamb_385375">inline_recursion pragma</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/functions-with-variable-argument-lists-cpp?view=msvc-170&amp;wt.mc_id=studentamb_385375">Functions with Variable Argument Lists (C++)</a></li><li><a href="https://devblogs.microsoft.com/oldnewthing/20180625-00/?p=99085?wt.mc_id=studentamb_385375">The cost/benefit analysis of comparing before an assignment - The Old New Thing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=768bf2a6ca2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/c-choice-for-function-performance-optimization-inline-768bf2a6ca2c">C++ — Choice for Function Performance Optimization, inline</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[More Deeper C++ Programming Language]—Introduction & Notice & References]]></title>
            <link>https://medium.com/more-deeper-c-programming-language/more-deeper-c-programming-language-introduction-notice-references-4643808bde75?source=rss----bb2aacb21981---4</link>
            <guid isPermaLink="false">https://medium.com/p/4643808bde75</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[notice]]></category>
            <category><![CDATA[deep]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[HyunsuYu]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 08:50:47 GMT</pubDate>
            <atom:updated>2024-07-09T11:19:44.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*ymgFR7JsecDUp2mGxmyUvA.png" /></figure><h3>1. Introduction</h3><p>Learning a programming language is not easy</p><p>But rather than learning the grammar of language, it’s more difficult to identify and learn the issues that are related to language — what happens behind the language, what happens with hardware, what happens in certain situations, what you don’t expect easily, what optimization techniques are there and how to use them</p><p>“More Deeper C++ Programming Language” seeks to convey deeper knowledge about C++ programming languages. It is an accurate and in-depth study of the ISO/IEC standard, AMD64 Architecture Manual, and other books and papers</p><h3>2. Notice</h3><blockquote>This document aims to explore and organize the content of C++ in more depth and share it with the public from various perspectives based on the grammar and various documents specified in the standard</blockquote><blockquote>Replicating this document for non-profit purposes is acceptable.</blockquote><blockquote>Please note that some of the contents of the document may be wrong</blockquote><h3>3. References</h3><ul><li><a href="https://www.iso.org/standard/38110.html">ISO/IEC 14882:2003 Programming languages — C++</a></li><li><a href="https://www.amd.com/content/dam/amd/en/documents/processor-tech-docs/programmer-references/24592.pdf">AMD64 Architecture Programmer’s Manual 1 : Application Programming</a></li><li><a href="https://www.amd.com/content/dam/amd/en/documents/processor-tech-docs/programmer-references/24593.pdf">AMD64 Architecture Programmer’s Manual 2 : System Programming</a></li><li><a href="https://www.amazon.com/C-Programming-Language-4th/dp/0321563840">The C++ Programming Language — 4th Edition</a></li><li><a href="https://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876">Effective C++</a></li><li><a href="https://www.amazon.com/Effective-Modern-Specific-Ways-Improve/dp/1491903996">Effective Modern C++</a></li><li><a href="https://learn.microsoft.com/cpp/cpp/?view=msvc-170&amp;wt.mc_id=studentamb_385375">MicroSoft Developer Network(MSDN)</a></li><li><a href="https://www.amazon.com/Structure-Interpretation-Computer-Programs-Engineering/dp/0262510871">Structure and Interpretation of Computer Programs — 2nd Edition</a></li><li><a href="https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670">Code Complete — 2nd Edition</a></li><li><a href="https://users.ece.cmu.edu/~omutlu/pub/mph_usenix_security07.pdf">Memory Performance Attacks : Denial of Memory Service in Multi-Core Systems — Paper</a></li><li><a href="https://www.usenix.org/legacy/event/atc11/tech/final_files/Blagodurov.pdf">A Case for NUMA-aware Contention Management on Multicore Systems — Paper</a></li><li><a href="https://web.archive.org/web/20170921235928id_/http://people.inf.ethz.ch/zmajo/publications/11-systor.pdf">Memory System Performance in a NUMA Multicore Multiprocessor — Paper</a></li><li>etc…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4643808bde75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/more-deeper-c-programming-language/more-deeper-c-programming-language-introduction-notice-references-4643808bde75">[More Deeper C++ Programming Language]—Introduction &amp; Notice &amp; References</a> was originally published in <a href="https://medium.com/more-deeper-c-programming-language">More Deeper Rendering &amp; C++ Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>